Are you sure you want to delete this record?

This action can't be undone!

        {!! $additionalMessage !!}

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="do-delete">Delete</button>

Are you sure you want to delete this record?

This action can't be undone!

        {!! $additionalMessage ?? "" !!}

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="do-delete">Delete</button>

Fix list of posts breaking

Fix list of posts breaking


<?php
function imc_parse_text($str,$obj){
  preg_match_all("|%(.*)%|U", $str, $match, PREG_PATTERN_ORDER);
  foreach($match[1] AS $field){
    if(!isset($obj[$field])){
      echo '
ParseError: Field '.$field.' not found on object '.get_class($obj).".
";
      $str = str_replace('%'.$field.'%','',$str);
    }else{
      $str = str_replace('%'.$field.'%',$obj[$field],$str);
    }
  }

  preg_match_all("|#(.*)#|U", $str, $match, PREG_PATTERN_ORDER);
  foreach($match[1] AS $function){
    $str = str_replace('#'.$function.'#',$obj->$function(),$str);
  }

  return html_entity_decode($str);
}

<?php
function imc_parse_text($str,$obj){
  preg_match_all("|%(.*)%|U", $str, $match, PREG_PATTERN_ORDER);
  foreach($match[1] AS $field){
    if(!isset($obj[$field])){
      echo '
ParseError: Field '.$field.' not found on object '.get_class($obj).".
";
      $str = str_replace('%'.$field.'%','',$str);
    }else{
      $str = str_replace('%'.$field.'%',$obj[$field],$str);
    }
  }

  preg_match_all("|#(.*)#|U", $str, $match, PREG_PATTERN_ORDER);
  foreach($match[1] AS $function){
    if(!is_null($obj->$function()->__toString()))
      $str = str_replace('#'.$function.'#',$obj->$function(),$str);
    else
      $str = str_replace('#'.$function.'#','',$str);
  }

  return html_entity_decode($str);
}

Fix Catchable fatal error en objetos null al llamar a __toString()


<?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\Security\Http\Tests\Authenticator\Fixtures;

use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class PasswordUpgraderProvider extends InMemoryUserProvider implements PasswordUpgraderInterface
{
    public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
    {
    }
}

<?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\Security\Http\Tests\Authenticator\Fixtures;

use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class PasswordUpgraderProvider extends InMemoryUserProvider implements PasswordUpgraderInterface
{
    public function upgradePassword($user, string $newHashedPassword): void
    {
    }
}

Prepare PasswordUpgraderInterface implementations for 6.0 signatures


{{ Form::label('first_name', 'First Name') }}
  {{ form_error('first_name', $errors) }}
  {{ Form::text('first_name', null, ['placeholder' => 'What\'s your name?']) }}

  {{ Form::label('birthdate', 'Birthdate') }}
  {{ form_error('birthdate', $errors) }}
  {{ Form::text('birthdate',  null, ['placeholder' => 'MM/DD/YYYY']) }}

  @if(get_login_type() == 'email')
    {{ Form::label('email', 'Email') }}
    {{ form_error('email', $errors) }}
    {{ Form::text('email', null, ['placeholder' => 'you@example.com']) }}
  @else
    {{ Form::label('phone', 'Cell Number') }}
    {{ form_error('phone', $errors) }}
    {{ Form::text('phone', null, ['placeholder' => '555-555-5555']) }}
  @endif

    {{ Form::checkbox('opt_in', null, true) }}

    Yes, send me updates from DoSomething.org

Add opt-in checkbox to session form.

Add opt-in checkbox to session form.


<?php
class Kwf_Update_20150728Legacy38017 extends Kwf_Update
{
    protected $_tags = array('kwc');

    public function update()
    {
        //clear all view caches, required for 7a36ae58a
        Kwf_Cache_Simple::getMemcache()->flush();
        Kwf_Registry::get('db')->query('TRUNCATE cache_component');
        Kwf_Registry::get('db')->query('TRUNCATE cache_component_includes');
    }
}

<?php
class Kwf_Update_20150728Legacy38017 extends Kwf_Update
{
    protected $_tags = array('kwc');

    public function update()
    {
        //clear all view caches, required for 7a36ae58a
        Kwf_Component_Cache_Memory::getInstance()->_clean();
        Kwf_Registry::get('db')->query('TRUNCATE cache_component');
        Kwf_Registry::get('db')->query('TRUNCATE cache_component_includes');
    }
}

Fix Update Script: clear view cache correctly if memcache isn't used


<?php

namespace Elastica\Test;

use Elastica\Client;
use Elastica\Document;
use Elastica\Test\Base as BaseTest;

/**
 * Tests the example code
 */
class ExampleTest extends BaseTest
{
    public function testExample()
    {
        // Creates a new index 'xodoa' and a type 'user' inside this index
        $client = $this->_getClient();
        $index = $client->getIndex('elastica_test');
        $index->create(array(), true);

        $type = $index->getType('user');

        // Adds 1 document to the index
        $doc1 = new Document(1,
            array('username' => 'hans', 'test' => array('2', '3', '5'))
        );
        $type->addDocument($doc1);

        // Adds a list of documents with _bulk upload to the index
        $docs = array();
        $docs[] = new Document(2,
            array('username' => 'john', 'test' => array('1', '3', '6'))
        );
        $docs[] = new Document(3,
            array('username' => 'rolf', 'test' => array('2', '3', '7'))
        );
        $type->addDocuments($docs);

        // Refresh index
        $index->refresh();

        $resultSet = $type->search('rolf');
    }
}

<?php

namespace Elastica\Test;

use Elastica\Client;
use Elastica\Document;
use Elastica\Test\Base as BaseTest;

/**
 * Tests the example code
 */
class ExampleTest extends BaseTest
{
	public function testBasicGettingStarted() {

		$client = new \Elastica\Client();
		$index = $client->getIndex('ruflin');
		$type = $index->getType('users');

		$id = 2;
		$data = array('firstname' => 'Nicolas', 'lastname' => 'Ruflin');
		$doc = new \Elastica\Document($id, $data);

		$type->addDocument($doc);

	}

    public function testExample()
    {
        // Creates a new index 'xodoa' and a type 'user' inside this index
        $client = $this->_getClient();
        $index = $client->getIndex('elastica_test');
        $index->create(array(), true);

        $type = $index->getType('user');

        // Adds 1 document to the index
        $doc1 = new Document(1,
            array('username' => 'hans', 'test' => array('2', '3', '5'))
        );
        $type->addDocument($doc1);

        // Adds a list of documents with _bulk upload to the index
        $docs = array();
        $docs[] = new Document(2,
            array('username' => 'john', 'test' => array('1', '3', '6'))
        );
        $docs[] = new Document(3,
            array('username' => 'rolf', 'test' => array('2', '3', '7'))
        );
        $type->addDocuments($docs);

        // Refresh index
        $index->refresh();

        $resultSet = $type->search('rolf');
    }
}

Add basic getting started test

Add basic getting started test


<?php

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

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        Model::unguard();

        $this->call('PtDistrictsTableSeeder');
        $this->call('ItemCategoriesTableSeeder');
        $this->call('VehicleColorsTableSeeder');
        $this->call('VehicleMakesTableSeeder');
        $this->call('VehicleModelsTableSeeder');
        $this->call('VehicleFuelsTableSeeder');
        $this->call('VehicleCategoriesTableSeeder');
        $this->call('VehicleTypesTableSeeder');
    }
}

<?php

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

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

/**
 * This is the database seeder class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        Model::unguard();

        $this->call('PtDistrictsTableSeeder');
        $this->call('PtMunicipalitiesTableSeeder');
        $this->call('ItemCategoriesTableSeeder');
        $this->call('VehicleColorsTableSeeder');
        $this->call('VehicleMakesTableSeeder');
        $this->call('VehicleModelsTableSeeder');
        $this->call('VehicleFuelsTableSeeder');
        $this->call('VehicleCategoriesTableSeeder');
        $this->call('VehicleTypesTableSeeder');
    }
}

Update the main database seeder class

Update the main database seeder class


Update dynamic IFrame size support settings.


<?php namespace duxet\Tests\Realtime\Connections;

use duxet\Realtime\Connections\PubNubConnection;
use duxet\Tests\Realtime\TestCase;
use Mockery;

class PubNubConnectionTest extends TestCase {

    public function testPublish()
    {
        $pubnub = $this->getPubNub()
            ->shouldReceive('publish')
            ->with('channel', 'test')
            ->andReturn([1, 'Sent', 14247819253237675])
            ->mock();

        $connection = $this->getConnection($pubnub);
        $result = $connection->publish('channel', 'test');

        $this->assertTrue($result);
    }

    protected function getConnection($pubnub)
    {
        return new PubNubConnection($pubnub);
    }

    protected function getPubNub()
    {
        return Mockery::mock('Pubnub\Pubnub');
    }

}

<?php namespace duxet\Tests\Realtime\Connections;

use duxet\Realtime\Connections\PubNubConnection;
use duxet\Tests\Realtime\TestCase;
use Mockery;

class PubNubConnectionTest extends TestCase {

    public function testPublish()
    {
        $pubnub = $this->getPubNub()
            ->shouldReceive('publish')
            ->with('channel', 'test')
            ->once()
            ->andReturn([1, 'Sent', 14247819253237675])
            ->mock();

        $connection = $this->getConnection($pubnub);
        $result = $connection->publish('channel', 'test');

        $this->assertTrue($result);
    }

    public function testSubscribe()
    {
        $result = null;
        $closure = function($message) use(&$result)
        {
            $result = $message;
        };

        $pubnub = $this->getPubNub()
            ->shouldReceive('subscribe')
            ->with('channel', Mockery::type('callable'))
            ->andReturnUsing(function($channel, $callback) {
                $callback('test');
            })
            ->once()
            ->mock();

        $connection = $this->getConnection($pubnub);
        $connection->subscribe('channel', $closure);

        $this->assertEquals($result, 'test');
    }

    protected function getConnection($pubnub)
    {
        return new PubNubConnection($pubnub);
    }

    protected function getPubNub()
    {
        return Mockery::mock('Pubnub\Pubnub');
    }

}

Add subscribe() test to PubNub

Add subscribe() test to PubNub


/**
 * Turns an array into an HTML seletion box for use in a form
 * @param $options keys are values for the option elements; values are what gets displayed
 * @param $default if this matches one of the $options keys, that is selected by default
 * @param $id the HTML id and name used for the selection box rendered
 * @return string the rendered HTML
 */
function disp_options(array $options,$default=null,$id='')
{
	if($id!='')
	{
		$id=" id='$id' name='$id'";
	}
	$retval = "<select$id>";
	foreach ($options as $n=>$v)
	{
		$retval.='<option value="'.html_out($n).'"'.($n==$default?' selected':'').'>'.
			html_out($v).'</option>';
	}
	return  $retval."</select>";
}

<?php
/**
 * Turns an array into an HTML seletion box for use in a form
 * @param $options keys are values for the option elements; values are what gets displayed
 * @param $default if this matches one of the $options keys, that is selected by default
 * @param $id the HTML id and name used for the selection box rendered
 * @return string the rendered HTML
 */
function disp_options(array $options,$default=null,$id='')
{
	if($id!='')
		$id=" id='$id' name='$id'";
	$retval = "<select$id>";
	foreach ($options as $n=>$v)
		$retval.='<option value="'.htmlentities($n).'"'.($n==$default?' selected':'').'>'.
			htmlentities($v).'</option>';
	return  $retval."</select>";
}

Make disp_options() definitnion more concise


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Emoji\Listener;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;

class FormatEmoticons
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function addEmoticons(ConfigureFormatter $event)
    {
        $event->configurator->Emoji->useEmojiOne();
        $event->configurator->Emoji->useSVG();

        $event->configurator->Emoji->addAlias(':)', '🙂');
        $event->configurator->Emoji->addAlias(':D', '😃');
        $event->configurator->Emoji->addAlias(':P', '😛');
        $event->configurator->Emoji->addAlias(':(', '🙁');
        $event->configurator->Emoji->addAlias(':|', '😐');
        $event->configurator->Emoji->addAlias(';)', '😉');
        $event->configurator->Emoji->addAlias(':\'(', '😢');
        $event->configurator->Emoji->addAlias(':O', '😮');
        $event->configurator->Emoji->addAlias('>:(', '😡');
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Emoji\Listener;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;

class FormatEmoticons
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function addEmoticons(ConfigureFormatter $event)
    {
        $event->configurator->Emoji->useEmojiOne();
        $event->configurator->Emoji->omitImageSize();
        $event->configurator->Emoji->useSVG();

        $event->configurator->Emoji->addAlias(':)', '🙂');
        $event->configurator->Emoji->addAlias(':D', '😃');
        $event->configurator->Emoji->addAlias(':P', '😛');
        $event->configurator->Emoji->addAlias(':(', '🙁');
        $event->configurator->Emoji->addAlias(':|', '😐');
        $event->configurator->Emoji->addAlias(';)', '😉');
        $event->configurator->Emoji->addAlias(':\'(', '😢');
        $event->configurator->Emoji->addAlias(':O', '😮');
        $event->configurator->Emoji->addAlias('>:(', '😡');
    }
}

Revert omission of image size

Revert omission of image size

Turns out this is still required in SVG mode :D


<?php
namespace AssetManager\Service;

use PHPUnit_Framework_TestCase;

class MimeResolverTest extends PHPUnit_Framework_TestCase
{
    public function testGetMimeType()
    {
        //Fails
        $mimeResolver = new MimeResolver;
        $this->assertEquals('text/plain', $mimeResolver->getMimeType('bacon.porn'));

        //Success
        $this->assertEquals('application/x-httpd-php', $mimeResolver->getMimeType(__FILE__));
    }

    public function testGetExtension()
    {
        $mimeResolver = new MimeResolver;

        $this->assertEquals('css', $mimeResolver->getExtension('text/css'));
        $this->assertEquals('js', $mimeResolver->getExtension('application/javascript'));
    }

    public function testGetUrlMimeType()
    {
        $mimeResolver = new MimeResolver;

        $this->assertEquals('js', $mimeResolver->getMimeType('http://foo.bar/file.js'));
    }
}

<?php
namespace AssetManager\Service;

use PHPUnit_Framework_TestCase;

class MimeResolverTest extends PHPUnit_Framework_TestCase
{
    public function testGetMimeType()
    {
        //Fails
        $mimeResolver = new MimeResolver;
        $this->assertEquals('text/plain', $mimeResolver->getMimeType('bacon.porn'));

        //Success
        $this->assertEquals('application/x-httpd-php', $mimeResolver->getMimeType(__FILE__));
    }

    public function testGetExtension()
    {
        $mimeResolver = new MimeResolver;

        $this->assertEquals('css', $mimeResolver->getExtension('text/css'));
        $this->assertEquals('js', $mimeResolver->getExtension('application/javascript'));
    }

    public function testGetUrlMimeType()
    {
        $mimeResolver = new MimeResolver;

        $this->assertEquals('application/javascript', $mimeResolver->getMimeType('http://foo.bar/file.js'));
    }
}

Check for mime type and not extension

Check for mime type and not extension


<?php

namespace SlmQueueTest\Queue;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;

class QueuePluginManagerTest extends TestCase
{
    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    public function setUp()
    {
        parent::setUp();
        $this->serviceManager = ServiceManagerFactory::getServiceManager();
    }

    public function testCanRetrievePluginManagerWithServiceManager()
    {
        $queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
        $this->assertInstanceOf('SlmQueue\Queue\QueuePluginManager', $queuePluginManager);
    }

    public function testAskingTwiceTheSameQueueReturnsTheSameInstance()
    {
        $queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');

        $firstInstance  = $queuePluginManager->get('basic-queue');
        $secondInstance = $queuePluginManager->get('basic-queue');

        $this->assertSame($firstInstance, $secondInstance);
    }
}

<?php

namespace SlmQueueTest\Queue;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueue\Queue\QueuePluginManager;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;

class QueuePluginManagerTest extends TestCase
{
    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    public function setUp()
    {
        parent::setUp();
        $this->serviceManager = ServiceManagerFactory::getServiceManager();
    }

    public function testCanRetrievePluginManagerWithServiceManager()
    {
        $queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
        $this->assertInstanceOf('SlmQueue\Queue\QueuePluginManager', $queuePluginManager);
    }

    public function testAskingTwiceTheSameQueueReturnsTheSameInstance()
    {
        $queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');

        $firstInstance  = $queuePluginManager->get('basic-queue');
        $secondInstance = $queuePluginManager->get('basic-queue');

        $this->assertSame($firstInstance, $secondInstance);
    }

    public function testPluginValidation()
    {
        $manager = new QueuePluginManager();
        $queue   = new \stdClass();

        $this->setExpectedException('SlmQueue\Queue\Exception\RuntimeException');
        $manager->validatePlugin($queue);
    }
}

Test exception on queue plugin manager validation


<?php
/**
 * Custom translation strings for Cambio Rural
 */
$spanish = array(
				 # 15: change tags to palabras claves
				 'tag'      => 'palabra clave',
				 'tags'     => 'Palabras claves';
				 );

add_translation('es', $spanish);

<?php
/**
 * Custom translation strings for Cambio Rural
 */
$spanish = array(
				 # 15: change tags to palabras claves
				 'tag'      => 'palabra clave',
				 'tags'     => 'Palabras claves',
				 );

add_translation('es', $spanish);

Fix typo and parse error

Fix typo and parse error


<?php

final class PhabricatorFeedDetailController extends PhabricatorFeedController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $id = $request->getURIData('id');

    $story = id(new PhabricatorFeedQuery())
      ->setViewer($viewer)
      ->withChronologicalKeys(array($id))
      ->executeOne();
    if (!$story) {
      return new Aphront404Response();
    }

    if ($request->getStr('text')) {
      $text = $story->renderText();
      return id(new AphrontPlainTextResponse())->setContent($text);
    }

    $feed = array($story);
    $builder = new PhabricatorFeedBuilder($feed);
    $builder->setUser($viewer);
    $feed_view = $builder->buildView();

    $title = pht('Story');

    $feed_view = phutil_tag_div('phabricator-feed-frame', $feed_view);

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb($title);

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $feed_view,
      ),
      array(
        'title' => $title,
      ));
  }

}

<?php

final class PhabricatorFeedDetailController extends PhabricatorFeedController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $id = $request->getURIData('id');

    $story = id(new PhabricatorFeedQuery())
      ->setViewer($viewer)
      ->withChronologicalKeys(array($id))
      ->executeOne();
    if (!$story) {
      return new Aphront404Response();
    }

    if ($request->getStr('text')) {
      $text = $story->renderText();
      return id(new AphrontPlainTextResponse())->setContent($text);
    }

    $feed = array($story);
    $builder = new PhabricatorFeedBuilder($feed);
    $builder->setUser($viewer);
    $feed_view = $builder->buildView();

    $title = pht('Story');

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb($title);

    return $this->newPage()
      ->setTitle($title)
      ->setCrumbs($crumbs)
      ->appendChild($feed_view);
  }

}

Update Feed Story page for newPage

Update Feed Story page for newPage

Summary: Cleans up Feed Story individual page

Test Plan: View an individual story by clicking on date.

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin

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


<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array('data' => array());
        return $result;
    }
}

<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns a project according to the project ID.
 */
class Projects extends \fennecweb\WebService
{
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array('project_id': {biomfile});
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        $project_id = $querydata['id'];
        if (!isset($_SESSION)) {
            session_start();
        }
        $query_get_project_details = <<<EOF
SELECT project FROM full_webuser_data WHERE project->>'id' = :project_id AND provider = :provider AND oauth_id = :oauth_id
EOF;
        $stm_get_project_details = $db->prepare($query_get_project_details);
        $stm_get_project_details->bindValue('project_id', $project_id);
        $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']);
        $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']);
        $stm_get_project_details->execute();

        while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) {
            $result[$project_id] = $row['project'];
        }
        return $result;
    }
}

Implement webservice which returns a project according to the projects id


<?php
// SETS SYSTEM-WIDE CONFIG PREFERNENCES

//Information to access your mysql database
$CC_dbhost = "";
$CC_dbusername = "";
$CC_dbpasswd = "";
$CC_database_name = "";

//Email address for the adminstrator who will deal with student questions
$CC_admin_email = "";

//Url where your Cliniccases installation will be run, e.g. http://www.yourservername.com/yourdirectory/ .  Don't forget trailing slash!
$CC_base_url = "";

//Your domain , e.g. http://www.yourserver.com
$CC_domain = "";

//Default email for ClinicCases notifications, e.g. no-reply@yourserver.com
$CC_default_email = "";

?>

<?php
// SETS SYSTEM-WIDE CONFIG PREFERNENCES

//Information to access your mysql database
$CC_dbhost = "";
$CC_dbusername = "";
$CC_dbpasswd = "";
$CC_database_name = "";

//Email address for the adminstrator who will deal with student questions
$CC_admin_email = "";

//Url where your Cliniccases installation will be run, e.g. http://www.yourservername.com/yourdirectory/ .  Don't forget trailing slash!
$CC_base_url = "";

//Your domain , e.g. http://www.yourserver.com
$CC_domain = "";

//Default email for ClinicCases notifications, e.g. no-reply@yourserver.com
$CC_default_email = "";

//Your Program Name, e.g. "Loyola Law Clinic"
$CC_program_name = "";

?>

Add program name to system-wide variables

git-svn-id: 236d1da889b004185c53d75d23fb6bdc6a50cecb@492 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php

namespace CedricZiel\ShariffBundle\Service;

use CedricZiel\ShariffBundle\ShariffConfig;
use Heise\Shariff\Backend;

/**
 * @package CedricZiel\ShariffBundle\Service
 */
class ShariffService implements ShariffServiceInterface
{
    /**
     * @var ShariffConfig
     */
    protected $config;

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

    /**
     * Get the information from the backend for the given url
     *
     * @param string $url
     *
     * @return array
     */
    public function get($url)
    {
        $backend = new Backend($this->config->toArray());

        try {
            return $backend->get($url);
        } catch (GuzzleException $e) {
            return '{}';
        }
    }

}

<?php

namespace CedricZiel\ShariffBundle\Service;

use CedricZiel\ShariffBundle\Model\ShariffConfig;
use GuzzleHttp\Exception\GuzzleException;
use Heise\Shariff\Backend;

/**
 * @package CedricZiel\ShariffBundle\Service
 */
class ShariffService implements ShariffServiceInterface
{
    /**
     * @var ShariffConfig
     */
    protected $config;

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

    /**
     * Get the information from the backend for the given url
     *
     * @param string $url
     *
     * @return array
     */
    public function get($url)
    {
        $backend = new Backend($this->config->toArray());

        try {
            return $backend->get($url);
        } catch (GuzzleException $e) {
            return '{}';
        }
    }

}

Use correct Exception class to catch

Use correct Exception class to catch


<?php
class aboutActions extends sfActions
{
  public function executeIndex()
  {
    $this->forward('about', 'about');
  }

  public function executeAbout()
  {
    $response = $this->getResponse();

    // test et preuve pour HostGator après l'attaque 2014/02/19
    $throttler = new RequestThrottler($this->getUser(), 'baduser');
    $throttler->setInterval(2);

    if (!$throttler->isValid())
    {
      $throttler->setTimeout(); // reset le timer

    //  $response->setContentType('text/plain; charset=utf-8');
      $response->setContentType('html');
      return $this->renderPartial('misc/requestThrottleError');
    }

    $throttler->setTimeout();
  }

  /* DISABLED
  public function executeAdvertise()
  {
  }
  */

  public function executeLicense()
  {
  }

  public function executeLearnmore()
  {
  }

  public function executeSupport()
  {
  }
}

<?php
class aboutActions extends sfActions
{
  public function executeIndex()
  {
    $this->forward('about', 'about');
  }

  public function executeAbout()
  {
    $response = $this->getResponse();

    // test et preuve pour HostGator après l'attaque 2014/02/19
    $throttler = new RequestThrottler($this->getUser(), 'baduser');
    $throttler->setInterval(2);

    if (!$throttler->isValid())
    {
      $throttler->setTimeout(); // reset le timer

    //  $response->setContentType('text/plain; charset=utf-8');
      $response->setContentType('html');
      return $this->renderPartial('misc/requestThrottleError');
    }

    $throttler->setTimeout();
  }

  public function executePhpinfo()
  {
    if ($this->getUser()->isAdministrator()) {
      phpinfo();exit;
    }
    // dont do a 404 + log on staging
    exit;
  }

  public function executeLicense()
  {
  }

  public function executeLearnmore()
  {
  }

  public function executeSupport()
  {
  }
}

Add about/phpinfo for debugging (admin only)


<?php

/*
 * Mustache PHP Compiler
 *
 * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com
 */

?>

<?php

/*
 * Mustache PHP Compiler
 *
 * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com
 */

namespace Mustache;

class Template {
  public function __construct($data) {
  }
};

?>

Add placeholder for template class

Add placeholder for template class


<?php

namespace App\Http\Middleware;

use Closure;

class SetLocale {
    public function handle($request, Closure $next) {
        if (\Auth::check()) {
            $user = \Auth::user();

            \App::setLocale($user->language);
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;

class SetLocale {
    public function handle($request, Closure $next) {
        if (\Auth::check()) {
            $user = \Auth::user();

            \App::setLocale($user->language);
            Carbon::setLocale($user->language);
        }

        return $next($request);
    }
}

Set the locale for Carbon, so diffForHumans is translated


Enable to use env variable.

Enable to use env variable.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)
    @if (is_null($pending->machine)) {
        break;
    }
    @else {

			id)}}">{{ $pending->id }}
			machine->id) }}">{{ $pending->machine->description }}
			{{ $pending->test_date}}
            {{ $pending->type->test_type}}
			{{ $pending->accession }}
			{{ $pending->notes }}
            id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">

    }
@endif
@endforeach

Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)
    @unless (is_null($pending->machine))

			id)}}">{{ $pending->id }}
			machine->id) }}">{{ $pending->machine->description }}
			{{ $pending->test_date}}
            {{ $pending->type->test_type}}
			{{ $pending->accession }}
			{{ $pending->notes }}
            id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">

    @endunless
@endforeach

Fix logic for displaying pending survey info


<?php

namespace SecucardConnect\Product\Payment\Model;

/**
 * RedirectUrl Data Model class
 *
 */
class RedirectUrl
{
    /**
     * The url for redirect the customer back to the shop after a successful payment checkout
     *
     * @var string
     */
    public $url_success;

    /**
     * The url for redirect the customer back to the shop after a failure (or on cancel) on the payment checkout page
     *
     * @var string
     */
    public $url_failure;

    /**
     * The url for redirect the customer to the payment checkout page
     *
     * @var string
     */
    public $iframe_url;
}

<?php

namespace SecucardConnect\Product\Payment\Model;

/**
 * RedirectUrl Data Model class
 *
 */
class RedirectUrl
{
    /**
     * The url for redirect the customer back to the shop after a successful payment checkout
     *
     * @var string
     */
    public $url_success;

    /**
     * The url for redirect the customer back to the shop after a failure (or on cancel) on the payment checkout page
     *
     * @var string
     */
    public $url_failure;

    /**
     * The url for redirect the customer to the payment checkout page
     *
     * @var string
     */
    public $iframe_url;

    /**
     * Your endpoint to receive push notifications (when the status of the payment transaction will be changed).
     *
     * @var string
     */
    public $url_push;
}

ADD url_push to redirect url model

ADD url_push to redirect url model


<?php

namespace App\Helpers\BBCode\Tags;

class WikiCategoryTag extends LinkTag {

    function __construct()
    {
        $this->token = false;
        $this->element = '';
    }

    public function Matches($state, $token)
    {
        $peekTag = $state->Peek(5);
        $pt = $state->PeekTo(']');
        return $peekTag == '[cat:' && $pt && strlen($pt) > 5 && strstr($pt, "\n") === false;
    }

    public function Parse($result, $parser, $state, $scope)
    {
        $index = $state->Index();

        if ($state->ScanTo(':') != '[cat' || $state->Next() != ':') {
            $state->Seek($index, true);
            return false;
        }
        $str = $state->ScanTo(']');
        if ($state->Next() != ']') {
            $state->Seek($index, true);
            return false;
        }
        $state->SkipWhitespace();
        $result->AddMeta('WikiCategory', $str);
        return '';
    }
}

<?php

namespace App\Helpers\BBCode\Tags;

class WikiCategoryTag extends LinkTag {

    function __construct()
    {
        $this->token = false;
        $this->element = '';
    }

    public function Matches($state, $token)
    {
        $peekTag = $state->Peek(5);
        $pt = $state->PeekTo(']');
        return $peekTag == '[cat:' && $pt && strlen($pt) > 5 && strstr($pt, "\n") === false;
    }

    public function Parse($result, $parser, $state, $scope)
    {
        $index = $state->Index();

        if ($state->ScanTo(':') != '[cat' || $state->Next() != ':') {
            $state->Seek($index, true);
            return false;
        }
        $str = $state->ScanTo(']');
        if ($state->Next() != ']') {
            $state->Seek($index, true);
            return false;
        }
        $state->SkipWhitespace();
        $result->AddMeta('WikiCategory', trim($str));
        return '';
    }
}

Trim whitespace on category tags

Trim whitespace on category tags


<?php
class Vps_User_Web_Model extends Vps_Model_Db
{
    protected $_table = 'vps_users';
    protected $_referenceMap = array(
        'User' => array(
            'column' => 'id',
            'refModelClass' => 'Vps_User_Model'
        )
    );
    protected $_default = array('role' => 'guest');
}

<?php
class Vps_User_Web_Model extends Vps_Model_Db
{
    protected $_table = 'vps_users';
    protected $_referenceMap = array(
        'User' => array(
            'column' => 'id',
            'refModelClass' => ''
        )
    );
    protected $_default = array('role' => 'guest');

    protected function _init()
    {
        $userModelClass = get_class(Vps_Registry::get('userModel'));
        $this->_referenceMap['User']['refModelClass']  = $userModelClass;
        parent::_init();
    }
}

Fix bei vps_users model, reference ist immer das in der config eingestellte model


<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Variant;

trait HasMetaData
{
    /**
     * Retrieve the meta data for this model
     *
     * @param Variant $variant
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function meta(Variant $variant = null)
    {
        if ( ! $variant) {
            return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
        }

        return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
                    ->where('variant_id', $variant->getKey())
                    ->where('variant_type', $variant->getType());
    }

    /**
     * Check if the meta has been set for the metable item, if a variant is
     * passed then check if it is set for the variant.
     *
     * @param Variant|null $variant
     * @return bool
     */
    public function hasMeta(Variant $variant = null)
    {
        if (! empty($variant)) {
            return $this->meta($variant)->exists();
        }

        $this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
    }

    /**
     * Get the meta data for the metable item.
     *
     * @param Variant|null $variant
     * @return mixed
     */
    public function getMeta(Variant $variant = null)
    {
        if ($variant) {
            return $this->meta($variant)->getResults();
        }

        return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
    }
}

<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Variant;

trait HasMetaData
{
    /**
     * Retrieve the meta data for this model
     *
     * @param Variant $variant
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function meta(Variant $variant = null)
    {
        if ( ! $variant) {
            return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
        }

        return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
                    ->where('variant_id', $variant->getKey())
                    ->where('variant_type', $variant->getType());
    }

    /**
     * Check if the meta has been set for the metable item, if a variant is
     * passed then check if it is set for the variant.
     *
     * @param Variant|null $variant
     * @return bool
     */
    public function hasMeta(Variant $variant = null)
    {
        if (! empty($variant)) {
            return $this->meta($variant)->exists();
        }

        return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
    }

    /**
     * Get the meta data for the metable item.
     *
     * @param Variant|null $variant
     * @return mixed
     */
    public function getMeta(Variant $variant = null)
    {
        if ($variant) {
            return $this->meta($variant)->getResults();
        }

        return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
    }
}

Add return to method (corrected typo)

Add return to method (corrected typo)


<?php

namespace Prophets\DrupalJsonApi\Scopes;

use Prophets\DrupalJsonApi\Contracts\DrupalScope;
use Prophets\DrupalJsonApi\Request\DrupalJsonApiRequestBuilder;

class LanguageScope implements DrupalScope
{
    /**
     * @var null
     */
    protected $locale;

    /**
     * LanguageScope constructor.
     * @param null $locale
     */
    public function __construct($locale = null)
    {
        $this->locale = $locale ?: config('app.locale');
    }

    /**
     * Localize the request to the Drupal JSON API.
     * Note: this will not limit resources to the locale, if no resource was found,
     * the API will return the resource in it's "original" language.
     * To limit resources to a specific language add a filter on the resources' field
     * which represents it's locale. For example, for resources based on a Drupal Node resource,
     * use the NodeLangcodeScope.
     * @param DrupalJsonApiRequestBuilder $requestBuilder
     */
    public function apply(DrupalJsonApiRequestBuilder $requestBuilder)
    {
        $requestBuilder->setUriQueryParam('language', $this->locale);
    }
}

<?php

namespace Prophets\DrupalJsonApi\Scopes;

use Prophets\DrupalJsonApi\Contracts\DrupalScope;
use Prophets\DrupalJsonApi\Request\DrupalJsonApiRequestBuilder;

class LanguageScope implements DrupalScope
{
    /**
     * @var null
     */
    protected $locale;

    /**
     * LanguageScope constructor.
     * @param null $locale
     */
    public function __construct($locale = null)
    {
        $this->locale = $locale ?: config('app.locale');
    }

    /**
     * Localize the request to the Drupal JSON API.
     * Note: this will not limit resources to the locale, if no resource was found,
     * the API will return the resource in it's "original" language.
     * To limit resources to a specific language add a filter on the resources' field
     * which represents it's locale. For example, for resources based on a Drupal Node resource,
     * use the NodeLangcodeScope.
     * @param DrupalJsonApiRequestBuilder $requestBuilder
     */
    public function apply(DrupalJsonApiRequestBuilder $requestBuilder)
    {
        $requestBuilder->setUriQueryParam('language_content_entity', $this->locale);
    }
}

Use Drupal's content language detection instead of interface detection.


<?php

/*
 * This file is part of the Antvel Shop package.
 *
 * (c) Gustavo Ocanto <gustavoocanto@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Antvel\User\Models;

use Antvel\Antvel;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    /**
     * The database table.
     *
     * @var string
     */
    protected $table = 'businesses';

    /**
     * Avoiding timestamps.
     *
     * @var boolean
     */
    public $timestamps = false;

    /**
     * The table primary key.
     *
     * @var string
     */
    public $primaryKey = 'user_id';

    /**
     * The auto-increment controller.
     *
     * @var boolean
     */
    public $incrementing = false;

    /**
     * Mass assignable attributes.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'business_name', 'local_phone', 'creation_date'];

     /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['user_id'];

    /**
     * Returns the business user.
     *
     * @return Illuminate\Database\Eloquent\Relations\Relation
     */
    public function user()
    {
        return $this->belongsTo(Antvel::user());
    }

    /**
     * Returns the user full name.
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return ucwords($this->profile->business_name);
    }
}

<?php

/*
 * This file is part of the Antvel Shop package.
 *
 * (c) Gustavo Ocanto <gustavoocanto@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Antvel\User\Models;

use Antvel\Antvel;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    /**
     * The database table.
     *
     * @var string
     */
    protected $table = 'businesses';

    /**
     * Avoiding timestamps.
     *
     * @var boolean
     */
    public $timestamps = false;

    /**
     * The table primary key.
     *
     * @var string
     */
    public $primaryKey = 'user_id';

    /**
     * The auto-increment controller.
     *
     * @var boolean
     */
    public $incrementing = false;

    /**
     * Mass assignable attributes.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'business_name', 'local_phone', 'creation_date'];

     /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['user_id'];

    /**
     * Returns the business user.
     *
     * @return Illuminate\Database\Eloquent\Relations\Relation
     */
    public function user()
    {
        return $this->belongsTo(Antvel::user());
    }

    /**
     * Returns the user full name.
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return ucwords($this->business_name);
    }
}

Fix a bug on business model

Fix a bug on business model


<?php
namespace ZerobRSS;

use \Auryn\Injector;

class Middlewares
{
    /** @var Injector */
    private $injector;

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

    /**
     * Closure to load controllers
     */
    public function controllerLoader($controller, $method)
    {
        $injector = $this->injector;

        return function () use ($controller, $method, $injector) {
            $controller = $injector->make('ZerobRSS\Controllers\\'.$controller);

            return call_user_func_array([$controller, $method], func_get_args());
        };
    }

    /**
     * Middleware to initiate the database connection
     */
    public function db()
    {
        $injector = $this->injector;

        return function () use ($injector) {
            $config = require(PROJECT_ROOT.'/config.php');
            $dbConfig = $config['environments']['database'];

            $dbalConfig = new \Doctrine\DBAL\Configuration();

            $dbalConn = \Doctrine\DBAL\DriverManager::getConnection([
                'url' => $dbConfig['adapter'].'://'.$dbConfig['user'].':'.$dbConfig['pass'].'@'.$dbConfig['host'].':'
                        .$dbConfig['port'].'/'.$dbConfig['name'].'?charset='.$dbConfig['charset']
            ], $dbalConfig);

            $dbalConn->setFetchMode(\PDO::FETCH_OBJ);

            $injector->share($dbalConn);                       // Share \Doctrine\DBAL\Connection
            $injector->share($dbalConn->createQueryBuilder()); // Share \Doctrine\DBAL\Query\QueryBuilder
        };
    }
}

<?php
namespace ZerobRSS;

use \Auryn\Injector;

class Middlewares
{
    /** @var Injector */
    private $injector;

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

    /**
     * Closure to load controllers
     */
    public function controllerLoader($controller, $method)
    {
        $injector = $this->injector;

        return function () use ($controller, $method, $injector) {
            $controller = $injector->make('ZerobRSS\Controllers\\'.$controller);

            return call_user_func_array([$controller, $method], func_get_args());
        };
    }

    /**
     * Middleware to initiate the database connection
     */
    public function db()
    {
        $injector = $this->injector;

        return function () use ($injector) {
            $config = require(PROJECT_ROOT.'/config.php');
            $dbConfig = $config['environments']['database'];

            // Connect to database
            $dbalConfig = new \Doctrine\DBAL\Configuration();
            $dbalConn = \Doctrine\DBAL\DriverManager::getConnection([
                'url' => $dbConfig['adapter'].'://'.$dbConfig['user'].':'.$dbConfig['pass'].'@'.$dbConfig['host'].':'
                        .$dbConfig['port'].'/'.$dbConfig['name'].'?charset='.$dbConfig['charset']
            ], $dbalConfig);

            // Set default fetch-mode to fetch objects
            $dbalConn->setFetchMode(\PDO::FETCH_OBJ);

            // Share \Doctrine\DBAL\Connection
            $injector->share($dbalConn);
        };
    }
}

Stop sharing the query builder, this was a bad idea


<?php

declare(strict_types=1);

namespace Funktions;

use Exception;
use Generator;

/**
 * Return a value based on a test
 *
 * @param boolean $test
 * @param callable $truthy
 * @param callable $falsy
 * @return mixed
 */
function condition(bool $test, callable $truthy, callable $falsy)
{
    if ($test) {
        return call_user_func($truthy);
    }
    return call_user_func($falsy);
}

/**
 * Loop over items and pass them to a generator
 *
 * @param iterable $iterable
 * @param callable $callable
 * @return array
 */
function loop(iterable $iterable, callable $callable): array
{
    $array = [];
    foreach ($iterable as $item) {
        $generator = call_user_func($callable, $item);
        if ($generator instanceof Generator === false) {
            throw new Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    return $array;
}

/**
 * Loop in a generator until a condition is met
 *
 * @param callable $callable
 * @return array
 */
function loop_until(callable $callable): array
{
    $array = [];
    do {
        $generator = call_user_func($callable);
        if ($generator instanceof Generator === false) {
            throw Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    while(!$generator->getReturn());
    return $array;
}

<?php

declare(strict_types=1);

namespace Funktions;

use Exception;
use Generator;

/**
 * Return a value based on a test
 *
 * @param boolean $test
 * @param callable $truthy
 * @param callable $falsy
 * @return mixed
 */
function condition(bool $test, callable $truthy, callable $falsy)
{
    if ($test) {
        return call_user_func($truthy);
    }
    return call_user_func($falsy);
}

/**
 * Loop over items and pass them to a generator
 *
 * @param iterable $iterable
 * @param callable $callable
 * @return Generator
 */
function loop(iterable $iterable, callable $callable): Generator
{
    foreach ($iterable as $item) {
        $generator = call_user_func($callable, $item);
        if ($generator instanceof Generator === false) {
            throw new Exception('Callable must be a generator');
        }
        yield from $generator;
    }
}

/**
 * Loop over a generator until a condition is met
 *
 * @param callable $callable
 * @return Generator
 */
function loop_until(callable $callable): Generator
{
    do {
        $generator = call_user_func($callable);
        if ($generator instanceof Generator === false) {
            throw Exception('Callable must be a generator');
        }
        yield from $generator;
    }
    while($generator->getReturn() === false);
}

Make loop() and loop_until() return a Generator


<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Demo.php';

/**
 * A demo using a radiolist
 *
 * @package   SwatDemo
 * @copyright 2005-2007 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class RadioListDemo extends Demo
{
	// {{{ public function buildDemoUI()

	public function buildDemoUI(SwatUI $ui)
	{
		$radiolist = $ui->getWidget('radiolist');
		$radiolist->addOptionsByArray(array(
			0 => 'Apple',
			1 => 'Orange',
			2 => 'Banana',
			3 => 'Pear',
			4 => 'Pineapple',
			5 => 'Kiwi',
			6 => 'Tangerine',
			7 => 'Grapefruit',
			8 => 'Strawberry'));

		$radiotable = $ui->getWidget('radiotable');
		$radiotable->addOptionsByArray(array(
			0 => 'Apple',
			1 => 'Orange',
			2 => 'Banana',
			3 => 'Pear',
			4 => 'Pineapple',
			5 => 'Kiwi',
			6 => 'Tangerine',
			7 => 'Grapefruit',
			8 => 'Strawberry'));
	}

	// }}}
}

?>

<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Demo.php';

/**
 * A demo using a radiolist
 *
 * @package   SwatDemo
 * @copyright 2005-2007 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class RadioListDemo extends Demo
{
	// {{{ public function buildDemoUI()

	public function buildDemoUI(SwatUI $ui)
	{
		$radiolist = $ui->getWidget('radiolist');
		$radiolist->addOptionsByArray(array(
			0 => 'Apple',
			1 => 'Orange',
			2 => 'Banana',
			3 => 'Pear',
			4 => 'Pineapple',
			5 => 'Kiwi',
			6 => 'Tangerine',
			7 => 'Grapefruit',
			8 => 'Strawberry'));
		$radiolist->addDivider();
		$radiolist->addOption(new SwatOption(9, 'I don\'t like fruit'));

		$radiotable = $ui->getWidget('radiotable');
		$radiotable->addOptionsByArray(array(
			0 => 'Apple',
			1 => 'Orange',
			2 => 'Banana',
			3 => 'Pear',
			4 => 'Pineapple',
			5 => 'Kiwi',
			6 => 'Tangerine',
			7 => 'Grapefruit',
			8 => 'Strawberry'));
		$radiotable->addDivider();
		$radiotable->addOption(new SwatOption(9, 'I don\'t like fruit'));
	}

	// }}}
}

?>

Add dividers to radiolist demo.

Add dividers to radiolist demo.

svn commit r16811


<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		$operation_message = $event->getOperation()->__toString();
		WP_CLI::log( ' - ' . $operation_message );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) );
			}
		}

	}

}

<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Installer\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		$operation_message = $event->getOperation()->__toString();
		WP_CLI::log( ' - ' . $operation_message );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) );
			}
		}

	}

}

Fix PHP notice from the wrong type hint

Fix PHP notice from the wrong type hint


<?php

namespace Nekland\FeedBundle\Item;

interface FullRssItemInterface extends RssItemInterface {
    /**
     * Somethink like "NickName (Real Name)"
     * @return string
     */
    public function getRssAuthor();

    /**
     * @return string
     */
    public function getRssCategory();

    /**
     * @return string|array with [0] => 'route_name', [1] => params
     */
    public function getRssCommentRoute();

    /**
     *
     * @return array with param1 => "value1", param3 => "value 2", ...
     */
    public function getRssEnclosure();

    /**
     * Unique identifiant
     * @return string
     */
    public function getRssGuid();
}

<?php

namespace Nekland\FeedBundle\Item;

interface FullRssItemInterface extends RssItemInterface {
    /**
     * Somethink like "NickName (Real Name)"
     * @return string
     */
    public function getRssAuthor();

    /**
     * @return string
     */
    public function getRssCategory();

    /**
     * @return string|array with [0] => 'route_name', [1] => params
     */
    public function getRssCommentRoute();

    /**
     *
     * @return array with param1 => "value1", param3 => "value 2", ...
     */
    public function getRssEnclosure();

}

Remove guid getter, the id (like a guid) is now required.


<?php

/*
 * This file is part of Alt Three Validator.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\Validator;

use Illuminate\Contracts\Support\MessageProvider;
use Illuminate\Support\MessageBag;
use RuntimeException;

/**
 * This is the validating exception class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ValidationException extends RuntimeException implements MessageProvider
{
    /**
     * The validation errors.
     *
     * @var \Illuminate\Support\MessageBag
     */
    protected $errors;

    /**
     * Make a new validation exception instance.
     *
     * @param \Illuminate\Support\MessageBag $errors
     *
     * @return void
     */
    public function __construct(MessageBag $errors)
    {
        $this->errors = $errors;

        parent::__construct('Validation has failed.');
    }

    /**
     * Get the messages for the instance.
     *
     * @return \Illuminate\Support\MessageBag
     */
    public function getMessageBag()
    {
        return $this->errors;
    }
}

<?php

/*
 * This file is part of Alt Three Validator.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\Validator;

use Illuminate\Contracts\Support\MessageBag;
use Illuminate\Contracts\Support\MessageProvider;
use RuntimeException;

/**
 * This is the validating exception class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ValidationException extends RuntimeException implements MessageProvider
{
    /**
     * The validation errors.
     *
     * @var \Illuminate\Contracts\Support\MessageBag
     */
    protected $errors;

    /**
     * Make a new validation exception instance.
     *
     * @param \Illuminate\Contracts\Support\MessageBag $errors
     *
     * @return void
     */
    public function __construct(MessageBag $errors)
    {
        $this->errors = $errors;

        parent::__construct('Validation has failed.');
    }

    /**
     * Get the messages for the instance.
     *
     * @return \Illuminate\Contracts\Support\MessageBag
     */
    public function getMessageBag()
    {
        return $this->errors;
    }
}

Use the message bag contract

Use the message bag contract


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

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

class AddTrackIdToBeatmapsets extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('osu_beatmapsets', function (Blueprint $table) {
            $table->bigInteger('track_id')->unsigned()->nullable();
            $table->index('track_id');
        });
    }

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

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

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

class AddTrackIdToBeatmapsets extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('osu_beatmapsets', function (Blueprint $table) {
            $table->integer('track_id')->unsigned()->nullable();
            $table->index('track_id');
        });
    }

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

Change column to `integer` to match `artist_tracks` table spec


<?php

namespace JPB\WpBehatExtension\Context;

use Behat\MinkExtension\Context\RawMinkContext;

class AuthenticationContext extends RawMinkContext {

	/**
	 * @Given I am not logged in
	 */
	public function iAmNotLoggedIn() {
		$this->getSession()->reset();
		$this->getSession()->visit( wp_logout_url() );
	}

	/**
	 * @Given I am logged in as :username with :password
	 */
	public function iAmLoggedInAs( $username, $password ) {
		$this->getSession()->reset();
		$login_url = wp_login_url();
		$this->getSession()->visit( $login_url );
		$currentPage = $this->getSession()->getPage();

		$currentPage->fillField( 'user_login', $username );
		$currentPage->fillField( 'user_pass', $password );
		$currentPage->findButton( 'wp-submit' )->click();

		\PHPUnit_Framework_Assert::assertNotEquals( $this->getSession()->getCurrentUrl(), $login_url );
	}

}

<?php

namespace JPB\WpBehatExtension\Context;

use Behat\MinkExtension\Context\RawMinkContext;

class AuthenticationContext extends RawMinkContext {

	/**
	 * @Given I am not logged in
	 */
	public function iAmNotLoggedIn() {
		$this->getSession()->reset();
		$this->getSession()->visit( wp_logout_url() );
	}

	/**
	 * @Given I am logged in as :username with :password
	 */
	public function iAmLoggedInAs( $username, $password ) {
		$this->getSession()->reset();
		$login_url = wp_login_url();
		$this->getSession()->visit( $login_url );
		$currentPage = $this->getSession()->getPage();

		$currentPage->fillField( 'user_login', $username );
		$currentPage->fillField( 'user_pass', $password );
		$currentPage->findButton( 'wp-submit' )->click();

		\PHPUnit_Framework_Assert::assertNotEquals( $this->getSession()->getCurrentUrl(), $login_url );
	}

	/**
	 * @Then I should be logged out
	 */
	public function iShouldBeLoggedOut() {
		$this->getSession()->visit( add_query_arg( [ 'action' => 'logged-in' ], admin_url( 'admin-ajax.php' ) ) );
		$body = $this->getSession()->getPage()->getContent();
		\PHPUnit_Framework_Assert::assertEquals( '0', trim( $body ) );
	}

	/**
	 * @Then I should be logged in
	 */
	public function iShouldBeLoggedIn() {
		$this->getSession()->visit( add_query_arg( [ 'action' => 'logged-in' ], admin_url( 'admin-ajax.php' ) ) );
		$body = $this->getSession()->getPage()->getContent();
		\PHPUnit_Framework_Assert::assertEquals( '1', trim( $body ) );
	}

}

Add two methods for verifying the two different auth states


<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\Building;
use AppBundle\Entity\Category;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadBuildingData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function load(ObjectManager $manager)
    {
        $countCategories = count($manager->getRepository(Category::class)->findAll());
        for ($i = 0; $i < $countCategories; $i++) {
            for ($j = 0; $j < 3; $j++) {
                $building = new Building();
                $building->setStreetName('Street ' . $i); // Count of street is equal to count of category
                $building->setBuildingNumber($j);         //For 3 buildings per street
                $building->setCoordinateX(rand(-1000, 1000));
                $building->setCoordinateY(rand(-1000, 1000));

                $manager->persist($building);
                $manager->flush();
            }
        }
    }

    public function getOrder()
    {
        return 2;
    }

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

<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\Building;
use AppBundle\Entity\Category;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadBuildingData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function load(ObjectManager $manager)
    {
        $countCategories = count($manager->getRepository(Category::class)->findAll());
        for ($i = 0; $i < $countCategories; $i++) {
            for ($j = 0; $j < 3; $j++) {
                $building = new Building();
                $building->setStreetName('Street ' . $i); // Count of street is equal to count of category
                $building->setBuildingNumber($j);         //For 3 buildings per street
                $building->setCoordinateX(rand(-10000, 10000));
                $building->setCoordinateY(rand(-10000, 10000));

                $manager->persist($building);
                $manager->flush();
            }
        }
    }

    public function getOrder()
    {
        return 2;
    }

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

Increase coordinate in building fixtures


<?php

namespace OParl\Server\API\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;

class RootController extends Controller
{
    public function index(Router $router)
    {
        $routes = collect($router->getRoutes()->get('GET'))
            ->filter(function (Route $route) {
                return starts_with($route->getName(), 'api.oparl.v1');
            });

        return view('server::overview', compact('routes'));
    }
}

<?php

namespace OParl\Server\API\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;

class RootController extends Controller
{
    public function index(Router $router)
    {
//        $routes = collect($router->getRoutes()->get('GET'))
//            ->filter(function (Route $route) {
//                return starts_with($route->getName(), 'api.oparl.v1');
//            });
//
//        return view('server::overview', compact('routes'));
        return redirect()->route('api.oparl.v1.system.index', ['format' => 'html']);
    }
}

Revert demo api to show system

Revert demo api to show system


<?php

namespace Gobie\Regex\Drivers\Pcre;

use Gobie\Regex\RegexException;

class PcreRegexException extends RegexException
{

    public static $messages = array(
        PREG_INTERNAL_ERROR        => 'Internal error',
        PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
        PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
        PREG_BAD_UTF8_ERROR        => 'Malformed UTF-8 data',
        PREG_BAD_UTF8_OFFSET_ERROR => 'The offset didn\'t correspond to the begin of a valid UTF-8 code point',
    );

    public function __construct($message, $code = null, $pattern = null)
    {
        if (!$message && isset(self::$messages[$code])) {
            $message = self::$messages[$code];
        }

        parent::__construct($message, $code, $pattern);
    }
}

<?php

namespace Gobie\Regex\Drivers\Pcre;

use Gobie\Regex\RegexException;

// hhvm fix
if (!\defined('PREG_BAD_UTF8_OFFSET_ERROR')) {
    \define('PREG_BAD_UTF8_OFFSET_ERROR', 5);
};

class PcreRegexException extends RegexException
{

    public static $messages = array(
        PREG_INTERNAL_ERROR        => 'Internal error',
        PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
        PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
        PREG_BAD_UTF8_ERROR        => 'Malformed UTF-8 data',
        PREG_BAD_UTF8_OFFSET_ERROR => 'The offset didn\'t correspond to the begin of a valid UTF-8 code point',
    );

    public function __construct($message, $code = null, $pattern = null)
    {
        if (!$message && isset(self::$messages[$code])) {
            $message = self::$messages[$code];
        }

        parent::__construct($message, $code, $pattern);
    }
}

Define PREG_BAD_UTF8_OFFSET_ERROR if it doesn't exist for HHVM


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

/**
 * VoterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProvinceRepository extends EntityRepository
{
	public function fetchProvinces()
	{
		$query = "SELECT id, name FROM provinces_spain";

		$statement = $this->getEntityManager()->getConnection()->executeQuery($query);
		return $statement->fetchAll();
	}

	public function getMunicipalityName($municipality_id)
	{
		$query = "SELECT name FROM municipalities_spain WHERE id='" . intval($municipality_id) . "' LIMIT 1";

		$statement = $this->getEntityManager()->getConnection()->executeQuery($query);

		$result = $statement->fetchAll();

		if(!empty($result))
		{
			return $result['name'];
		}

		return NULL;
	}
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

/**
 * VoterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProvinceRepository extends EntityRepository
{
	public function fetchProvinces()
	{
		$query = "SELECT id, name FROM provinces_spain";

		$statement = $this->getEntityManager()->getConnection()->executeQuery($query);
		return $statement->fetchAll();
	}

	public function getMunicipalityName($municipality_id)
	{
		$query = "SELECT name FROM municipalities_spain WHERE id='" . intval($municipality_id) . "' LIMIT 1";

		$statement = $this->getEntityManager()->getConnection()->executeQuery($query);

		$result = $statement->fetchAll();

		if(!empty($result))
		{
			if(!isset($result['name']))
			{
				$result = reset($result);
			}
			return $result['name'];
		}

		return NULL;
	}
}

Fix result as array parsing

Fix result as array parsing


<?php

namespace AppBundle\Tests\Services;

use AppBundle\Tests\Controller\AbstractApiTest;
use AppBundle\Document\Dream;

class ObjectUpdaterTest extends AbstractApiTest
{
    public function testUpdateObject()
    {
        $client   = static::createClient();

        $dreamOld = $client->getContainer()
                           ->get('doctrine_mongodb.odm.document_manager')
                           ->getRepository('AppBundle:Dream')
                           ->findOneBySlug('sunt');

        $financial_resource = new FinancialResource();
        $financial_resource->setTitle('ex');
        $financial_resource->setQuantity(50);

        $dreamTmp = new Dream();
        $dreamTmp->setTitle('test1');
        $dreamTmp->setDescription('test2');
        $dreamTmp->addDreamFinancialResource($financial_resource);

        $dreamNew = $client->getContainer()->get('app.services.object_updater')->updateObject($dreamOld, $dreamTmp);

        $this->assertEquals($dreamNew->getTitle(), $dreamTmp->getTitle());
        $this->assertEquals($dreamNew->getDescription(), $dreamTmp->getDescription());
    }
}

<?php

namespace AppBundle\Tests\Services;

use AppBundle\Tests\Controller\AbstractApiTest;
use AppBundle\Document\Dream;
use AppBundle\Document\FinancialResource;

class ObjectUpdaterTest extends AbstractApiTest
{
    public function testUpdateObject()
    {
        $client   = static::createClient();

        $dreamOld = $client->getContainer()
                           ->get('doctrine_mongodb.odm.document_manager')
                           ->getRepository('AppBundle:Dream')
                           ->findOneBySlug('sunt');

        $financial_resource = new FinancialResource();
        $financial_resource->setTitle('ex');
        $financial_resource->setQuantity(50);

        $dreamTmp = new Dream();
        $dreamTmp->setTitle('test1');
        $dreamTmp->setDescription('test2');
        $dreamTmp->addDreamFinancialResource($financial_resource);

        $dreamNew = $client->getContainer()->get('app.services.object_updater')->updateObject($dreamOld, $dreamTmp);

        $this->assertEquals($dreamNew->getTitle(), $dreamTmp->getTitle());
        $this->assertEquals($dreamNew->getDescription(), $dreamTmp->getDescription());
    }
}

Add use financial resource in ObjectUpdater


<?php
/**
 * mbc-user-digest.php
 *
 * A consumer to process entries in the registrationMobileQueue via the
 * transactionalExchange. The mbp-registration-mobile application produces user
 * entries in Mobile Commons based the contents of the queue.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_RegistrationMobile\MBC_RegistrationMobile_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-registration-mobile.config.inc';

// Kick off - block, wait for messages in queue
echo '------- mbc-registration-mobile START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_RegistrationMobile_Consumer(), 'consumeRegistrationMobileQueue'));
echo '------- mbc-registration-mobile END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

<?php
/**
 * mbc-user-digest.php
 *
 * A consumer to process entries in the registrationMobileQueue via the
 * transactionalExchange. The mbp-registration-mobile application produces user
 * entries in Mobile Commons based the contents of the queue.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');
// The number of messages for the consumer to reserve with each callback
// See consumeMwessage for further details.
// Necessary for parallel processing when more than one consumer is running on the same queue.
define('QOS_SIZE', 1);

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_RegistrationMobile\MBC_RegistrationMobile_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-registration-mobile.config.inc';

// Kick off - block, wait for messages in queue
echo '------- mbc-registration-mobile START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_RegistrationMobile_Consumer(), 'consumeRegistrationMobileQueue'), QOS_SIZE);
echo '------- mbc-registration-mobile END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

Add QOS setting to support parallel processing


<?php

namespace TQ\Shamir\Random;

/**
 * Class PhpGenerator
 *
 * @package TQ\Shamir\Random
 */
class PhpGenerator implements Generator
{

    /**
     * The maximum random number
     *
     * @var int
     */
    protected $max = PHP_INT_MAX;

    /**
     * The minimum random number
     *
     * @var int
     */
    protected $min = 1;

    /**
     * Constructor
     *
     * @param int $max The maximum random number
     * @param int $min The minimum random number
     */
    public function __construct($max = PHP_INT_MAX, $min = 1)
    {
        $this->min = (int)$min;
        $this->max = (int)$max;
    }

    /**
     * @inheritdoc
     */
    public function getRandomInt()
    {
        $random = mt_rand($this->min, $this->max);
        if ($random === false ) {
            throw new \RuntimeException(
                'Random number generator algorithm failed.'
            );

        }
        return $random;
    }

}

<?php

namespace TQ\Shamir\Random;

/**
 * Class PhpGenerator
 *
 * @package TQ\Shamir\Random
 */
class PhpGenerator implements Generator
{

    /**
     * The maximum random number
     *
     * @var int
     */
    protected $max = PHP_INT_MAX;

    /**
     * The minimum random number
     *
     * @var int
     */
    protected $min = 1;

    /**
     * Constructor
     *
     * @param int $max The maximum random number
     * @param int $min The minimum random number
     */
    public function __construct($max = PHP_INT_MAX, $min = 1)
    {
        $this->min = (int)$min;
        $this->max = (int)$max;
    }

    /**
     * @inheritdoc
     */
    public function getRandomInt()
    {
        if (version_compare(PHP_VERSION, '7.0') >= 0) {
            $random = random_int($this->min, $this->max);
        }
        else {
            $random = mt_rand($this->min, $this->max);
        }

        if ($random === false ) {
            throw new \RuntimeException(
                'Random number generator algorithm failed.'
            );

        }
        return $random;
    }

}

Use more secure PHP 7.0 random_int() function if available


<?php

namespace Tests\SitemapPlugin\Controller;

use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;

/**
 * @author Stefan Doorn <stefan@efectos.nl>
 */
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
    /**
     * @before
     */
    public function setUpDatabase()
    {
        parent::setUpDatabase();

        $root = new Taxon();
        $root->setCurrentLocale('en_US');
        $root->setName('Root');
        $root->setCode('root');
        $root->setSlug('root');

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Test');
        $taxon->setCode('test-code');
        $taxon->setSlug('test');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Mock');
        $taxon->setCode('mock-code');
        $taxon->setSlug('mock');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $this->getEntityManager()->persist($root);

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

    public function testShowActionResponse()
    {
        $this->client->request('GET', '/sitemap/taxons.xml');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'show_sitemap_taxons');
    }
}

<?php

namespace Tests\SitemapPlugin\Controller;

use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;

/**
 * @author Stefan Doorn <stefan@efectos.nl>
 */
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
    /**
     * @before
     */
    public function setUpDatabase()
    {
        parent::setUpDatabase();

        $root = new Taxon();
        $root->setCurrentLocale('en_US');
        $root->setName('Root');
        $root->setCode('root');
        $root->setSlug('root');

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Test');
        $taxon->setCode('test-code');
        $taxon->setSlug('test');
        $taxon->setParent($root);

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Mock');
        $taxon->setCode('mock-code');
        $taxon->setSlug('mock');
        $taxon->setParent($root);

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

    public function testShowActionResponse()
    {
        $this->client->request('GET', '/sitemap/taxons.xml');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'show_sitemap_taxons');
    }
}

Adjust saving of test taxons

Adjust saving of test taxons


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

namespace Imbo\Image\Transformation;

use Imbo\Exception\TransformationException,
    ImagickException;

/**
 * Clip transformation
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\Transformations
 */
class Clip extends Transformation {
    /**
     * {@inheritdoc}
     */
    public function transform(array $params) {
        try {
            $this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_TRANSPARENT);
            $this->imagick->clipImage();
            $this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_OPAQUE);
        } catch (ImagickException $e) {
            throw new TransformationException($e->getMessage(), 400, $e);
        }

        $this->image->hasBeenTransformed(true);
    }
}

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

namespace Imbo\Image\Transformation;

use Imbo\Exception\TransformationException,
    ImagickException;

/**
 * Clip transformation
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\Transformations
 */
class Clip extends Transformation {
    /**
     * {@inheritdoc}
     */
    public function transform(array $params) {
        try {
            $this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_TRANSPARENT);
            $this->imagick->clipImage();
            $this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_OPAQUE);
        } catch (ImagickException $e) {
            // NoClipPathDefined - the image doesn't have a clip path, but this isn't an fatal error.
            if ($e->getCode() == 410) {
                return;
            }

            throw new TransformationException($e->getMessage(), 400, $e);
        }

        $this->image->hasBeenTransformed(true);
    }
}

Handle files without a clip path

Handle files without a clip path


Add component path to config

Add component path to config


<?php
namespace Neos\Flow\Mvc;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Mvc\Routing\RoutingComponent;
use Neos\Flow\Security\Context;

/**
 *
 */
class PrepareMvcRequestComponent implements ComponentInterface
{
    /**
     * @Flow\Inject(lazy=false)
     * @var Context
     */
    protected $securityContext;

    /**
     * @Flow\Inject
     * @var ActionRequestFactory
     */
    protected $actionRequestFactory;

    /**
     * @inheritDoc
     */
    public function handle(ComponentContext $componentContext)
    {
        $httpRequest = $componentContext->getHttpRequest();

        $routingMatchResults = $componentContext->getParameter(RoutingComponent::class, 'matchResults');
        $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults ?? []);
        $this->securityContext->setRequest($actionRequest);
        $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
    }
}

<?php
namespace Neos\Flow\Mvc;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Http\ServerRequestAttributes;
use Neos\Flow\Security\Context;

/**
 *
 */
class PrepareMvcRequestComponent implements ComponentInterface
{
    /**
     * @Flow\Inject(lazy=false)
     * @var Context
     */
    protected $securityContext;

    /**
     * @Flow\Inject
     * @var ActionRequestFactory
     */
    protected $actionRequestFactory;

    /**
     * @inheritDoc
     */
    public function handle(ComponentContext $componentContext)
    {
        $httpRequest = $componentContext->getHttpRequest();

        $routingMatchResults = $httpRequest->getAttribute(ServerRequestAttributes::ROUTING_RESULTS) ?? [];
        $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults);
        $this->securityContext->setRequest($actionRequest);
        $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
    }
}

TASK: Replace RouteComponent::class matchResults with ServerRequestAttributes::ROUTING_RESULTS


<?php

namespace Ibillmaker\Hub\CoreBundle\Entity;

use Sylius\Component\Core\Model\User as BaseUser;
use Sylius\Component\Core\Model\UserInterface;
class User extends BaseUser {

    protected $companyName;
    protected $admin;

    public function __construct()
    {
        parent::__construct();
    }

    public function getAdmin()
    {
        return $this->admin;
    }

    public function setAdmin(UserInterface $admin)
    {
     $this->admin = $admin;
     return $this;
    }

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value)
    {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }

        return $this;
    }

}

<?php

namespace Ibillmaker\Hub\CoreBundle\Entity;

use Sylius\Component\Core\Model\User as BaseUser;
use Sylius\Component\Core\Model\UserInterface;
class User extends BaseUser {

    /*
     * @var string
     * desc companyName
     */
    protected $companyName;
    // admin id ex. user(admin) who creates the client.
    protected $admin;
    // people id ex. clientId for the contact of that perticular client
    protected $people;
    // phone number
    protected $phoneNumber;
    // mobile number
    protected $mobileNumber;

    public function __construct()
    {
        parent::__construct();
    }

    public function getAdmin()
    {
        return $this->admin;
    }

    public function setAdmin(UserInterface $admin)
    {
     $this->admin = $admin;
     return $this;
    }

    public function getPeople()
    {
        return $this->people;
    }

    public function setPeople(UserInterface $people)
    {
     $this->people = $people;
     return $this;
    }

    public function getPhoneNumber()
    {
        return $this->phoneNumber;
    }

    public function setPhoneNumber($phoneNumber)
    {
     $this->phoneNumber = $phoneNumber;
     return $this;
    }

    public function getMobileNumber()
    {
        return $this->mobileNumber;
    }

    public function setMobileNumber($mobileNumber)
    {
     $this->mobileNumber = $mobileNumber;
     return $this;
    }

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value)
    {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }

        return $this;
    }

}

Test Fake - new user interface.

Test Fake - new user interface.


<?php

namespace Asmaster\EquipTwig\Tests;

use Asmaster\EquipTwig\TwigFormatter;
use Equip\Adr\PayloadInterface;
use Lukasoppermann\Httpstatus\Httpstatus;
use PHPUnit_Framework_TestCase as TestCase;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;

class TwigFormatterTest extends TestCase
{
    /**
     * @var TwigFormatter
     */
    private $formatter;

    protected function setUp()
    {
        $loader = new TwigLoaderFilesystem(__DIR__.'/Asset/templates');

        $this->formatter = new TwigFormatter(
            new TwigEnvironment($loader),
            new HttpStatus
        );
    }

    public function testAccepts()
    {
        $this->assertEquals(['text/html'], TwigFormatter::accepts());
    }

    public function testType()
    {
        $this->assertEquals('text/html', $this->formatter->type());
    }

    public function testResponse()
    {
        $template = 'test.html.twig';
        $output = [
            'header' => 'header',
            'body'   => 'body',
            'footer' => 'footer'
        ];

        $payload = $this->getMock(PayloadInterface::class);

        $payload->expects($this->any())
            ->method('getOutput')
            ->willReturn($output);

        $payload->expects($this->any())
            ->method('getSetting')
            ->willReturn($template);

        $body = $this->formatter->body($payload);

        $this->assertEquals("
header
\n
body
\nfooter\n", $body);
    }
}

<?php

namespace Asmaster\EquipTwig\Tests;

use Asmaster\EquipTwig\TwigFormatter;
use Equip\Adr\PayloadInterface;
use PHPUnit_Framework_TestCase as TestCase;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;

class TwigFormatterTest extends TestCase
{
    /**
     * @var TwigFormatter
     */
    private $formatter;

    protected function setUp()
    {
        $loader = new TwigLoaderFilesystem(__DIR__.'/Asset/templates');

        $this->formatter = new TwigFormatter(
            new TwigEnvironment($loader)
        );
    }

    public function testAccepts()
    {
        $this->assertEquals(['text/html'], TwigFormatter::accepts());
    }

    public function testType()
    {
        $this->assertEquals('text/html', $this->formatter->type());
    }

    public function testResponse()
    {
        $template = 'test.html.twig';
        $output = [
            'header' => 'header',
            'body'   => 'body',
            'footer' => 'footer'
        ];

        $payload = $this->getMock(PayloadInterface::class);

        $payload->expects($this->any())
            ->method('getOutput')
            ->willReturn($output);

        $payload->expects($this->any())
            ->method('getSetting')
            ->willReturn($template);

        $body = $this->formatter->body($payload);

        $this->assertEquals("
header
\n
body
\nfooter\n", $body);
    }
}

Remove unused "use statement" from the test


<?php

namespace Omnipay\Stripe\Message;

use Mockery as m;
use Omnipay\Tests\TestCase;

class AbstractRequestTest extends TestCase
{
    public function testSendDataSetsApiVersionIfPresent_Mockery()
    {
        $apiVersion = '2014-10-12';

        $eventDispatcher = m::mock('\Symfony\Component\EventDispatcher\EventDispatcherInterface')
            ->shouldReceive('addListener')->getMock();

        $response = m::mock('\Guzzle\Http\Message\Response')->shouldReceive('json')->getMock();

        $request = $this->getMockRequest()
            ->shouldReceive('setHeader')->once()->withArgs(['Authorization', 'Basic Og=='])
            ->shouldReceive('setHeader')->once()->withArgs(['Stripe-Version', $apiVersion])
            ->shouldReceive('send')->andReturn($response)
            ->getMock();

        $httpClient = m::mock('Guzzle\Http\ClientInterface')
            ->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher)
            ->shouldReceive('createRequest')->andReturn($request)
            ->getMock();

        $request = m::mock('\Omnipay\Stripe\Message\AbstractRequest[getEndPoint,getApiVersion]', array($httpClient, $this->getHttpRequest()));
        $request->shouldReceive('getApiVersion')->andReturn($apiVersion);
        $request->shouldReceive('getEndpoint')->andReturn('foo');

        $request->sendData(array('foo' => 'bar'));
    }

}

<?php

namespace Omnipay\Stripe\Message;

use Mockery as m;
use Omnipay\Tests\TestCase;

class AbstractRequestTest extends TestCase
{
    public function testSendDataSetsApiVersionIfPresent_Mockery()
    {
        $apiVersion = '2014-10-12';

        $eventDispatcher = m::mock('\Symfony\Component\EventDispatcher\EventDispatcherInterface')
            ->shouldReceive('addListener')->getMock();

        $response = m::mock('\Guzzle\Http\Message\Response')->shouldReceive('json')->getMock();

        $request = $this->getMockRequest()
            ->shouldReceive('setHeader')->once()->withArgs(array('Authorization', 'Basic Og=='))
            ->shouldReceive('setHeader')->once()->withArgs(array('Stripe-Version', $apiVersion))
            ->shouldReceive('send')->andReturn($response)
            ->getMock();

        $httpClient = m::mock('Guzzle\Http\ClientInterface')
            ->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher)
            ->shouldReceive('createRequest')->andReturn($request)
            ->getMock();

        $request = m::mock('\Omnipay\Stripe\Message\AbstractRequest[getEndPoint,getApiVersion]', array($httpClient, $this->getHttpRequest()));
        $request->shouldReceive('getApiVersion')->andReturn($apiVersion);
        $request->shouldReceive('getEndpoint')->andReturn('foo');

        $request->sendData(array('foo' => 'bar'));
    }

}

Fix array notation to support PHP 5.3

Fix array notation to support PHP 5.3


<?php

require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');

class MustacheTestSuite extends TestSuite {
  function MustacheTestSuite() {
    $this->TestSuite('All Mustache tests');
    $this->addFile(dirname(__FILE__)."/testStringScanner.php");
    $this->addFile(dirname(__FILE__)."/testHelpers.php");
    $this->addFile(dirname(__FILE__)."/testMustache.php");
    $this->addFile(dirname(__FILE__)."/testContext.php");
    $this->addFile(dirname(__FILE__)."/testParser.php");
    $this->addFile(dirname(__FILE__)."/testGenerator.php");
    $this->addFile(dirname(__FILE__)."/testSpec.php");
  }
};

?>

<?php

require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');

class MustacheTestSuite extends TestSuite {
  function MustacheTestSuite() {
    $this->TestSuite('All Mustache tests');
    $this->addFile(dirname(__FILE__)."/testStringScanner.php");
    $this->addFile(dirname(__FILE__)."/testHelpers.php");
    $this->addFile(dirname(__FILE__)."/testMustache.php");
    $this->addFile(dirname(__FILE__)."/testContext.php");
    $this->addFile(dirname(__FILE__)."/testParser.php");
    $this->addFile(dirname(__FILE__)."/testGenerator.php");
    //    $this->addFile(dirname(__FILE__)."/testSpec.php");
  }
};

?>

Remove specs from suite (separate)

Remove specs from suite (separate)


<?php

class Stripe_Invoice extends Stripe_ApiResource
{
  public static function constructFrom($values, $apiKey=null)
  {
    $class = get_class();
    return self::scopedConstructFrom($class, $values, $apiKey);
  }

  public static function retrieve($id, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedRetrieve($class, $id, $apiKey);
  }

  public static function all($params=null, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedAll($class, $params, $apiKey);
  }

  public static function upcoming($params=null, $apiKey=null)
  {
    $requestor = new Stripe_ApiRequestor($apiKey);
    $url = self::classUrl(get_class()) . '/upcoming';
    list($response, $apiKey) = $requestor->request('get', $url, $params);
    return Stripe_Util::convertToStripeObject($response, $apiKey);
  }
}

<?php

class Stripe_Invoice extends Stripe_ApiResource
{
  public static function constructFrom($values, $apiKey=null)
  {
    $class = get_class();
    return self::scopedConstructFrom($class, $values, $apiKey);
  }

  public static function retrieve($id, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedRetrieve($class, $id, $apiKey);
  }

  public static function all($params=null, $apiKey=null)
  {
    $class = get_class();
    return self::_scopedAll($class, $params, $apiKey);
  }

  public static function upcoming($params=null, $apiKey=null)
  {
    $requestor = new Stripe_ApiRequestor($apiKey);
    $url = self::classUrl(get_class()) . '/upcoming';
    list($response, $apiKey) = $requestor->request('get', $url, $params);
    return Stripe_Util::convertToStripeObject($response, $apiKey);
  }

  public function save()
  {
    $class = get_class();
    return self::_scopedSave($class);
  }

  public function pay()
  {
    $requestor = new Stripe_ApiRequestor($this->_apiKey);
    $url = $this->instanceUrl() . '/pay';
    list($response, $apiKey) = $requestor->request('post', $url);
    $this->refreshFrom($response, $apiKey);
    return $this;
  }
}

Add invoice pay and update methods

Add invoice pay and update methods