<?php namespace Iverberk\Larasearch\Exceptions;

use Exception;

class ImportException extends Exception {

	// Redefine the exception so message isn't optional
	public function __construct($message, $code = 0, $errorItems = [])
	{
		// Just dump the errorItems for now
		var_dump($errorItems);

		// make sure everything is assigned properly
		parent::__construct($message, $code);
	}

}

<?php namespace Iverberk\Larasearch\Exceptions;

use Exception;

class ImportException extends Exception {

	// Redefine the exception so message isn't optional
	public function __construct($message, $code = 0, $errorItems = [])
	{
		// make sure everything is assigned properly
		parent::__construct($message, $code);
	}

}

Remove the plain var_dump, needs a better logging solution


<?php

namespace Bolt\Provider;

use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Service\Client;
use Silex\Application;
use Silex\ServiceProviderInterface;

class GuzzleServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['guzzle.base_url'] = '/';

        if (!isset($app['guzzle.plugins'])) {
            $app['guzzle.plugins'] = array();
        }

        // Register a Guzzle ServiceBuilder
        $app['guzzle'] = $app->share(
            function () use ($app) {
                if (!isset($app['guzzle.services'])) {
                    $builder = new ServiceBuilder(array());
                } else {
                    $builder = ServiceBuilder::factory($app['guzzle.services']);
                }

                return $builder;
            }
        );

        // Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset)
        $app['guzzle.client'] = $app->share(
            function () use ($app) {
                $client = new Client($app['guzzle.base_url']);
                foreach ($app['guzzle.plugins'] as $plugin) {
                    $client->addSubscriber($plugin);
                }

                return $client;
            }
        );
    }

    public function boot(Application $app)
    {
    }
}

<?php

namespace Bolt\Provider;

use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Service\Client as ServiceClient;
use GuzzleHttp\Client;
use Silex\Application;
use Silex\ServiceProviderInterface;

class GuzzleServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['guzzle.base_url'] = '/';

        if (!isset($app['guzzle.plugins'])) {
            $app['guzzle.plugins'] = array();
        }

        /** @deprecated */
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            return $this->compat($app);
        }
    }

    /**
     * PHP 5.3 compatibility services
     *
     * @deprecated
     *
     * @param Application $app
     */
    private function compat(Application $app)
    {
        // Register a Guzzle ServiceBuilder
        $app['guzzle'] = $app->share(
            function () use ($app) {
                if (!isset($app['guzzle.services'])) {
                    $builder = new ServiceBuilder(array());
                } else {
                    $builder = ServiceBuilder::factory($app['guzzle.services']);
                }

                return $builder;
            }
        );

        // Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset)
        $app['guzzle.client'] = $app->share(
            function () use ($app) {
                $client = new ServiceClient($app['guzzle.base_url']);
                foreach ($app['guzzle.plugins'] as $plugin) {
                    $client->addSubscriber($plugin);
                }

                return $client;
            }
        );
    }

    public function boot(Application $app)
    {
    }
}

Move Guzzle 3.9 providers to a compat() function


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Password Reminder Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are the default lines which match reasons
	| that are given by the password broker for a password update attempt
	| has failed, such as for an invalid token or invalid new password.
	|
	*/

	"password" => "Passwords must be at least six characters and match the confirmation.",

	"user" => "We can't find a user with that e-mail address.",

	"token" => "This password reset token is invalid.",

	"sent" => "Password reminder sent!",

	"reset" => "Password has been reset!",

);

<?php

return [

	/*
	|--------------------------------------------------------------------------
	| Password Reminder Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are the default lines which match reasons
	| that are given by the password broker for a password update attempt
	| has failed, such as for an invalid token or invalid new password.
	|
	*/

	"password" => "Passwords must be at least six characters and match the confirmation.",

	"user" => "We can't find a user with that e-mail address.",

	"token" => "This password reset token is invalid.",

	"sent" => "Password reminder sent!",

	"reset" => "Password has been reset!",

];

Convert language PHP 5.4 arrays.

Convert language PHP 5.4 arrays.


<?php

namespace App\Forms\Admin;

use App\Base\Forms\AdminForm;

class SettingsForm extends AdminForm
{
    public function buildForm()
    {
        $this
            ->add('email', 'text', [
                'label' => trans('admin.fields.setting.email')
            ])
            ->add('facebook', 'text', [
                'label' => trans('admin.fields.setting.facebook')
            ])
            ->add('twitter', 'text', [
                'label' => trans('admin.fields.setting.twitter')
            ])
            ->add('analytics_id', 'text', [
                'label' => trans('admin.fields.setting.analytics_id')
            ])
            ->add('disqus_shortname', 'text', [
                'label' => trans('admin.fields.setting.disqus_shortname')
            ])
            ->add('logo', 'file', [
                'label' => trans('admin.fields.setting.logo'),
                'attr' => ['class' => '']
            ]);
        parent::buildForm();
    }
}

<?php

namespace App\Forms\Admin;

use App\Base\Forms\AdminForm;

class SettingsForm extends AdminForm
{
    public function buildForm()
    {
        $this
            ->add('email', 'text', [
                'label' => trans('admin.fields.setting.email')
            ])
            ->add('analytics_id', 'text', [
                'label' => trans('admin.fields.setting.analytics_id')
            ]);
        parent::buildForm();
    }
}

Switch up the settings form

Switch up the settings form


<?php

use App\Models\Business;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class GuestBusinessControllerTest extends TestCase
{
    use DatabaseTransactions;

    ///////////
    // TESTS //
    ///////////

    /** @test */
    public function it_presents_the_business_home()
    {
        // Given I am a guest user
        $business = factory(Business::class)->create();

        // And I visit the homepage
        $this->visit(route('guest.business.home', $business));

        // Then I should see the business home
        $this->see($business->name)
             ->see(substr($business->description, 0, 15));
    }
}

<?php

use App\Models\Business;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class GuestBusinessControllerTest extends TestCase
{
    use DatabaseTransactions;
    use CreateBusiness;

    ///////////
    // TESTS //
    ///////////

    /** @test */
    public function it_presents_the_business_home()
    {
        // Given I am a guest user
        $business = $this->createBusiness();

        // And I visit the homepage
        $this->visit(route('guest.business.home', $business));

        // Then I should see the business home
        $this->see($business->name)
             ->see(substr($business->description, 0, 15));
    }
}

Simplify test code by using helpers

Simplify test code by using helpers


<?php

namespace Backend\Modules\Analytics\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class SettingsTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        $this->assertAuthenticationIsNeeded($client, '/private/en/analytics/settings');
    }

    public function testAnalyticsSettingsWorks(Client $client): void
    {
        $this->login($client);

        $crawler = $client->request('GET', '/private/en/analytics/settings');

        self::assertEquals(200, $client->getResponse()->getStatusCode());
        self::assertContains('How to get your secret file?', $crawler->html());
    }
}

<?php

namespace Backend\Modules\Analytics\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class SettingsTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        $this->assertAuthenticationIsNeeded($client, '/private/en/analytics/settings');
    }

    public function testAnalyticsSettingsWorks(Client $client): void
    {
        $this->login($client);

        $this->assertPageLoadedCorrectly($client, '/private/en/analytics/settings', 'How to get your secret file?');
    }
}

Clean up analytics settings action test

Clean up analytics settings action test


<?php
/*
 * This file is part of the RedisBundle package.
 *
 * (c) Axel Etcheverry <axel@etcheverry.biz>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Euskadi31\Bundle\RedisBundle\Redis;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;
use Redis;

/**
 * NativeRedisSessionStorage.
 *
 * Driver for the redis session save handler provided by the redis PHP extension.
 *
 * @see https://github.com/nicolasff/phpredis
 *
 * @author Axel Etcheverry <axel@etcheverry.biz>
 */
class NativeRedisSessionHandler extends NativeSessionHandler
{
    /**
     * Constructor.
     *
     * @param Redis $redis
     */
    public function __construct(Redis $redis)
    {
        ini_set('session.save_handler', 'redis');
        ini_set(
            'session.save_path',
            sprintf('tcp://%s:%d?persistent=0', $redis->getHost(), $redis->getPort())
        );
    }
}

<?php
/*
 * This file is part of the RedisBundle package.
 *
 * (c) Axel Etcheverry <axel@etcheverry.biz>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Euskadi31\Bundle\RedisBundle\Redis;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;
use Redis;

/**
 * NativeRedisSessionStorage.
 *
 * Driver for the redis session save handler provided by the redis PHP extension.
 *
 * @see https://github.com/nicolasff/phpredis
 *
 * @author Axel Etcheverry <axel@etcheverry.biz>
 */
class NativeRedisSessionHandler extends NativeSessionHandler
{
    /**
     * Constructor.
     *
     * @param Redis $redis
     */
    public function __construct(Redis $redis)
    {
        ini_set('session.save_handler', 'redis');
        if($redis->getAuth() === null) {
            ini_set(
                'session.save_path',
                sprintf('tcp://%s:%d?persistent=0', $redis->getHost(), $redis->getPort())
            );
        } else {
            ini_set(
                'session.save_path',
                sprintf('tcp://%s:%d?persistent=0&auth=%s', $redis->getHost(), $redis->getPort(), urlencode($redis->getAuth()))
            );
        }
    }
}

Fix problem Auth when password was requested

English and French following:
A RedisException was thrown when redis was configured with a password

Adding a test to verify that the connexion use a password or not
Adding a parameters for auth in TCP

French:
Une RedisException était déclenchée lorsqu'on tentait d'utiliser un redis configurer avec un mot de passe

Ajout d'un test pour vérifier si Redis est configurer avec un mot de passe
Ajout d'un paramètre auth sur la requête TCP pour les redis avec mot de passe


<?php
	$tags_q = $this->db->get("tags");
	echo "
";
	echo "

Title	Color	Actions

";
	echo "
";
	$odd_even = "odd";
	foreach ($tags_q->result() as $row)
	{
		echo "
";
		echo "" . $row->title . "	";
		echo "" . $this->Tag_model->show_voucher_tag($row->id) . "	";

		echo "" . anchor('tag/edit/' . $row->id , img(array('src' => asset_url() . "images/icons/edit.png", 'border' => '0', 'alt' => 'Edit Tag')), array('title' => 'Edit Tag')) . "	";

		echo "" . anchor('tag/delete/' . $row->id , img(array('src' => asset_url() . "images/icons/delete.png", 'border' => '0', 'alt' => 'Delete Tag', 'class' => "confirmClick", 'title' => "Delete Tag")), array('title' => 'Delete  Tag')) . "	";
		echo "
";
		$odd_even = ($odd_even == "odd") ? "even" : "odd";
	}
	echo "
";
	echo "
";
	echo "
";
	echo anchor('setting', 'Back', array('title' => 'Back to Settings'));

<?php
	$tags_q = $this->db->get("tags");
	echo "
";
	echo "

Title	Color

";
	echo "
";
	$odd_even = "odd";
	foreach ($tags_q->result() as $row)
	{
		echo "
";
		echo "" . $row->title . "	";
		echo "" . $this->Tag_model->show_voucher_tag($row->id) . "	";

		echo "" . anchor('tag/edit/' . $row->id , "Edit", array('title' => 'Edit Tag', 'class' => 'red-link'));
		echo "  ";
		echo anchor('tag/delete/' . $row->id , img(array('src' => asset_url() . "images/icons/delete.png", 'border' => '0', 'alt' => 'Delete Tag', 'class' => "confirmClick", 'title' => "Delete Tag")), array('title' => 'Delete  Tag')) . "	";
		echo "
";
		$odd_even = ($odd_even == "odd") ? "even" : "odd";
	}
	echo "
";
	echo "
";
	echo "
";
	echo anchor('setting', 'Back', array('title' => 'Back to Settings'));

Tag list now uses the simple table style

Signed-off-by: Prashant P Shah <80f978b5ac27fb318171799f0fb6a277863f2bf5@gmail.com>


<?php
/* @var $object Mouf\Html\Widgets\Form\CheckBoxField */
$input = $object->getInput();
$label = $object->getLabel();
$label->addChild($input);
$label->addClass("checkbox-inline");
$label->toHtml();
?>
<!--
<label class="checkbox-inline">
  <input type="checkbox" id="inlineCheckbox1" value="option1"> 1
</label>
 -->

<?php
/* @var $object Mouf\Html\Widgets\Form\CheckBoxField */
$input = $object->getInput();
$label = $object->getLabel();
$text = $label->getChildren();
$text = $text[0];
$label->setChildren([$input]);
$label->addChild($text);
$label->addClass("checkbox-inline");
$label->toHtml();

Set Label's text AFTER checkbox

Set Label's text AFTER checkbox

Signed-off-by: Kevin Nguyen <006815eb9035d5d78bd32c783377981b5c1ce236@thecodingmachine.com>


<?php

namespace Drupal\AppConsole\Generator;

use Symfony\Component\DependencyInjection\Container;

class ControllerGenerator extends Generator {

  private $filesystem;

  public function __construct() {}

  public function generate($module, $name, $controller, $services ) {
    $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module);

    $path_controller = $path . '/lib/Drupal/' . $module . '/Controller';

    $parameters = array(
      'name' => $name,
      'services' => $services,
      'module' => $module
    );

    $this->renderFile(
      'module/module.DefaultController.php.twig',
      $path_controller . '/'. $name .'.php',
      $parameters
    );

    $this->renderFile('module/controller-routing.yml.twig', DRUPAL_ROOT.'/modules/'.$module.'/'.$module.'.routing.yml', $parameters, FILE_APPEND);

  }

}

<?php

namespace Drupal\AppConsole\Generator;

use Symfony\Component\DependencyInjection\Container;

class ControllerGenerator extends Generator {

  private $filesystem;

  public function __construct() {}

  public function generate($module, $name, $controller, $services) {
    $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module);

    $path_controller = $path . '/lib/Drupal/' . $module . '/Controller';

    $parameters = array(
      'name' => $name,
      'services' => $services,
      'module' => $module
    );

    $this->renderFile(
      'module/module.'. $name .'Controller.php.twig',
      $path_controller . '/'. $name .'.php',
      $parameters
    );

    $this->renderFile('module/controller-routing.yml.twig', DRUPAL_ROOT.'/modules/'.$module.'/'.$module.'.routing.yml', $parameters, FILE_APPEND);

  }

}

Fix router name generation at CollerGenerator

* Replace hardcoded text DefaultController with passed argumnet
  {{name}}Controller when rendering routing yml file


<?php

/*
 * This file is part of the Slim Image Resize middleware
 *
 * Copyright (c) 2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-image-resize
 *
 */

namespace Slim\Middleware\ImageResize;

class DefaultMutator extends MutatorAbstract
{
    protected static $regexp = "/(?<original>[^-]+)-(?<size>(?<width>\d*)x(?<height>\d*))-?(?<signature>[0-9a-z]*)/";

    public function execute()
    {
        /* Fit or resize. */
        extract($this->options);
        if (null !== $width && null !== $height) {
            $this->image->fit($width, $height);
        } else {
            $this->image->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
        }

        return $this;
    }
}

<?php

/*
 * This file is part of the Slim Image Resize middleware
 *
 * Copyright (c) 2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-image-resize
 *
 */

namespace Slim\Middleware\ImageResize;

class DefaultMutator extends MutatorAbstract
{
    protected static $regexp = "/(?<original>.+)-(?<size>(?<width>\d*)x(?<height>\d*))-?(?<signature>[0-9a-z]*)/";

    public function execute()
    {
        /* Fit or resize. */
        extract($this->options);
        if (null !== $width && null !== $height) {
            $this->image->fit($width, $height);
        } else {
            $this->image->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
        }

        return $this;
    }
}

Fix regex for images with hypen

[TASK] Fix regex for images with hypen


<?php

namespace Pantheon\Terminus\Commands\Auth;

use Pantheon\Terminus\Commands\TerminusCommand;
use Terminus\Models\Auth;

class WhoamiCommand extends TerminusCommand
{
    /**
     * Displays information about the user currently logged in
     *
     * @command auth:whoami
     * @aliases whoami
     *
     * @usage terminus auth:whoami
     *   Responds with the email of the logged-in user
     * @usage terminus auth:whoami -vvv
     *   Responds with the current session and user's data
     * @return string
     */
    public function whoAmI()
    {
        $auth = new Auth();
        if ($auth->loggedIn()) {
            $user = $this->session()->getUser();
            $this->log()->debug(print_r($user->fetch()->serialize(), true));
            return $user->get('email');
        } else {
            $this->log()->notice('You are not logged in.');
            return null;
        }
    }
}

<?php

namespace Pantheon\Terminus\Commands\Auth;

use Pantheon\Terminus\Commands\TerminusCommand;
use Terminus\Models\Auth;
use Consolidation\OutputFormatters\StructuredData\AssociativeList;

class WhoamiCommand extends TerminusCommand
{
    /**
     * Displays information about the user currently logged in
     *
     * @command auth:whoami
     * @aliases whoami
     *
     * @field-labels
     *   firstname: First Name
     *   lastname: Last Name
     *   email: eMail
     *   id: ID
     * @single-field-default email
     * @usage terminus auth:whoami
     *   Responds with the email of the logged-in user
     * @usage terminus auth:whoami --format=table
     *   Responds with the current session and user's data
     * @return string
     */
    public function whoAmI($options = ['format' => 'string', 'fields' => ''])
    {
        $auth = new Auth();
        if ($auth->loggedIn()) {
            $user = $this->session()->getUser();
            return new AssociativeList($user->fetch()->serialize());
        } else {
            $this->log()->notice('You are not logged in.');
            return null;
        }
    }
}

Use new output formatters feature @single-field-default to reduce table data down to a single element when 'string' format is selected.


<?php
namespace GoRemote\Model;

class CompanyModel
{
	public $id = 0;
	public $name;
	public $url = '';
	public $twitter;
	public $logo;

	public function insert(\Doctrine\DBAL\Connection $db)
	{
		$duplicateId = $db->fetchColumn(
			'select companyid from companies where name=?',
			[
				(string) $this->name
			]);

		if ($duplicateId) {
			$this->id = $duplicateId;
			return $duplicateId;
		}

		$company = [
			'name' => $this->name,
			'dateadded' => date('Y-m-d H:i:s'),
			'logo' => $this->logo,
			'twitter' => $this->twitter,
			'url' => $this->url
		];

		$db->insert('companies', $company);
		$this->id = $db->lastInsertId();
		return $this->id;
	}
}

<?php
namespace GoRemote\Model;

class CompanyModel
{
	public $id = 0;
	public $name;
	public $url = '';
	public $twitter;
	public $logo;

	public function insert(\Doctrine\DBAL\Connection $db)
	{
		$duplicateId = $db->fetchAssoc(
			'select companyid, url, logo from companies where name=?',
			[
				(string) $this->name
			]);

		if ($duplicateId) {
            if (empty($duplicateId['logo']) && !empty($this->logo)) {
                $db->createQueryBuilder()
                    ->update('companies')
                    ->set('logo', '?')
                    ->where('companyid = ?')
                    ->setParameter(0, $this->logo)
                    ->setParameter(1, $duplicateId['companyid']);
            }
			$this->id = $duplicateId;
			return $duplicateId;
		}

		$company = [
			'name' => $this->name,
			'dateadded' => date('Y-m-d H:i:s'),
			'logo' => $this->logo,
			'twitter' => $this->twitter,
			'url' => $this->url
		];

		$db->insert('companies', $company);
		$this->id = $db->lastInsertId();
		return $this->id;
	}
}

Update company logos if they didn't previously have one but they do now


<?php

namespace Kazoo\Api\Resource;
use Kazoo\Api\AbstractResource;

/**
 *
 */
class Media extends AbstractResource {

    protected static $_entity_class = "Kazoo\\Api\\Data\\Entity\\Media";
    protected static $_entity_collection_class = "Kazoo\\Api\\Data\\Collection\\MediaCollection";

}

<?php

namespace Kazoo\Api\Resource;
use Kazoo\Api\AbstractResource;

/**
 *
 */
class Media extends AbstractResource {

    protected static $_entity_class = "Kazoo\\Api\\Data\\Entity\\Media";
    protected static $_entity_collection_class = "Kazoo\\Api\\Data\\Collection\\MediaCollection";

    public function __call($name, $arguments) {

        switch (strtolower($name)) {
            case 'raw':
                if (empty($arguments[0])) return "";
                $resource_id = $arguments[0];

                $uri = $this->_client->getTokenizedUri($this->_uri) . "/" . urlencode($resource_id) . "/raw?auth_token=" . urlencode($this->_client->getAuthToken());

                if (!empty($arguments[1]))
                    return file_get_contents($uri);
                else
                    return $uri;

                break;
            default:
                parent::__call($name, $arguments);
        }
    }
}

Add support to download raw media

Add support to download raw media


<?php

class EngineBlock_Corto_Filter_Command_AttributeAggregator extends EngineBlock_Corto_Filter_Command_Abstract
{
    /**
     * This command may modify the response attributes
     *
     * @return array
     */
    public function getResponseAttributes()
    {
        return $this->_responseAttributes;
    }

    public function execute()
    {
        $logger = EngineBlock_ApplicationSingleton::getLog();

        $serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider(
            $this->_serviceProvider,
            $this->_request,
            $this->_server->getRepository()
        );

        if (!$serviceProvider) {
            $serviceProvider = $this->_serviceProvider;
        }

        if (!$serviceProvider->attributeAggregationRequired) {
            $logger->notice("No Attribute Aggregation for " . $serviceProvider->entityId);
            return;
        }

        $spEntityId = $serviceProvider->entityId;

        $logger->notice("Attribute Aggregation for $spEntityId");

        $aggregator = $this->_getAggregator();

        $aggregations = $aggregator->aggregate(
            $this->_collabPersonId,
            $spEntityId,
            $this->_responseAttributes
        );

        $this->_responseAttributes = array_merge($this->_responseAttributes, $aggregations);
    }

    /**
     * @return EngineBlock_AttributeAggregation_Aggregator
     */
    protected function _getAggregator()
    {
        return new AttributeAggregation_Client(EngineBlock_ApplicationSingleton::getInstance()->getConfiguration());
    }
}

<?php

class EngineBlock_Corto_Filter_Command_AttributeAggregator extends EngineBlock_Corto_Filter_Command_Abstract
{
    /**
     * This command may modify the response attributes
     *
     * @return array
     */
    public function getResponseAttributes()
    {
        return $this->_responseAttributes;
    }

    public function execute()
    {
        $logger = EngineBlock_ApplicationSingleton::getLog();

        $serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider(
            $this->_serviceProvider,
            $this->_request,
            $this->_server->getRepository()
        );

        if (!$serviceProvider) {
            $serviceProvider = $this->_serviceProvider;
        }

        if (!$serviceProvider->attributeAggregationRequired) {
            $logger->info("No Attribute Aggregation for " . $serviceProvider->entityId);
            return;
        }

        $spEntityId = $serviceProvider->entityId;

        $logger->notice("Attribute Aggregation for $spEntityId");

        $aggregator = $this->_getAggregator();

        $aggregations = $aggregator->aggregate(
            $this->_collabPersonId,
            $spEntityId,
            $this->_responseAttributes
        );

        $this->_responseAttributes = array_merge($this->_responseAttributes, $aggregations);
    }

    /**
     * @return EngineBlock_AttributeAggregation_Aggregator
     */
    protected function _getAggregator()
    {
        return new AttributeAggregation_Client(EngineBlock_ApplicationSingleton::getInstance()->getConfiguration());
    }
}

Make "No Attribute Aggregation for $SP" log message level info.

This is a common case so not really deserving of notice status.


<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Proxy;

use ProxyManager\FileLocator\FileLocator as BaseFileLocator;
use function mkdir;
use function realpath;

/**
 * @internal
 */
final class FileLocator extends BaseFileLocator
{
    public function __construct(string $proxiesDirectory)
    {
        $absolutePath = realpath($proxiesDirectory);

        if ($absolutePath === false) {
            mkdir($proxiesDirectory, 0755, true);
        }

        parent::__construct($proxiesDirectory);
    }
}

<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Proxy;

use ProxyManager\FileLocator\FileLocator as BaseFileLocator;
use function mkdir;
use function realpath;

/**
 * @internal
 */
final class FileLocator extends BaseFileLocator
{
    public function __construct(string $proxiesDirectory)
    {
        $absolutePath = realpath($proxiesDirectory);

        if ($absolutePath === false) {
            mkdir($proxiesDirectory, 0775, true);
        }

        parent::__construct($proxiesDirectory);
    }
}

Fix dir permissions for proxies

Fix dir permissions for proxies


<?php

/**
 * This empty class ensures a proper naming standard
 * @see Phpr_Extension
 */

class Phpr_Extendable extends Phpr_Extension
{

}

<?php

/**
 * Base class for extension validation
 * @see Phpr_Extension
 */

class Phpr_Validate_Extension extends Phpr_Extension
{

    public function _execute_validation($method, $name, $value)
    {
        if (method_exists($this, $method))
            return $this->$method($name, $value);

        throw new Phpr_SystemException('Validation method '.$method.' not found in '.get_class($this));
    }

}

Set up base class for extension validation


@section("field")

    <input name="{{ $prefixed_field_name }}" id="{{ $field_id }}" type="hidden" value="{{ $field_value }}">
@overwrite

@section("footer.js")
    @parent

@stop

Fix JSON field for multiple instances

Fix JSON field for multiple instances


<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/stylus.php';

class StylusView implements Component {
  private $css;

  public function __construct(Stylus $stylus) {
    $this->css = $stylus->toString();
  }

  public static function fromString(Stylus $stylus, string $styl): self {
    return new self($stylus->fromString($styl));
  }

  public static function fromFile(Stylus $stylus, string $filename): self {
    return new self($stylus->fromFile($filename));
  }

  public function render(): Component {
    return HtmlElement::create('style', array(
      'type' => 'text/css',
      new UnescapedText($this->css)
    ));
  }
}
?>

<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/stylus.php';
use NodejsPhpFallback\Stylus;

class StylusView implements Component {
  private $css;

  public function __construct(Stylus $stylus) {
    $this->css = $stylus->getCss();
  }

  static public function instance(string $str): self {
    return new self(new Stylus($str));
  }

  public function render(): Component {
    return HtmlElement::create('style', array(
      'type' => 'text/css',
      new UnescapedText($this->css)
    ));
  }
}
?>

Update StylusView to match new submodule


<?php

/*
 * This file is part of the Bukashk0zzzTimestampTypeBundle
 *
 * (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception;

/**
 * Class TimestampToDateTimeTransformer
 * @author Denis Golubovskiy <bukashk0zzz@gmail.com>
 */
class TimestampToDateTimeTransformer implements DataTransformerInterface
{
    /**
     * @param mixed $value
     * @return int|mixed
     */
    public function transform($value)
    {
        if ($value instanceof \DateTime) {
            return $value->getTimestamp();
        }

        return $value;
    }

    /**
     * @param mixed $value
     * @return \DateTime|null
     */
    public function reverseTransform($value)
    {
        if ($value) {
            return new \DateTime('@'.$value);
        }

        return null;
    }
}

<?php

/*
 * This file is part of the Bukashk0zzzTimestampTypeBundle
 *
 * (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception;

/**
 * Class TimestampToDateTimeTransformer
 * @author Denis Golubovskiy <bukashk0zzz@gmail.com>
 */
class TimestampToDateTimeTransformer implements DataTransformerInterface
{
    /**
     * @param mixed $value
     * @return int|mixed
     */
    public function transform($value)
    {
        if ($value instanceof \DateTime) {
            return $value->getTimestamp();
        }

        return $value;
    }

    /**
     * @param mixed $value
     * @return \DateTime|null
     */
    public function reverseTransform($value)
    {
        if ($value) {
            $date = new \DateTime();
            return $date->setTimestamp($value);
        }

        return null;
    }
}

Fix bug with old dates

Fix bug with old dates


<?php namespace peer;

/**
 * OutputStream that reads from a socket
 */
class SocketOutputStream extends \lang\Object implements \io\streams\SocketOutputStream {
  protected $socket= null;

  /**
   * Constructor
   *
   * @param   peer.Socket socket
   */
  public function __construct(Socket $socket) {
    $this->socket= $socket;
    $this->socket->isConnected() || $this->socket->connect();
  }

  /**
   * Write a string
   *
   * @param   var arg
   */
  public function write($arg) {
    $this->socket->write($arg);
  }

  /**
   * Flush this buffer
   *
   */
  public function flush() {
    // NOOP, sockets cannot be flushed
  }

  /**
   * Close this buffer
   *
   */
  public function close() {
    $this->socket->isConnected() && $this->socket->close();
  }

  /**
   * Creates a string representation of this output strean
   *
   * @return  string
   */
  public function toString() {
    return nameof($this).'<'.$this->socket->toString().'>';
  }
}

<?php namespace peer;

/**
 * OutputStream that reads from a socket
 */
class SocketOutputStream extends \lang\Object implements \io\streams\OutputStream {
  protected $socket= null;

  /**
   * Constructor
   *
   * @param   peer.Socket socket
   */
  public function __construct(Socket $socket) {
    $this->socket= $socket;
    $this->socket->isConnected() || $this->socket->connect();
  }

  /**
   * Write a string
   *
   * @param   var arg
   */
  public function write($arg) {
    $this->socket->write($arg);
  }

  /**
   * Flush this buffer
   *
   */
  public function flush() {
    // NOOP, sockets cannot be flushed
  }

  /**
   * Close this buffer
   *
   */
  public function close() {
    $this->socket->isConnected() && $this->socket->close();
  }

  /**
   * Creates a string representation of this output strean
   *
   * @return  string
   */
  public function toString() {
    return nameof($this).'<'.$this->socket->toString().'>';
  }
}

Fix "Interface `io\streams\SocketOutputStream` not found


<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Realms\Server;

class RealmsController extends Controller
{
    public function listing()
    {
        return view('realms', ['realms' => Server::all()]);
    }
}

<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Realms\Player;
use App\Realms\Server;
use Illuminate\Http\Request;

class RealmsController extends Controller
{
    /**
     * Get Realms management page.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listing()
    {
        return view('realms', ['realms' => Server::all()]);
    }

    /**
     * Create new Realm.
     * Should be called with AJAX.
     *
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request)
    {
        // Validate request.
        $this->validate($request, [
            'name' => 'required|max:32',
            'owner' => 'required|max:64'
        ]);
        $realmName = $request->input('name');
        $owner = $request->input('owner');

        // Get owner's UUID
        $player = new Player(null, $owner);
        $player->lookupFromApi();
        if ($player->uuid === null) {
            // Bad username error.
            return [
                'success' => false,
                'error' => 'bad_username'
            ];
        }

        // Create Realm.
        $realm = new Server();
        $realm->name = $realmName;
        $realm->owner = $player;
        $realm->state = Server::STATE_UNINITIALIZED;
        $realm->save();

        // All good!
        return [
            'success' => true
        ];
    }
}

Add create Realm controller method.

Add create Realm controller method.


<?php

namespace Oro\Bundle\ReminderBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

class ReminderRepository extends EntityRepository
{
}

<?php

namespace Oro\Bundle\ReminderBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

use Oro\Bundle\ReminderBundle\Entity\Reminder;

class ReminderRepository extends EntityRepository
{
    /**
     * @return Reminder[]
     */
    public function getRemindersToProcess()
    {
        return $this->createQueryBuilder('r')
            ->where('r.isSent = false')
            ->getQuery()
            ->execute();
    }
}

BAP-3442: Create Reminder entities
- create repo method


<?php

/*
 Invokes the mail() function in Swift Mailer.

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

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

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

 */

//@require 'Swift/Transport/MailInvoker.php';

/**
 * This is the implementation class for {@link Swift_Transport_MailInvoker}.
 *
 * @package Swift
 * @subpackage Transport
 * @author Chris Corbyn
 */
class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker
{

  /**
   * Send mail via the mail() function.
   *
   * This method takes the same arguments as PHP mail().
   *
   * @param string $to
   * @param string $subject
   * @param string $body
   * @param string $headers
   * @param string $extraParams
   *
   * @return boolean
   */
  public function mail($to, $subject, $body, $headers = null, $extraParams = null)
  {
    return mail($to, $subject, $body, $headers, $extraParams);
  }

}

<?php

/*
 Invokes the mail() function in Swift Mailer.

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

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

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

 */

//@require 'Swift/Transport/MailInvoker.php';

/**
 * This is the implementation class for {@link Swift_Transport_MailInvoker}.
 *
 * @package Swift
 * @subpackage Transport
 * @author Chris Corbyn
 */
class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker
{

  /**
   * Send mail via the mail() function.
   *
   * This method takes the same arguments as PHP mail().
   *
   * @param string $to
   * @param string $subject
   * @param string $body
   * @param string $headers
   * @param string $extraParams
   *
   * @return boolean
   */
  public function mail($to, $subject, $body, $headers = null, $extraParams = null)
  {
    if (!ini_get('safe_mode'))
    {
      return mail($to, $subject, $body, $headers, $extraParams);
    }
    else
    {
      return mail($to, $subject, $body, $headers);
    }
  }

}

Check for safe_mode before passing 5th parameter to mail()


<?php

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

namespace Sylius\Component\Currency\Context;

use Sylius\Component\Model\CurrencyInterface;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    /**
     * Get the default currency.
     *
     * @return CurrencyInterface
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return CurrencyInterface
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param CurrencyInterface $currency
     */
    public function setCurrency($currency);
}

<?php

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

namespace Sylius\Component\Currency\Context;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    /**
     * Get the default currency.
     *
     * @return string
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return string
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param string $currency
     */
    public function setCurrency($currency);
}

Fix behat context & fixtures after latest merges


<?php
namespace LazyRecord\Schema\Column;
use LazyRecord\Schema\ColumnDeclare;

class AutoIncrementPrimaryKeyColumn extends ColumnDeclare
{
    public function __construct()
    {
        parent::__construct('id');
        $this->isa('int')
            ->integer()
            ->notNull()
            ->primary()
            ->autoIncrement();
    }
}

<?php
namespace LazyRecord\Schema\Column;
use LazyRecord\Schema\ColumnDeclare;

class AutoIncrementPrimaryKeyColumn extends ColumnDeclare
{
    public function __construct()
    {
        parent::__construct('id');
        $this->isa('int')
            ->integer()
            ->notNull()
            ->primary()
            ->autoIncrement();
    }

    /**
     * Create primary key column with autoIncrement and unsigned.
     */
    static public function forMySQL($type = 'bigint')
    {
        $column = new ColumnDeclare('id');
        $column->isa('int');
        $column->type($type);
        $column->unsigned();
        $column->notNull();
        $column->primary()->autoIncrement();
        return $column;
    }

}

Add optimized auto increment primary key for mysql


<?php

/**
 * This file is part of the silex-annotation-provider package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 * @copyright (c) 2013, Dana Desrosiers <dana.desrosiers@gmail.com>
 */

namespace DDesrosiers\SilexAnnotations\Annotations;

use Silex\Application;
use Silex\Controller;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * @Annotation
 * @Target({"METHOD", "ANNOTATION"})
 */
class Secure implements RouteAnnotation
{
    /** @var mixed */
    public $role;

    /**
     * @param Controller $route
     */
    public function process(Controller $route)
    {
        $roles = $this->role;
        $route->before(
            function (SymfonyRequest $request, Application $app) use ($roles) {
                if (!$app["security"]->isGranted($roles)) {
                    throw new AccessDeniedException();
                }
            }
        );
    }
}

<?php

/**
 * This file is part of the silex-annotation-provider package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 * @copyright (c) 2013, Dana Desrosiers <dana.desrosiers@gmail.com>
 */

namespace DDesrosiers\SilexAnnotations\Annotations;

use Silex\Application;
use Silex\Controller;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * @Annotation
 * @Target({"METHOD", "ANNOTATION"})
 */
class Secure implements RouteAnnotation
{
    /** @var mixed */
    public $role;

    /**
     * @param Controller $route
     */
    public function process(Controller $route)
    {
        if (method_exists($route, "secure")) {
            $route->secure($this->role);
        } else {
            $roles = $this->role;
            $route->before(
                function (SymfonyRequest $request, Application $app) use ($roles) {
                    if (!$app["security"]->isGranted($roles)) {
                        throw new AccessDeniedException();
                    }
                }
            );
        }
    }
}

Use the Security trait method if it exists


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Requests;

use Cortex\Foundation\Http\FormRequest;

class ImportFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'file.*' => 'required|file|mimetypes:application/vnd.ms-excel',
        ];
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Requests;

use Cortex\Foundation\Http\FormRequest;

class ImportFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'file.*' => 'required|file|mimetypes:'.implode(',', config('cortex.foundation.datatables.imports')),
        ];
    }
}

Fix datatable import extensions to be dynamic/configurable


<?php
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\TestCase;

class ExceptionMessageRegExpTest extends TestCase
{
    /**
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/
     */
    public function testRegexMessage()
    {
        throw new \Exception('A polymorphic exception message');
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i
     */
    public function testRegexMessageExtreme()
    {
        throw new \Exception('A polymorphic exception message');
    }

    /**
     * @runInSeparateProcess
     * @requires extension xdebug
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp #Screaming preg_match#
     */
    public function testMessageXdebugScreamCompatibility()
    {
        \ini_set('xdebug.scream', '1');

        throw new \Exception('Screaming preg_match');
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage A variadic exception message
     * @expectedExceptionMessageRegExp /^A variadic \w+ message/
     */
    public function testSimultaneousLiteralAndRegExpExceptionMessage()
    {
        throw new \Exception('A variadic exception message');
    }
}

<?php
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\TestCase;

class ExceptionMessageRegExpTest extends TestCase
{
    /**
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/
     */
    public function testRegexMessage()
    {
        throw new \Exception('A polymorphic exception message');
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i
     */
    public function testRegexMessageExtreme()
    {
        throw new \Exception('A polymorphic exception message');
    }

    /**
     * @runInSeparateProcess
     * @requires extension xdebug
     * @expectedException \Exception
     * @expectedExceptionMessageRegExp #Screaming preg_match#
     */
    public function testMessageXdebugScreamCompatibility()
    {
        \ini_set('xdebug.scream', '1');

        throw new \Exception('Screaming preg_match');
    }

    /**
     * @expectedException \Exception variadic
     * @expectedExceptionMessageRegExp /^A variadic \w+ message/
     */
    public function testSimultaneousLiteralAndRegExpExceptionMessage()
    {
        throw new \Exception('A variadic exception message');
    }
}

Revert "Change test case with partial message in expectedExceptino annotation to use full expectedExceptionMessage one"

This reverts commit b5ff03e2117f38fa5af341b10cc877bc62fa2a81.


@extends('helpdesk::tickets.show.action')

@section('action-content')
  {{ $action->name }}

  Pool Name: {{ $action->object->pool->name }}

  By: {{ $action->object->agent->name or 'System Process' }}
@overwrite

@section('action-note')
@overwrite

@extends('helpdesk::tickets.show.action')

@section('action-content')
  Assigned To Team

  Team Name: {{ $action->object->pool->name }}

  By: {{ $action->object->agent->name or 'System Process' }}
@overwrite

@section('action-note')
@overwrite

Change action name from pool to team

Change action name from pool to team


<?php

namespace Korobi\WebBundle\Test\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase {

    public function testIndexLoadsSuccessfully() {
        $client = static::createClient();
        $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }

    public function testIndexWithLightTheme() {
        $client = static::createClient();

        $theme = $this->getMockBuilder('Korobi\WebBundle\Util\ThemeService')
            ->disableOriginalConstructor()
            ->getMock();

        $theme->expects($this->any())->method("isLight")->will($this->returnValue(true));
        $client->getContainer()->set('korobi.theme_service', $theme);

        $crawler = $client->request('GET', '/');

        $this->assertTrue($crawler->filter('body.light')->count() > 0);
        // everything resets..
        $crawler = $client->request('GET', '/');
        $this->assertTrue($crawler->filter('body.light')->count() === 0);
    }

}

<?php

namespace Korobi\WebBundle\Test\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase {

    public function testIndexLoadsSuccessfully() {
        $client = static::createClient();
        $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }

    public function testIndexWithLightTheme() {
        $client = static::createClient();

        $theme = $this->getMockBuilder('Korobi\WebBundle\Util\ThemeService')
            ->disableOriginalConstructor()
            ->getMock();

        $theme->expects($this->any())->method("isLight")->will($this->returnValue(true));
        $client->getContainer()->set('korobi.theme_service', $theme);

        $crawler = $client->request('GET', '/');

        $this->assertTrue($crawler->filter('body.light')->count() > 0);
        // everything resets..
        $crawler = $client->request('GET', '/');
        $this->assertTrue($crawler->filter('body.light')->count() === 0);
    }

    public function testBranchAndCommitDisplayedInFooter() {
        $client = static::createClient();

        $gitInfo = $this->getMockBuilder('Korobi\WebBundle\Util\GitInfo')
            ->disableOriginalConstructor()
            ->getMock();

        $gitInfo->expects($this->any())->method("getBranch")->will($this->returnValue("dummy_branch"));
        $gitInfo->expects($this->any())->method("getShortHash")->will($this->returnValue("1234567"));
        $client->getContainer()->set('korobi.git_info', $gitInfo);

        $crawler = $client->request('GET', '/');

        $this->assertTrue($crawler->filter('footer.footer .footer--copyright:contains("dummy_branch")')->count() > 0);
        $this->assertTrue($crawler->filter('footer.footer .footer--copyright:contains("1234567")')->count() > 0);
    }

}

Expand unit testing coverage to cover git branch/commit info in footer


<?php
/**
 * This code is free software; you can redistribute it and/or modify it under
 * the terms of the new BSD License.
 *
 * Copyright (c) 2011-2012, Sebastian Staudt
 *
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

error_reporting(E_ALL & ~E_USER_NOTICE | E_STRICT);

require_once dirname(__FILE__) . "/../lib/steam-condenser.php";

function getFixture($fileName) {
    return file_get_contents(dirname(__FILE__) . "/fixtures/$fileName");
}

<?php
/**
 * This code is free software; you can redistribute it and/or modify it under
 * the terms of the new BSD License.
 *
 * Copyright (c) 2011-2012, Sebastian Staudt
 *
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

error_reporting(E_ALL & ~E_USER_NOTICE | E_STRICT);

require_once dirname(__FILE__) . "/../vendor/autoload.php";
require_once dirname(__FILE__) . "/../lib/steam-condenser.php";

function getFixture($fileName) {
    return file_get_contents(dirname(__FILE__) . "/fixtures/$fileName");
}

Load Composer dependencies during tests

Load Composer dependencies during tests


<?php

namespace Oro\Bundle\LocaleBundle\Form\Type;

use Oro\Bundle\FormBundle\Form\Type\OroEntitySelectOrCreateInlineType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LocalizationSelectType extends AbstractType
{
    const NAME = 'oro_locale_localization_select';

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'autocomplete_alias' => LocalizationType::class,
                'create_form_route' => 'oro_locale_localization_create',
                'configs' => [
                    'placeholder' => 'oro.locale.localization.form.placeholder.choose',
                ]
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return OroEntitySelectOrCreateInlineType::class;
    }
}

<?php

namespace Oro\Bundle\LocaleBundle\Form\Type;

use Oro\Bundle\FormBundle\Form\Type\OroEntitySelectOrCreateInlineType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LocalizationSelectType extends AbstractType
{
    const NAME = 'oro_locale_localization_select';

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'autocomplete_alias' => 'oro_localization',
                'create_form_route' => 'oro_locale_localization_create',
                'configs' => [
                    'placeholder' => 'oro.locale.localization.form.placeholder.choose',
                ]
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return OroEntitySelectOrCreateInlineType::class;
    }
}

BAP-16838: Fix form types issues for commerce application
- revert autocomplete_aliases changes


<?php

namespace Terminus\Loggers;

class Regular {

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

  protected function write( $handle, $str ) {
    fwrite( $handle, $str );
  }

  private function _line( $message, $label, $color, $handle = STDOUT ) {
    $label = \cli\Colors::colorize( "$color$label:%n", $this->in_color );
    $this->write( $handle, "$label $message\n" );
  }

  function info( $message ) {
    $this->write( STDOUT, $message . "\n" );
  }

  function success( $message ) {
    $this->_line( $message, 'Success', '%G' );
  }

  function warning( $message ) {
    $this->_line( $message, 'Warning', '%C', STDERR );
  }

  function error( $message ) {
    $this->_line( $message, 'Error', '%R', STDERR );
  }
}

<?php

namespace Terminus\Loggers;

class Regular {
  static $instance;

  function __construct( $in_color ) {
    $this->in_color = $in_color;
    self::$instance = $this;
  }

  protected function write( $handle, $str ) {
    fwrite( $handle, $str );
  }

  private function _line( $message, $label, $color, $handle = STDOUT ) {
    $label = \cli\Colors::colorize( "$color$label:%n", $this->in_color );
    $this->write( $handle, "$label $message\n" );
  }

  function info( $message ) {
    $this->write( STDOUT, $message . "\n" );
  }

  function success( $message ) {
    $this->_line( $message, 'Success', '%G' );
  }

  function warning( $message ) {
    $this->_line( $message, 'Warning', '%C', STDERR );
  }

  function error( $message ) {
    $this->_line( $message, 'Error', '%R', STDERR );
  }

  static function notify( $message ) {
    return new \cli\notify\Dots($message, 5, 0);
  }

  static function redLine($message = " ") {
    $cli = new Self('%1%K');
    $message = \cli\Colors::colorize( "%1%K$message%n", $cli->in_color );
    $cli->write( STDOUT, "$message\n");
  }
}

Add a function to print exception line

Add a function to print exception line


<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration to add primary key to hosttype table
 **/

class Migration20180924153232ComTools extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		if ($mwdb->tableExists('hosttype'))
		{
			if (!$mwdb->tableHasKey('hosttype', 'name'))
			{
				$query = "ALTER TABLE `hosttype` ADD PRIMARY KEY (name)";
				$mwdb->setQuery($query);
				$mwdb->query();
			}
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		if ($mwdb->tableExists('hosttype'))
		{
			if ($mwdb->getPrimaryKey('hosttype') == 'name')
			{
				$query = "ALTER TABLE `hosttype` DROP PRIMARY KEY";
				$mwdb->setQuery($query);
				$mwdb->query();
			}
		}
	}
}

<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration to add primary key to hosttype table
 **/

class Migration20180924153232ComTools extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		if ($mwdb->tableExists('hosttype'))
		{
			if (!$mwdb->tableHasKey('hosttype', 'name') && !$mwdb->getPrimaryKey('hosttype'))
			{
				$query = "ALTER TABLE `hosttype` ADD PRIMARY KEY (name)";
				$mwdb->setQuery($query);
				$mwdb->query();
			}
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		if ($mwdb->tableExists('hosttype'))
		{
			if ($mwdb->getPrimaryKey('hosttype') == 'name')
			{
				$query = "ALTER TABLE `hosttype` DROP PRIMARY KEY";
				$mwdb->setQuery($query);
				$mwdb->query();
			}
		}
	}
}

Check for primary key too

[fix] Check for primary key too


<?php
namespace KwfBundle\Serializer\KwfModel\ColumnNormalizer;
use Kwf_Model_Row_Interface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;

class ChildRows implements ColumnNormalizerInterface, SerializerAwareInterface
{
    /**
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array())
    {
        if (!isset($settings['rule'])) {
            throw new \Exception("rule setting is required");
        }
        $rows = $row->getChildRows($settings['rule']);
        if (isset($settings['child_groups'])) {
            $context['groups'] = $settings['child_groups'];
        } else if (isset($settings['groups'])) {
            $context['groups'] = $settings['groups'];
        }
        return $this->serializer->normalize($rows, $format, $context);
    }
}

<?php
namespace KwfBundle\Serializer\KwfModel\ColumnNormalizer;
use Kwf_Model_Row_Interface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;

class ChildRows implements ColumnNormalizerInterface, SerializerAwareInterface
{
    /**
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array())
    {
        if (!isset($settings['rule'])) {
            throw new \Exception("rule setting is required");
        }
        $select = new \Kwf_Model_Select(isset($settings['where']) ? $settings['where'] : array());
        $rows = $row->getChildRows($settings['rule'], $select);
        if (isset($settings['child_groups'])) {
            $context['groups'] = $settings['child_groups'];
        } else if (isset($settings['groups'])) {
            $context['groups'] = $settings['groups'];
        }
        return $this->serializer->normalize($rows, $format, $context);
    }
}

Allow adding a select-where to symfony child-rows-serializer


<?php

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

class CreateNewEventsTableSchema extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('eventable');
            $table->json('content');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateNewEventsTableSchema extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('eventable');
            $table->text('content');
            $table->timestamps();
        });
    }

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

Store event column in text field

Store event column in text field


<?php

class Edge_Loyalty_Model_Price_Observer
{
    public function getFinalPrice(Varien_Event_Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $loyaltyType = $product->getLoyaltyType();
        if ($loyaltyType) {
            if ($product->getData($loyaltyType) !== $product->getLoyaltyPrice()) {
                $product->setData($loyaltyType, $product->getLoyaltyPrice());
            }
        }
    }

    public function catalogProductLoadAfter(Varien_Event_Observer $observer)
    {
        $helper = Mage::helper('loyalty');
        if ($helper->isEligible()) {
            $helper->applyLoyaltyDiscount($observer->getEvent()->getProduct(), 'special');
        }
    }

    public function catalogProductCollectionLoadAfter(Varien_Event_Observer $observer)
    {
        $helper = Mage::helper('loyalty');
        if ($helper->isEligible()) {
            foreach ($observer->getEvent()->getCollection() as $product) {
                $helper->applyLoyaltyDiscount($product, 'final');
            }
        }
    }
}

<?php

class Edge_Loyalty_Model_Price_Observer
{
    public function getFinalPrice(Varien_Event_Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $loyaltyType = $product->getLoyaltyType();
        if ($loyaltyType) {
            if ($product->getData($loyaltyType) !== $product->getLoyaltyPrice()) {
                $product->setData($loyaltyType, $product->getLoyaltyPrice());
            }
        }
    }

    public function catalogProductLoadAfter(Varien_Event_Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        if ($product->getData('no_loyalty_calculation')) {
            return;
        }

        $helper = Mage::helper('loyalty');
        if ($helper->isEligible()) {
            $helper->applyLoyaltyDiscount($product, 'special');
        }
    }

    public function catalogProductCollectionLoadAfter(Varien_Event_Observer $observer)
    {
        $helper = Mage::helper('loyalty');
        if ($helper->isEligible()) {
            foreach ($observer->getEvent()->getCollection() as $product) {
                $helper->applyLoyaltyDiscount($product, 'final');
            }
        }
    }
}

Allow Loading Product Without Loyalty Pricing Being Applied


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

class Search_Index_TypeAnalysisDecorator extends Search_Index_AbstractIndexDecorator
{
	private $identifierClass;
	private $mapping = array();

	function __construct(Search_Index_Interface $index)
	{
		parent::__construct($index);
		$this->identifierClass = get_class($index->getTypeFactory()->identifier(1));
	}

	function addDocument(array $document)
	{
		$new = array_diff_key($document, $this->mapping);
		foreach ($new as $key => $value) {
			$this->mapping[$key] = $value instanceof $this->identifierClass;
		}
		return $this->parent->addDocument($document);
	}

	function getIdentifierFields()
	{
		return array_keys(array_filter($this->mapping));
	}
}

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

class Search_Index_TypeAnalysisDecorator extends Search_Index_AbstractIndexDecorator
{
	private $identifierClass;
	private $numericClass;
	private $mapping = array();

	function __construct(Search_Index_Interface $index)
	{
		parent::__construct($index);
		$this->identifierClass = get_class($index->getTypeFactory()->identifier(1));
		$this->numericClass = get_class($index->getTypeFactory()->numeric(1));
	}

	function addDocument(array $document)
	{
		$new = array_diff_key($document, $this->mapping);
		foreach ($new as $key => $value) {
			$this->mapping[$key] = $value instanceof $this->identifierClass || $value instanceof $this->numericClass;
		}
		return $this->parent->addDocument($document);
	}

	function getIdentifierFields()
	{
		return array_keys(array_filter($this->mapping));
	}
}

[FIX] Test broken after introduction of numeric type

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


<?php

use Phinx\Migration\AbstractMigration;

class AllowNullOnIndexesContextId extends AbstractMigration {
	public function change() {
		if(defined('ORM_ID_AS_UID') && ORM_ID_AS_UID){
			$strategy = ! defined('ORM_UID_STRATEGY') ? 'php' : ORM_UID_STRATEGY;
			$t = $this->table('indexes');
			switch($strategy){
				case 'mysql':
				case 'laravel-uuid':
						$t->changeColumn('context_id', 'char', ['limit' => 36, "null" => true])->update();
					break;
				default:
				case 'php':
					$t->changeColumn('context_id', 'char', ['limit' => 23, "null" => true])->update();
					break;
			}
		}
		else{
			$t = $this->table('indexes');
			$t->changeColumn('context_id', 'integer', ["null" => true])->update();
		}
	}
}

<?php

use Phinx\Migration\AbstractMigration;

class AllowNullOnIndexesContextId extends AbstractMigration {
	public function up() {
		if(defined('ORM_ID_AS_UID') && ORM_ID_AS_UID){
			$strategy = ! defined('ORM_UID_STRATEGY') ? 'php' : ORM_UID_STRATEGY;
			$t = $this->table('indexes');
			switch($strategy){
				case 'mysql':
				case 'laravel-uuid':
						$t->changeColumn('context_id', 'char', ['limit' => 36, "null" => true])->update();
					break;
				default:
				case 'php':
					$t->changeColumn('context_id', 'char', ['limit' => 23, "null" => true])->update();
					break;
			}
		}
		else{
			$t = $this->table('indexes');
			$t->changeColumn('context_id', 'integer', ["null" => true])->update();
		}
	}
	public function down(){
		if(defined('ORM_ID_AS_UID') && ORM_ID_AS_UID){
			$strategy = ! defined('ORM_UID_STRATEGY') ? 'php' : ORM_UID_STRATEGY;
			$t = $this->table('indexes');
			switch($strategy){
				case 'mysql':
				case 'laravel-uuid':
					$t->changeColumn('context_id', 'char')->update();
					break;
				default:
				case 'php':
					$t->changeColumn('context_id', 'char')->update();
					break;
			}
		}
		else{
			$t = $this->table('indexes')
				->changeColumn('context_id', 'integer')->update();
		}
	}
}

Set Up & Down fct for AllowNullOnIndexesContextId

changeColumn can't be revert


<?php
class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {

    }
}

<?php
class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

CC-5781: Upgrade script for new storage quota implementation


<?php

namespace spec\MageTest\MagentoExtension\Fixture;

use PHPSpec2\Specification;

class Product implements Specification
{
    function described_with()
    {
        \Mage::app();
        $this->productModel = \Mockery::mock(new \Mage_Catalog_Model_Product());

        $productModel = $this->productModel;

        $factory = function () use ($productModel) { return $productModel; };
        $this->product->isAnInstanceOf('MageTest\MagentoExtension\Fixture\Product', array($factory));
    }

    function it_should_create_a_product_given_all_required_attributes()
    {
        $this->productModel->shouldReceive('setData')->once()->andReturn($this->productModel)->ordered();
        $this->productModel->shouldReceive('save')->once()->andReturn(true)->ordered();

        $this->product->create(
            array(
                'sku' => 'sku1'
            )
        );
    }
}

<?php

namespace spec\MageTest\MagentoExtension\Fixture;

use PHPSpec2\Specification;

class Product implements Specification
{
    function described_with()
    {
        \Mage::app();
        $this->productModel = \Mockery::mock(new \Mage_Catalog_Model_Product());

        $productModel = $this->productModel;

        $factory = function () use ($productModel) { return $productModel; };
        $this->product->isAnInstanceOf('MageTest\MagentoExtension\Fixture\Product', array($factory));
    }

    function it_should_create_a_product_given_all_required_attributes()
    {
        $data = array(
            'sku' => 'sku1'
        );
        $this->productModel->shouldReceive('setData')
            ->with($data)->once()->andReturn($this->productModel)->ordered();
        $this->productModel->shouldReceive('save')->once()->andReturn(true)->ordered();

        $this->product->create($data);
    }
}

Check passed parameters in product fixture spec


<?php

namespace Backend\Modules\Analytics\Actions;

use Backend\Core\Engine\Base\ActionDelete;
use Backend\Core\Engine\Model;

/**
 * This is the reset-action. It will remove your coupling with analytics
 *
 * @author Wouter Sioen <wouter@sumocoders.be>
 */
final class Reset extends ActionDelete
{
    /**
     * The form instance
     *
     * @var Form
     */
    private $form;

    public function execute()
    {
        $this->get('fork.settings')->delete($this->getModule(), 'certificate');
        $this->get('fork.settings')->delete($this->getModule(), 'email');
        $this->get('fork.settings')->delete($this->getModule(), 'account');
        $this->get('fork.settings')->delete($this->getModule(), 'web_property_id');
        $this->get('fork.settings')->delete($this->getModule(), 'profile');

        return $this->redirect(Model::createURLForAction('Settings'));
    }
}

<?php

namespace Backend\Modules\Analytics\Actions;

use Backend\Core\Engine\Base\ActionDelete;
use Backend\Core\Engine\Model;

/**
 * This is the reset-action. It will remove your coupling with analytics
 *
 * @author Wouter Sioen <wouter@sumocoders.be>
 */
final class Reset extends ActionDelete
{
    public function execute()
    {
        $this->get('fork.settings')->delete($this->getModule(), 'certificate');
        $this->get('fork.settings')->delete($this->getModule(), 'email');
        $this->get('fork.settings')->delete($this->getModule(), 'account');
        $this->get('fork.settings')->delete($this->getModule(), 'web_property_id');
        $this->get('fork.settings')->delete($this->getModule(), 'profile');

        return $this->redirect(Model::createURLForAction('Settings'));
    }
}

Remove unused form class variable.

Remove unused form class variable.


<?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.
 */

/*
 * This file implements rewrite rules for PHP built-in web server.
 *
 * See: http://www.php.net/manual/en/features.commandline.webserver.php
 *
 * If you have custom directory layout, then you have to write your own router
 * and pass it as a value to 'router' option of server:run command.
 *
 * @author: Michał Pipa <michal.pipa.xsolve@gmail.com>
 * @author: Albert Jessurum <ajessu@gmail.com>
 */

if (is_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SERVER['REQUEST_URI'])) {
    return false;
}

$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app_dev.php';

require 'app_dev.php';

<?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.
 */

/*
 * This file implements rewrite rules for PHP built-in web server.
 *
 * See: http://www.php.net/manual/en/features.commandline.webserver.php
 *
 * If you have custom directory layout, then you have to write your own router
 * and pass it as a value to 'router' option of server:run command.
 *
 * @author: Michał Pipa <michal.pipa.xsolve@gmail.com>
 * @author: Albert Jessurum <ajessu@gmail.com>
 */

if (is_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SERVER['SCRIPT_NAME'])) {
    return false;
}

$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app_dev.php';

require 'app_dev.php';

[FrameworkBundle] Fix built-in server when using query params in paths

$_SERVER['REQUEST_URI'] will contain the query params so is_file will fail.
Change it to use $_SERVER['SCRIPT_NAME'] instead which only contains the
relative filename of the the script.


<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait informatio
 */
class Traits_to_organism extends \WebService {

    /**
     * @param $querydata[]
     * @returns array of traits
     */
    public function execute($querydata) {

    }
}

?>

<?php

namespace ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait information to an organism by its id
 */
class Traits_to_organism extends \WebService {

    /**
     * @param $querydata[]
     * @returns organism id
     */
    public function execute($querydata) {
        global $db;
        $organism_id = $querydata['organism_id'];
        $query_get_traits_to_organism = <<<EOF
SELECT *
    FROM trait_entry WHERE organism_id = :organism_id
EOF;
        $stm_get_traits_to_organism = $db->prepare($query_get_traits_to_organism);
        $stm_get_traits_to_organism->bindValue('organism_id', $organism_id);
        $stm_get_traits_to_organism->execute();

        $result = array();
        while ($row = $stm_get_traits_to_organism->fetch(PDO::FETCH_ASSOC)) {
            $this_trait = [];
            $this_trait['type'] = $this->get_cvterm($row['type_cvterm_id']);
            if($row['value'] != NULL){
                $this_trait['value'] = $row['value'];
            } else {
                $this_trait['value_cvterm_id'] = $this->get_cvterm($row['value_cvterm_id']);
            }
            array_push($result, $this_trait);

        }
        return $result;
    }

    private function get_cvterm($cvterm_id){
        global $db;
        $query_get_cvterm = <<<EOF
SELECT name, definition FROM trait_cvterm WHERE trait_cvterm_id = :cvterm_id
EOF;
        $stm_get_cvterm = $db->prepare($query_get_cvterm);
        $stm_get_cvterm->bindValue('cvterm_id', $cvterm_id);
        $stm_get_cvterm->execute();
        $result = $stm_get_cvterm->fetch(PDO::FETCH_ASSOC);

        return ($result['name'] == NULL) ? $result['definition'] : $result['name'];
    }
}

?>

Add functionality to new webservice and return all traits to an organism by its id


<?php

namespace CultuurNet\UDB3\EventExport\Command;

use CultuurNet\Deserializer\JSONDeserializer;
use CultuurNet\Deserializer\MissingValueException;
use CultuurNet\UDB3\EventExport\EventExportQuery;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

abstract class ExportEventsJSONDeserializer extends JSONDeserializer
{
    /**
     * @param \ValueObjects\String\String $data
     * @return ExportEvents
     */
    public function deserialize(String $data)
    {
        $data = parent::deserialize($data);

        if (!isset($data->query)) {
            throw new MissingValueException('query is missing');
        }

        $query = new EventExportQuery($data->query);
        $email = $selection = $include = null;

        // @todo This throws an exception when the e-mail is invalid. How do we handle this?
        if (isset($data->email)) {
            $email = new EmailAddress($data->email);
        }

        if (isset($data->selection)) {
            $selection = $data->selection;
        }

        if (isset($data->include)) {
            $include = $data->include;
        }

        return $this->createCommand($query, $email, $selection, $include);
    }

    /**
     * @param EventExportQuery $query
     * @param EmailAddress|null $address
     * @param string[]|null $selection
     * @param string[]|null $include
     * @return ExportEvents
     */
    abstract protected function createCommand(
        EventExportQuery $query,
        EmailAddress $address = null,
        $selection = null,
        $include = null
    );
}

<?php

namespace CultuurNet\UDB3\EventExport\Command;

use CultuurNet\Deserializer\JSONDeserializer;
use CultuurNet\Deserializer\MissingValueException;
use CultuurNet\UDB3\EventExport\EventExportQuery;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

abstract class ExportEventsJSONDeserializer extends JSONDeserializer
{
    /**
     * @param String $data
     * @return ExportEvents
     */
    public function deserialize(String $data)
    {
        $data = parent::deserialize($data);

        if (!isset($data->query)) {
            throw new MissingValueException('query is missing');
        }

        $query = new EventExportQuery($data->query);
        $email = $selection = $include = null;

        // @todo This throws an exception when the e-mail is invalid. How do we handle this?
        if (isset($data->email)) {
            $email = new EmailAddress($data->email);
        }

        if (isset($data->selection)) {
            $selection = $data->selection;
        }

        if (isset($data->include)) {
            $include = $data->include;
        }

        return $this->createCommand($query, $email, $selection, $include);
    }

    /**
     * @param EventExportQuery $query
     * @param EmailAddress|null $address
     * @param string[]|null $selection
     * @param string[]|null $include
     * @return ExportEvents
     */
    abstract protected function createCommand(
        EventExportQuery $query,
        EmailAddress $address = null,
        $selection = null,
        $include = null
    );
}

III-709: Use String instead of fully namespaced equivalent


<?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.
 */

use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
    Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
    Imbo\Auth\AccessControl\UserQuery,
    Imbo\Auth\AccessControl\GroupQuery;

/**
 * Use a custom user lookup implementation
 */
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
    public function hasAccess($publicKey, $resource, $user = null) {
        return $publicKey === 'public';
    }

    public function getPrivateKey($publicKey) {
        return 'private';
    }

    public function getUsers(UserQuery $query = null) {
        return ['public'];
    }

    public function getGroups(GroupQuery $query = null) {
        return [];
    }

    public function getGroup($groupName) {
        return false;
    }

    public function userExists($publicKey) {
        return $publicKey === 'public';
    }
}

return [
    'accessControl' => new StaticAccessControl(),
];

<?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.
 */

use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
    Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
    Imbo\Auth\AccessControl\UserQuery,
    Imbo\Auth\AccessControl\GroupQuery;

/**
 * Use a custom user lookup implementation
 */
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
    public function hasAccess($publicKey, $resource, $user = null) {
        return $publicKey === 'public';
    }

    public function getPrivateKey($publicKey) {
        return 'private';
    }

    public function getUsers(UserQuery $query = null) {
        return ['public'];
    }

    public function getGroups(GroupQuery $query = null) {
        return [];
    }

    public function getGroup($groupName) {
        return false;
    }

    public function userExists($publicKey) {
        return $publicKey === 'public';
    }

    public function publicKeyExists($publicKey) {
        return $publicKey === 'public';
    }
}

return [
    'accessControl' => new StaticAccessControl(),
];

Add publicKeyExists implementation in staticAccessController


<?php

namespace tests\Nerdstorm\GoogleBooks\Api;

use GuzzleHttp\Psr7\Response;
use Nerdstorm\GoogleBooks\Api\VolumesSearch;
use tests\Nerdstorm\Config;

class VolumeSearchTest extends \PHPUnit_Framework_TestCase
{
    /** @var VolumeSearch */
    protected $volume_search;

    public function setup()
    {
        $this->volume_search = new VolumesSearch(
            Config::API_KEY,
            Config::guzzleOpts()
        );
    }

    public function testVolumeList()
    {
        /** @var Response $response */
        $response = $this->volume_search->volumesList('Systems analysis and design');
        $response->getBody()->getContents();
    }
}

<?php

namespace tests\Nerdstorm\GoogleBooks\Api;

use GuzzleHttp\Psr7\Response;
use Nerdstorm\GoogleBooks\Api\VolumesSearch;
use tests\Nerdstorm\Config;

class VolumeSearchTest extends \PHPUnit_Framework_TestCase
{
    /** @var VolumeSearch */
    protected $volume_search;

    public function setup()
    {
        $this->volume_search = new VolumesSearch(
            Config::API_KEY,
            Config::guzzleOpts()
        );
    }

    public function testVolumeList()
    {
        /** @var Response $response */
        $response = $this->volume_search->volumesList('Systems analysis and design');

        $json = (string) $response->getBody();
        $data = json_decode($json, true);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json; charset=UTF-8', $response->getHeader('Content-Type')[0]);
        $this->assertEquals($data['kind'], 'books#volumes');
        if ($data['totalItems'] >= 10) {
            $this->assertCount(10, $data['items']);
        } else {
            $this->assertCount($data['totalItems'], $data['items']);
        }
    }
}

Test for list volumes added

Test for list volumes added


<?php

namespace App\Console\Commands\Import;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:events-ticketed-full', ['--yes' => 'default']);
        $this->call('import:mobile');
        $this->call('import:products-full --yes');
        $this->call('import:web');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full events/occurrences --yes');
    }

}

<?php

namespace App\Console\Commands\Import;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:events-ticketed-full', ['--yes' => 'default']);
        $this->call('import:mobile');
        $this->call('import:products-full', ['--yes' => 'default']);
        $this->call('import:web');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', [
            '--yes' => 'default',
            'endpoint' => 'events/occurrences'
        ]);
    }

}

Fix scheduled import option syntax

Fix scheduled import option syntax

Confirmed that this is the correct syntax. Otherwise, it complains
about the command not being found.


<?php

namespace Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes;

use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
use Kunstmaan\FormBundle\Form\StringFormSubmissionType;

/**
 * The StringFormSubmissionField can be used to store string values to a FormSubmission
 *
 * @ORM\Entity
 * @ORM\Table(name="kuma_string_form_submission_fields")
 */
class StringFormSubmissionField extends FormSubmissionField
{
    /**
     * @ORM\Column(name="sfsf_value", type="string")
     */
    protected $value;

    /**
     * Returns the default form type for this FormSubmissionField
     *
     * @return string
     */
    public function getDefaultAdminType()
    {
        return StringFormSubmissionType::class;
    }

    /**
     * Return a string representation of this FormSubmissionField
     *
     * @return string
     */
    public function __toString()
    {
        $value = $this->getValue();

        return !empty($value) ? $value : '';
    }

    /**
     * Returns the current value of this field
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Sets the current value of this field
     *
     * @param string $value
     *
     * @return StringFormSubmissionField
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }
}

<?php

namespace Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes;

use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
use Kunstmaan\FormBundle\Form\StringFormSubmissionType;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * The StringFormSubmissionField can be used to store string values to a FormSubmission
 *
 * @ORM\Entity
 * @ORM\Table(name="kuma_string_form_submission_fields")
 */
class StringFormSubmissionField extends FormSubmissionField
{
    /**
     * @ORM\Column(name="sfsf_value", type="string")
     * @Assert\Length(max=255)
     */
    protected $value;

    /**
     * Returns the default form type for this FormSubmissionField
     *
     * @return string
     */
    public function getDefaultAdminType()
    {
        return StringFormSubmissionType::class;
    }

    /**
     * Return a string representation of this FormSubmissionField
     *
     * @return string
     */
    public function __toString()
    {
        $value = $this->getValue();

        return !empty($value) ? $value : '';
    }

    /**
     * Returns the current value of this field
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Sets the current value of this field
     *
     * @param string $value
     *
     * @return StringFormSubmissionField
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }
}

Add length validation to string form field


<?php

namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Utils;

use Oro\Bundle\IntegrationBundle\Utils\FormUtils;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;

use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestChannelType;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestConnector;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestTwoWayConnector;

class FormUtilsTest extends \PHPUnit_Framework_TestCase
{
    /** @var TypesRegistry */
    protected $typesRegistry;

    /** @var FormUtils */
    protected $utils;

    public function setUp()
    {
        $this->typesRegistry = new TypesRegistry();
        $this->utils         = new FormUtils($this->typesRegistry);
    }

    public function tearDown()
    {
        unset($this->utils, $this->typesRegistry);
    }

    public function testHasTwoWaySyncConnectors()
    {
        $testType                  = 'type2';
        $testTypeThatHasConnectors = 'type1';

        $this->typesRegistry->addChannelType($testType, new TestChannelType());
        $this->typesRegistry->addChannelType($testTypeThatHasConnectors, new TestChannelType());
        $this->typesRegistry->addConnectorType(uniqid('type'), $testType, new TestConnector());
        $this->typesRegistry->addConnectorType(uniqid('type'), $testTypeThatHasConnectors, new TestTwoWayConnector());

        $this->assertTrue($this->utils->hasTwoWaySyncConnectors($testTypeThatHasConnectors));
        $this->assertFalse($this->utils->hasTwoWaySyncConnectors($testType));
    }
}

<?php

namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Utils;

use Oro\Bundle\IntegrationBundle\Utils\FormUtils;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;

use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestConnector;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestIntegrationType;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestTwoWayConnector;

class FormUtilsTest extends \PHPUnit_Framework_TestCase
{
    /** @var TypesRegistry */
    protected $typesRegistry;

    /** @var FormUtils */
    protected $utils;

    public function setUp()
    {
        $this->typesRegistry = new TypesRegistry();
        $this->utils         = new FormUtils($this->typesRegistry);
    }

    public function tearDown()
    {
        unset($this->utils, $this->typesRegistry);
    }

    public function testHasTwoWaySyncConnectors()
    {
        $testType                  = 'type2';
        $testTypeThatHasConnectors = 'type1';

        $this->typesRegistry->addChannelType($testType, new TestIntegrationType());
        $this->typesRegistry->addChannelType($testTypeThatHasConnectors, new TestIntegrationType());
        $this->typesRegistry->addConnectorType(uniqid('type'), $testType, new TestConnector());
        $this->typesRegistry->addConnectorType(uniqid('type'), $testTypeThatHasConnectors, new TestTwoWayConnector());

        $this->assertTrue($this->utils->hasTwoWaySyncConnectors($testTypeThatHasConnectors));
        $this->assertFalse($this->utils->hasTwoWaySyncConnectors($testType));
    }
}

CRM-1321: Refactor sync commands
   - minor unit tests fixesxy


<?php
namespace Prettus\Repository\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class LumenRepositoryServiceProvider
 * @package Prettus\Repository\Providers
 */
class LumenRepositoryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->commands('Prettus\Repository\Generators\Commands\RepositoryCommand');
        $this->commands('Prettus\Repository\Generators\Commands\TransformerCommand');
        $this->commands('Prettus\Repository\Generators\Commands\PresenterCommand');
        $this->commands('Prettus\Repository\Generators\Commands\EntityCommand');
        $this->commands('Prettus\Repository\Generators\Commands\ValidatorCommand');
        $this->commands('Prettus\Repository\Generators\Commands\ControllerCommand');
        $this->commands('Prettus\Repository\Generators\Commands\BindingsCommand');
        $this->app->register('Prettus\Repository\Providers\EventServiceProvider');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}

<?php
namespace Prettus\Repository\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class LumenRepositoryServiceProvider
 * @package Prettus\Repository\Providers
 */
class LumenRepositoryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->commands('Prettus\Repository\Generators\Commands\RepositoryCommand');
        $this->app->register('Prettus\Repository\Providers\EventServiceProvider');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}

Revert "Added missing generator commands to Lumen provider"

This reverts commit 3fb2cb778edcad84c3904bd8a26a6fc843cf83d9.