<?php

use igorw\edn;

class ShaunTest extends \PHPUnit_Framework_TestCase {
    /** @dataProvider provideValidEdnFile */
    function testParseWithValidEdn($ednFile) {
        $edn = file_get_contents($ednFile);

        $data = igorw\edn\parse($edn);
        $encoded = igorw\edn\encode($data);

        $this->assertEquals(trim($edn), trim($encoded));
    }

    function provideValidEdnFile() {
        $dir = __DIR__.'/../../vendor/shaunxcode/edn-tests/valid-edn';
        $files = new \FilesystemIterator($dir);
        return array_map(function ($file) { return [$file]; }, iterator_to_array($files));
    }

    /**
     * @dataProvider provideInvalidEdnFile
     * @expectedException Phlexy\LexingException
     */
    function testParseWithInvalidEdn($ednFile) {
        $edn = file_get_contents($ednFile);

        igorw\edn\parse($edn);
    }

    function provideInvalidEdnFile() {
        $dir = __DIR__.'/../../vendor/shaunxcode/edn-tests/invalid-edn';
        $files = new \FilesystemIterator($dir);
        return array_map(function ($file) { return [$file]; }, iterator_to_array($files));
    }
}

<?php

use igorw\edn;

class ShaunTest extends \PHPUnit_Framework_TestCase {
    /** @dataProvider provideValidEdnFile */
    function testParseWithValidEdn($ednFile) {
        $edn = file_get_contents($ednFile);

        $data = igorw\edn\parse($edn);
        $encoded = igorw\edn\encode($data);

        $this->assertEquals(trim($edn), trim($encoded));
    }

    function provideValidEdnFile() {
        $dir = __DIR__.'/../../vendor/shaunxcode/edn-tests/valid-edn';
        $files = new \FilesystemIterator($dir);
        return array_map(function ($file) { return [$file]; }, iterator_to_array($files));
    }

    /**
     * @dataProvider provideInvalidEdnFile
     * @expectedException Phlexy\LexingException
     */
    function testParseWithInvalidEdn($ednFile) {
        $edn = file_get_contents($ednFile);

        $data = igorw\edn\parse($edn);

        $this->fail(sprintf('Expected parser to fail on %s, but got: %s', json_encode($edn), print_r($data, true)));
    }

    function provideInvalidEdnFile() {
        $dir = __DIR__.'/../../vendor/shaunxcode/edn-tests/invalid-edn';
        $files = new \FilesystemIterator($dir);
        return array_map(function ($file) { return [$file]; }, iterator_to_array($files));
    }
}

Improve shaun test error messages

Improve shaun test error messages


<?php

use Illuminate\Database\Seeder;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=0; $i<5; $i++) {

            $firstName = $faker->firstName;
            $lastName = $faker->lastName;

            App\User::create(
                [
                    'name_first'    => $firstName,
                    'name_last'     => $lastName,
                    "affiliation_id"=> $faker->numberBetween(1,57),
                    "email"         => $faker->email,
                    'password'      => 'admin'
                ]
            );

            $this->command->info("Seeded user {$firstName} {$lastName}");
        }

        // Add dev account until we enable registration
        App\User::create(
            [
                'name_first'    => "Developer",
                'name_last'     => "lastName",
                "affiliation_id"=> 1,
                "email"         => "developer@codeforcharlotte.org",
                'password'      => 'admin'
            ]
        );

    }
}

<?php

use Illuminate\Database\Seeder;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=0; $i<5; $i++) {

            $firstName = $faker->firstName;
            $lastName = $faker->lastName;

            $newUser = App\User::create(
                [
                    'name_first'    => $firstName,
                    'name_last'     => $lastName,
                    "affiliation_id"=> $faker->numberBetween(1,57),
                    "email"         => $faker->email,
                    'password'      => 'admin'
                ]
            );

            $this->command->info("Seeded user {$firstName} {$lastName}");

            $role_id = $faker->numberBetween(1, 5);
            $role = \App\Role::find($role_id);

            $newUser->attachRole($role);

        }

        // Add dev account until we enable registration
        $newUser = App\User::create(
            [
                'name_first'    => "Developer",
                'name_last'     => "lastName",
                "affiliation_id"=> 1,
                "email"         => "developer@codeforcharlotte.org",
                'password'      => 'admin'
            ]
        );

        $role = \App\Role::find(1);
        $newUser->attachRole($role);

    }
}

Update user table seeder to assign roles


@extends(Config::get('entrust-gui.layout'))

@section('heading', 'Create Permission'))

@section('content')
<form action="{{ route('entrust-gui::permissions.store') }}" method="post" role="form">
    @include('entrust-gui::permissions.partials.form')
    <button type="submit" class="btn btn-labeled btn-primary">{{ trans('entrust-gui::button.create') }}</button>
    {{ trans('entrust-gui::button.cancel') }}
</form>
@endsection

@extends(Config::get('entrust-gui.layout'))

@section('heading', 'Create Permission')

@section('content')
<form action="{{ route('entrust-gui::permissions.store') }}" method="post" role="form">
    @include('entrust-gui::permissions.partials.form')
    <button type="submit" class="btn btn-labeled btn-primary">{{ trans('entrust-gui::button.create') }}</button>
    {{ trans('entrust-gui::button.cancel') }}
</form>
@endsection

Remove extra bracket in permission layout file


<?php

namespace Maghead\TableParser;

use PDO;
use SQLBuilder\Driver\BaseDriver;
use Maghead\QueryDriver;
use Maghead\Schema\DeclareSchema;
use Maghead\Runtime\Connection;

abstract class BaseTableParser
{
    /**
     * @var QueryDriver
     */
    protected $driver;

    /**
     * @var Connection
     */
    protected $connection;

    protected $config;

    public function __construct(PDO $connection, BaseDriver $driver)
    {
        $this->driver = $driver;
        $this->connection = $connection;
    }

    /**
     * Implements the query to parse table names from database.
     *
     * @return string[] table names
     */
    abstract public function getTables();

    /**
     * Implements the logic to reverse table definition to DeclareSchema object.
     *
     *
     * @return DeclareSchema[string tableName] returns (defined table + undefined table)
     */
    abstract public function reverseTableSchema($table, $referenceSchema = null);

    /**
     * Find all user-defined schema.
     *
     * This is not used right now.
     */
    public function getTableSchemaMap()
    {
        $tableSchemas = array();

        // Parse existing table and try to find the schema
        $tables = $this->getTables();
        foreach ($tables as $table) {
            $tableSchemas[$table] = $this->reverseTableSchema($table);
        }

        return $tableSchemas;
    }

    public function typenameToIsa($typeName)
    {
        $typeInfo = TypeInfoParser::parseTypeInfo($typeName);

        return $typeInfo->isa;
    }
}

<?php

namespace Maghead\TableParser;

use PDO;
use SQLBuilder\Driver\BaseDriver;
use Maghead\QueryDriver;
use Maghead\Schema\DeclareSchema;
use Maghead\Runtime\Connection;

abstract class BaseTableParser
{
    /**
     * @var QueryDriver
     */
    protected $driver;

    /**
     * @var Connection
     */
    protected $connection;

    protected $config;

    public function __construct(PDO $connection, BaseDriver $driver)
    {
        $this->driver = $driver;
        $this->connection = $connection;
    }

    /**
     * Implements the query to parse table names from database.
     *
     * @return string[] table names
     */
    abstract public function getTables();

    /**
     * Implements the logic to reverse table definition to DeclareSchema object.
     *
     *
     * @return DeclareSchema[string tableName] returns (defined table + undefined table)
     */
    abstract public function reverseTableSchema($table, $referenceSchema = null);

    public function typenameToIsa($typeName)
    {
        $typeInfo = TypeInfoParser::parseTypeInfo($typeName);

        return $typeInfo->isa;
    }
}

Clean up base table parser method

Clean up base table parser method


<?php
namespace M6Web\Bundle\CassandraBundle\Cassandra;

use Cassandra\Future;
use M6Web\Bundle\CassandraBundle\EventDispatcher\CassandraEvent;

/**
 * Class FutureResponse
 *
 * Handle future response for dispatching event when request is complete
 */
class FutureResponse implements Future
{
    /**
     * @var EventDispatcher
     */
    protected $eventDispatcher;

    /**
     * @var CassandraEvent
     */
    protected $event;

    /**
     * @var Futurer
     */
    protected $future;

    /**
     * @param Future          $future
     * @param CassandraEvent  $event
     * @param EventDispatcher $eventDispatcher
     */
    public function __construct(Future $future, CassandraEvent $event, $eventDispatcher)
    {
        $this->future          = $future;
        $this->event           = $event;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Waits for a given future resource to resolve and throws errors if any.
     *
     * @param int|null $timeout
     *
     * @throws \Cassandra\Exception\InvalidArgumentException
     * @throws \Cassandra\Exception\TimeoutException
     *
     * @return mixed a value that the future has been resolved with
     */
    public function get($timeout = null)
    {
        $return = $this->future->get($timeout);

        $this->event->setExecutionStop();
        $this->eventDispatcher->dispatch('m6web.cassandra', $this->event);

        return $return;
    }
}

<?php
namespace M6Web\Bundle\CassandraBundle\Cassandra;

use Cassandra\Future;
use M6Web\Bundle\CassandraBundle\EventDispatcher\CassandraEvent;

/**
 * Class FutureResponse
 *
 * Handle future response for dispatching event when request is complete
 */
class FutureResponse implements Future
{
    /**
     * @var EventDispatcher
     */
    protected $eventDispatcher;

    /**
     * @var CassandraEvent
     */
    protected $event;

    /**
     * @var Futurer
     */
    protected $future;

    /**
     * @param Future          $future
     * @param CassandraEvent  $event
     * @param EventDispatcher $eventDispatcher
     */
    public function __construct(Future $future, CassandraEvent $event, $eventDispatcher)
    {
        $this->future          = $future;
        $this->event           = $event;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Waits for a given future resource to resolve and throws errors if any.
     *
     * @param int|null $timeout
     *
     * @throws \Cassandra\Exception\InvalidArgumentException
     * @throws \Cassandra\Exception\TimeoutException
     *
     * @return mixed a value that the future has been resolved with
     */
    public function get($timeout = null)
    {
        $return = $this->future->get($timeout);

        $this->event->setExecutionStop();
        $this->eventDispatcher->dispatch(CassandraEvent::EVENT_NAME, $this->event);

        return $return;
    }
}

Add a future repsonse class for handle dispatcher for asynchronous command


<!DOCTYPE html>

        <title>Print Table</title>
        <meta charset="UTF-8">
        <meta name=description content="">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

            @foreach($data as $row)
                @if ($row == reset($data))

                        @foreach($row as $key => $value)
                            {!! $key !!}
                        @endforeach

                @endif

                    @foreach($row as $key => $value)
                        @if (is_string($value) || trim($value)==='' || is_numeric($value))
                            {!! $value !!}
                        @endif
                    @endforeach

            @endforeach

<!DOCTYPE html>

        <title>Print Table</title>
        <meta charset="UTF-8">
        <meta name=description content="">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

            @foreach($data as $row)
                @if ($row == reset($data))

                        @foreach($row as $key => $value)
                            {!! $key !!}
                        @endforeach

                @endif

                    @foreach($row as $key => $value)
                        @if(is_string($value) || is_numeric($value))
                            {!! $value !!}
                        @else

                        @endif
                    @endforeach

            @endforeach

Fix printing template when value is an array.


<?php

class RelationTest extends DatabaseTestCase {

	public function testGetOtherModel() {

	}

	public function testSetOtherModel() {

	}
}

<?php

class RelationTest extends DatabaseTestCase {

	public function testGetOtherModel() {
		$m1 = Blueprint::make('Model1');
		$m2 = Blueprint::make('Model2');
		$m1->model2_id = $m2->id;
		$m1->commit();

		$m2_ret = $m1->Model2();
		$this->assertEquals($m2, $m2_ret);
	}

	/**
	 * @depends testGetOtherModel
	 */
	public function testSetOtherModel() {
		$m1 = Blueprint::make('Model1');
		$m2 = Blueprint::make('Model2');

		$m1->Model2 = $m2;

		$this->assertEquals($m2->id, $m1->model2_id);
		$this->assertEquals($m2, $m1->Model2());

		$m1->commit();
	}
}

Add test for relation options

Add test for relation options


<?php

return array(
	'admin' => array(
		'models' =>array(
		),
		'parameters' => array(
			'social-patreon-name' => array(
				'displayName' => 'Patreon Name',
				'group' => 'Social',
				'type' => 'Text',
				'default' => '<Patreon Name Goes Here>',
			),
			'patreon-link-image' => array(
				'displayName' => 'Patreon Link Image',
				'group' => 'Social',
				'type' => 'ModelSelect',
				'default' => '',
				'options' => array(
					'className' => 'ATPCms\Model\Image',
				),
			),
			'social-twc-site-id' => array(
				'displayName' => 'Top Webcomics Site Id',
				'group' => 'Social',
				'type' => 'Text',
				'default' => '<TWC Site Id Goes Here>',
			),
			'social-twc-incentive-date' => array(
				'displayName' => 'Last TWC Incentive Update',
				'group' => 'Social',
				'type' => 'Date',
				'default' => '',
			),
		),
	),
);

<?php

return array(
	'admin' => array(
		'models' =>array(
		),
		'parameters' => array(
			'social-patreon-name' => array(
				'displayName' => 'Patreon Name',
				'group' => 'Social',
				'type' => 'Text',
				'default' => '<Patreon Name Goes Here>',
			),
			'patreon-link-image' => array(
				'displayName' => 'Patreon Link Image',
				'group' => 'Social',
				'type' => 'ModelSelect',
				'default' => '',
				'options' => array(
					'className' => 'ATPCms\Model\Image',
				),
			),
			'social-twc-site-id' => array(
				'displayName' => 'Top Webcomics Site Id',
				'group' => 'Social',
				'type' => 'Text',
				'default' => '<TWC Site Id Goes Here>',
			),
			'social-twc-incentive-date' => array(
				'displayName' => 'Last TWC Incentive Update',
				'group' => 'Social',
				'type' => 'Date',
				'default' => '',
			),
            'social-twc-incentive-date-format' => array(
                'displayName' => 'TWC Incentive Date Format',
                'group' => 'Social',
                'type' => 'Text',
                'default' => 'M jS',
            ),
		),
	),
);

Add TWC date format parameter

Add TWC date format parameter


<?php
// make links sortable
//SortableDataObject::add_sortable_class('Link');

// enabled the extension, need the FooterLinksFolder method to be available
Object::add_extension('SiteTree', 'LinksExtension');
?>

<?php
// make links sortable
//SortableDataObject::add_sortable_class('Link');

// enabled the extension, need the FooterLinksFolder method to be available
Object::add_extension('SiteTree', 'LinksExtension');

//define global path to Components' root folder
if(!defined('LINK_EDIT_TOOLS_PATH'))
{
	define('LINK_EDIT_TOOLS_PATH', rtrim(basename(dirname(__FILE__))));
}
?>

ENHANCEMENT: Add edit tools path so that no hardcoding is required


<?php
define('MOBILE_DIR', 'mobile');

SiteConfig::add_extension('MobileSiteConfigExtension');
ContentController::add_extension('MobileSiteControllerExtension');
SiteTree::add_extension('MobileSiteTreeExtension');

<?php
define('MOBILE_DIR', 'mobile');

SiteConfig::add_extension('MobileSiteConfigExtension');
ContentController::add_extension('MobileSiteControllerExtension');
Security::add_extension('MobileSiteControllerExtension');
SiteTree::add_extension('MobileSiteTreeExtension');

Add support to the Security controller

Add support to the Security controller

Fixes #27


<?php
/**
 * Header top template
 *
 * @package ZnWP Bootstrap Theme
 */

global $znwp_theme;
?>

              <div class="<?php echo $znwp_theme->get_full_width_class(); ?>">
                <?php if ($znwp_theme->display_header_text()): ?>

<?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

                <?php endif; ?>

Use div instead of h1 for site title

Use div instead of h1 for site title


<?php

use Sylius\Bundle\CoreBundle\Application\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use SitemapPlugin\SitemapPlugin;

final class AppKernel extends Kernel
{
    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        return array_merge(parent::registerBundles(), [
            new \Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
            new \Sylius\Bundle\ShopBundle\SyliusShopBundle(),

            new \FOS\OAuthServerBundle\FOSOAuthServerBundle(), // Required by SyliusApiBundle
            new \Sylius\Bundle\AdminApiBundle\SyliusAdminApiBundle(),

            new SitemapPlugin(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        if ($this->getEnvironment() === 'test_relative') {
            $loader->load($this->getRootDir() . '/config/config_relative.yml');
            return;
        }

        $loader->load($this->getRootDir() . '/config/config.yml');
    }
}

<?php

use Sylius\Bundle\CoreBundle\Application\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use SitemapPlugin\SitemapPlugin;

final class AppKernel extends Kernel
{
    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        return array_merge(parent::registerBundles(), [
            new \Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
            new \Sylius\Bundle\ShopBundle\SyliusShopBundle(),

            new \FOS\OAuthServerBundle\FOSOAuthServerBundle(), // Required by SyliusApiBundle
            new \Sylius\Bundle\AdminApiBundle\SyliusAdminApiBundle(),

            new SitemapPlugin(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        if ($this->getEnvironment() === 'test_relative') {
            $loader->load($this->getRootDir() . '/config/config_test_relative.yml');
            return;
        }

        $loader->load($this->getRootDir() . '/config/config.yml');
    }
}

Load the correct config for new Symfony environment


<?php namespace Anomaly\AddonsModule\Listener;

use Anomaly\Streams\Platform\Application\Event\SystemIsRefreshing;
use Anomaly\Streams\Platform\Console\Kernel;

/**
 * Class RefreshAddonsModule
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class RefreshAddonsModule
{

    /**
     * Handle the command.
     *
     * @param SystemIsRefreshing $event
     */
    public function handle(SystemIsRefreshing $event)
    {
        $command = $event->getCommand();

        app(Kernel::class)->call('addons:sync');

        $command->info('Updating addon information.');
    }
}

<?php namespace Anomaly\AddonsModule\Listener;

use Anomaly\Streams\Platform\Application\Event\SystemIsRefreshing;
use Anomaly\Streams\Platform\Console\Kernel;

/**
 * Class RefreshAddonsModule
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class RefreshAddonsModule
{

    /**
     * Handle the command.
     *
     * @param SystemIsRefreshing $event
     */
    public function handle(SystemIsRefreshing $event)
    {
        $command = $event->getCommand();

        app(Kernel::class)->call('addons:sync');

        $command->info('Addon information updated.');
    }
}

Change verbiage around refresh command.

Change verbiage around refresh command.


<?php

include ("../../../inc/includes.php");

// Close the ticket
if (!isset($_POST['id'])) {
   Html::back();
}

$ticket = new Ticket();
if ($ticket->getFromDB($_POST['id'])) {
   $input = array(
       'id'     => $_POST['id'],
       'status' => Ticket::CLOSED
   );
   $ticket->update($input);
}
Html::back();

?>

<?php

include ("../../../inc/includes.php");

// Close the ticket
if (!isset($_POST['id'])) {
   Html::back();
}

$ticket = new Ticket();
$ticketFollowup = new TicketFollowup();
if ($ticket->getFromDB($_POST['id'])) {
   $input = array(
       'tickets_id' => $_POST['id'],
       'content'    => "Fermé par le demandeur"
   );
   $ticketFollowup->add($input);

   $input = array(
       'id'     => $_POST['id'],
       'status' => Ticket::CLOSED
   );
   $ticket->update($input);
}
Html::back();

?>

Add followup when close the ticket

Add followup when close the ticket


    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" title="RSS feed">RSS feed

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" title=".ical format">.ical format

    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" title="RSS feed of upcoming events" class="wdn-icon-rss-squared">RSS

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" title="ICS format of upcoming events" class="wdn-icon-calendar">ICS

Adjust markup of subscribe links

Adjust markup of subscribe links


<!doctype html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>

<!DOCTYPE html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>
</head><body></body>
</html>

Add charset to HTML5 doc (and make more XHTML friendly)


<?php
namespace wcf\system\form\builder\field;

/**
 * Represents a form field that supports a placeholder value.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	3.2
 */
interface IPlaceholderFormField {
	/**
	 * Returns the placeholder value of this field or `null` if no placeholder has
	 * been set.
	 *
	 * @return	null|string
	 */
	public function getPlaceholder();

	/**
	 * Sets the placeholder value of this field using the given language item
	 * and returns this element. If `null` is passed, the placeholder value is
	 * removed.
	 *
	 * @param	null|string	$languageItem	language item containing the placeholder or `null` to unset description
	 * @param	array		$variables	additional variables used when resolving the language item
	 * @return	static				this field
	 *
	 * @throws	\InvalidArgumentException	if the given value is no string or otherwise invalid
	 */
	public function placeholder($languageItem = null, array $variables = []);
}

<?php
namespace wcf\system\form\builder\field;

/**
 * Represents a form field that supports a placeholder value.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	3.2
 */
interface IPlaceholderFormField {
	/**
	 * Returns the placeholder value of this field or `null` if no placeholder has
	 * been set.
	 *
	 * @return	null|string
	 */
	public function getPlaceholder();

	/**
	 * Sets the placeholder value of this field using the given language item
	 * and returns this element. If `null` is passed, the placeholder value is
	 * removed.
	 *
	 * @param	null|string	$languageItem	language item containing the placeholder or `null` to unset placeholder
	 * @param	array		$variables	additional variables used when resolving the language item
	 * @return	static				this field
	 *
	 * @throws	\InvalidArgumentException	if the given value is no string or otherwise invalid
	 */
	public function placeholder($languageItem = null, array $variables = []);
}

Fix parameter documentation in `IPlaceholderFormField`

See #2509


<?php

namespace Risan\OAuth1\Test\Unit;

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\OAuth1Factory;
use Risan\OAuth1\OAuth1Interface;

class OAuth1FactoryTest extends TestCase
{
    private $config;

    function setUp()
    {
        $this->config = [
            'client_credentials_identifier' => 'client_id',
            'client_credentials_secret' => 'client_secret',
            'base_uri' => 'http://example.com',
            'temporary_credentials_uri' => '/request_token',
            'authorization_uri' => '/authorize',
            'token_credentials_uri' => '/access_token',
            'callback_uri' => 'http://johndoe.net',
        ];
    }

    /** @test */
    function it_can_create_oauth1_instance()
    {
        $oauth1 = OAuth1Factory::create($this->config);

        $this->assertInstanceOf(OAuth1Interface::class, $oauth1);
    }
}

<?php

namespace Risan\OAuth1\Test\Unit;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Risan\OAuth1\OAuth1Factory;
use Risan\OAuth1\OAuth1Interface;
use Risan\OAuth1\Signature\HmacSha1Signer;

class OAuth1FactoryTest extends TestCase
{
    private $config;

    function setUp()
    {
        $this->config = [
            'client_credentials_identifier' => 'client_id',
            'client_credentials_secret' => 'client_secret',
            'base_uri' => 'http://example.com',
            'temporary_credentials_uri' => '/request_token',
            'authorization_uri' => '/authorize',
            'token_credentials_uri' => '/access_token',
            'callback_uri' => 'http://johndoe.net',
        ];
    }

    /** @test */
    function it_can_create_oauth1_instance()
    {
        $oauth1 = OAuth1Factory::create($this->config);

        $this->assertInstanceOf(OAuth1Interface::class, $oauth1);

        $this->assertInstanceOf(
            HmacSha1Signer::class,
            $oauth1->getRequestFactory()->getAuthorizationHeader()->getProtocolParameter()->getSigner()
        );
    }

    /** @test */
    function it_throws_exception_if_signer_not_implements_signer_interface()
    {
        $this->expectException(InvalidArgumentException::class);

        OAuth1Factory::create($this->config, 'foo');
    }
}

:white_check_mark: Add test if signer not implements signer interace.


<?php

namespace Laravel\Lumen\Http;

use Illuminate\Support\Arr;
use Illuminate\Http\Request as BaseRequest;

class Request extends BaseRequest
{
    /**
     * Get the route handling the request.
     *
     * @param  string|null  $param
     * @param  mixed  $default
     *
     * @return array|string
     */
    public function route($param = null, $default = null)
    {
        $route = call_user_func($this->getRouteResolver());

        if (is_null($route) || is_null($param)) {
            return $route;
        }

        return Arr::get($route[2], $param, $default);
    }
}

<?php

namespace Laravel\Lumen\Http;

use RuntimeException;
use Illuminate\Support\Arr;
use Illuminate\Http\Request as BaseRequest;

class Request extends BaseRequest
{
    /**
     * Get the route handling the request.
     *
     * @param  string|null  $param
     * @param  mixed  $default
     *
     * @return array|string
     */
    public function route($param = null, $default = null)
    {
        $route = call_user_func($this->getRouteResolver());

        if (is_null($route) || is_null($param)) {
            return $route;
        }

        return Arr::get($route[2], $param, $default);
    }

    /**
     * Get a unique fingerprint for the request / route / IP address.
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    public function fingerprint()
    {
        if (! $route = $this->route()) {
            throw new RuntimeException('Unable to generate fingerprint. Route unavailable.');
        }

        return sha1(implode('|', [
            $this->getMethod(), $this->root(), $this->path(), $this->ip()
        ]));
    }
}

Make the fingerprint method compatible with Lumen.


<?php

/**
 * Abstraction of an instance resource from the Twilio API.
 *
 * @category Services
 * @package  Services_Twilio
 * @author   Neuman Vong <neuman@twilio.com>
 * @license  http://creativecommons.org/licenses/MIT/ MIT
 * @link     http://pear.php.net/package/Services_Twilio
 */
abstract class Services_Twilio_InstanceResource
    extends Services_Twilio_Resource
{
    /**
     * @param mixed $params An array of updates, or a property name
     * @param mixed $value  A value with which to update the resource
     *
     * @return null
     */
    public function update($params, $value = null)
    {
        if (!is_array($params)) {
            $params = array($params => $value);
        }
        $this->client->updateData($params);
    }

    /**
     * Get the value of a property on this resource.
     *
     * @param string $key The property name
     *
     * @return mixed Could be anything.
     */
    public function __get($key)
    {
        if ($subresource = $this->getSubresources($key)) {
            return $subresource;
        }
        return $this->client->$key;
    }
}

<?php

/**
 * Abstraction of an instance resource from the Twilio API.
 *
 * @category Services
 * @package  Services_Twilio
 * @author   Neuman Vong <neuman@twilio.com>
 * @license  http://creativecommons.org/licenses/MIT/ MIT
 * @link     http://pear.php.net/package/Services_Twilio
 */
abstract class Services_Twilio_InstanceResource
    extends Services_Twilio_Resource
{
    /**
     * @param mixed $params An array of updates, or a property name
     * @param mixed $value  A value with which to update the resource
     *
     * @return null
     */
    public function update($params, $value = null)
    {
        if (!is_array($params)) {
            $params = array($params => $value);
        }
        $this->client->createData($this->uri, $params);
    }

    /**
     * Get the value of a property on this resource.
     *
     * @param string $key The property name
     *
     * @return mixed Could be anything.
     */
    public function __get($key)
    {
        if ($subresource = $this->getSubresources($key)) {
            return $subresource;
        }
        return $this->client->$key;
    }
}

Make POST request when updating object

Make POST request when updating object


<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;

use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;

class SchemaConfigMakeCommandTest extends TestCase
{
    use MakeCommandAssertionTrait;

    /**
     * @dataProvider dataForMakeCommand
     */
    public function testCommand(
        string $inputName,
        string $expectedFilename,
        string $expectedClassDefinition
    ): void {
        $this->assertMakeCommand(
            'Schema',
            SchemaConfigMakeCommand::class,
            $inputName,
            $expectedFilename,
            'App\\\\GraphQL\\\\Schemas',
            $expectedClassDefinition,
        );
    }

    public function dataForMakeCommand(): array
    {
        return [
            'Example' => [
                'inputName' => 'Example',
                'expectedFilename' => 'GraphQL/Schemas/Example.php',
                'expectedClassDefinition' => 'Example implements ConfigConvertible',
            ],
            'ExampleSchema' => [
                'inputName' => 'ExampleSchema',
                'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
                'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
            ],
        ];
    }
}

<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;

use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;

class SchemaConfigMakeCommandTest extends TestCase
{
    use MakeCommandAssertionTrait;

    /**
     * @dataProvider dataForMakeCommand
     */
    public function testCommand(
        string $inputName,
        string $expectedFilename,
        string $expectedClassDefinition
    ): void {
        $this->assertMakeCommand(
            'Schema',
            SchemaConfigMakeCommand::class,
            $inputName,
            $expectedFilename,
            'App\\\\GraphQL\\\\Schemas',
            $expectedClassDefinition
        );
    }

    public function dataForMakeCommand(): array
    {
        return [
            'Example' => [
                'inputName' => 'Example',
                'expectedFilename' => 'GraphQL/Schemas/Example.php',
                'expectedClassDefinition' => 'Example implements ConfigConvertible',
            ],
            'ExampleSchema' => [
                'inputName' => 'ExampleSchema',
                'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
                'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
            ],
        ];
    }
}

Make code compatible with PHP < 8

Make code compatible with PHP < 8


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\CompanyBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class CompanyManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class CompanyManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('company.manager');
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\CompanyBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class CompanyManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class CompanyManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('company.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php
namespace wcf\system\form\builder\field;

/**
 * Represents a form field that supports the `autocomplete` attribute.
 *
 * @author      Matthias Schmidt
 * @copyright   2001-2020 WoltLab GmbH
 * @license     GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package     WoltLabSuite\Core\System\Form\Builder\Field
 * @see         https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute
 * @since       5.4
 */
interface IAutoCompleteFormField {
	/**
	 * Sets the `autocomplete` attribute of the form field.
	 *
	 * Multiple tokens can be separated by spaces and if `null` is given, the attribute is unset.
	 *
	 * @throws      \InvalidArgumentException       if an invalid `autocomplete` token is included in the attribute value
	 */
	public function autoComplete(?string $autocomplete): self;

	/**
	 * Returns the `autocomplete` attribute of the form field.
	 *
	 * If `null` is returned, no `autocomplete` attribute will be set.
	 */
	public function getAutoComplete(): ?string;
}

<?php
namespace wcf\system\form\builder\field;

/**
 * Represents a form field that supports the `autocomplete` attribute.
 *
 * @author      Matthias Schmidt
 * @copyright   2001-2020 WoltLab GmbH
 * @license     GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package     WoltLabSuite\Core\System\Form\Builder\Field
 * @see         https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute
 * @since       5.4
 */
interface IAutoCompleteFormField {
	/**
	 * Sets the `autocomplete` attribute of the form field.
	 *
	 * Multiple tokens can be separated by spaces and if `null` is given, the attribute is unset.
	 *
	 * @throws      \InvalidArgumentException       if an invalid `autocomplete` token is included in the attribute value
	 */
	public function autoComplete(?string $autoComplete): self;

	/**
	 * Returns the `autocomplete` attribute of the form field.
	 *
	 * If `null` is returned, no `autocomplete` attribute will be set.
	 */
	public function getAutoComplete(): ?string;
}

Fix parameter name in `IAutoCompleteFormField`


<?php

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

class ElementsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('elements', function ($table) {
            $table->engine = 'InnoDB';

            $table->string('key');
            $table->string('type');
            $table->mediumtext('value')->nullable();
            $table->string('locale');

            $table->primary(['key', 'locale']);
            $table->index(['locale', 'key']);
        });
    }

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

<?php

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

class ElementsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('elements', function ($table) {
            $table->engine = 'InnoDB';

            $table->string('key');
            $table->string('type');
            $table->mediumtext('value')->nullable();
            $table->string('locale');
            $table->string('locale_group')->nullable();

            $table->primary(['key', 'locale']);
            $table->index(['locale', 'key']);
        });
    }

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

Add locale_group by default to elements

Add locale_group by default to elements

Closes #60


<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:op:title_no_user}',
	);
}

<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:openidProvider:title_no_user}',
	);
}

Fix translation tag for hook for openid provider


<?php
$DIR_BASE_CORE = dirname(__DIR__);
define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackageAutoloaders();
    $cms->setupPackages();
}
$app->setupDefaultCommands();

\Events::dispatch('on_before_console_run');

$app->run();

\Events::dispatch('on_after_console_run');

<?php
$DIR_BASE_CORE = dirname(__DIR__);

if (stripos(PHP_OS, 'WIN') === 0) {
    foreach (array('PHP_SELF', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'PATH_TRANSLATED') as $key) {
        // Check if the key is valid
        if (!isset($_SERVER[$key])) {
            continue;
        }
        $value = $_SERVER[$key];
        if (!is_file($value)) {
            continue;
        }
        // Just to simplify the regular expressions
        $value = str_replace('\\', '/', $value);
        // Check if the key is an absolute path
        if (preg_match('%^([A-Z]:/|//\w)%i', $value) !== 1) {
            continue;
        }
        if (preg_match('%/\.{1,2}/%', $value) !== 0) {
            continue;
        }
        // Ok!
        $DIR_BASE_CORE = dirname(dirname($value));
        break;
    }
    unset($key);
    unset($value);
}

define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackageAutoloaders();
    $cms->setupPackages();
}
$app->setupDefaultCommands();

\Events::dispatch('on_before_console_run');

$app->run();

\Events::dispatch('on_after_console_run');

Fix CLI run with symlinked core directory under Windows

Former-commit-id: 9dea9591bf36665df39e3277222df3f1f8af24f0
Former-commit-id: 88bc301efba74d2352f703366fe64b0c4b599a21


<?php
namespace HomoChecker\View;

class ServerSentEventView implements ViewInterface {
    public $event;

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

        header('Content-Type: text/event-stream');
        flush();
    }

    public function render($data) {
        echo "event: {$this->event}\n";
        echo "data: " . json_encode($data) . "\n\n";
        flush();
    }
}

<?php
namespace HomoChecker\View;

class ServerSentEventView implements ViewInterface {
    public $event;

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

        header('Content-Type: text/event-stream');

        // 2 KiB padding
        echo ":" . str_repeat(" ", 2048) . "\n";

        flush();
    }

    public function render($data) {
        echo "event: {$this->event}\n";
        echo "data: " . json_encode($data) . "\n\n";
        flush();
    }
}

Add extra padding before event-stream output


<?php

namespace Oro\Bundle\SegmentBundle\Migrations\Schema\v1_3;

use Psr\Log\LoggerInterface;

use Oro\Bundle\EntityBundle\ORM\DatabaseDriverInterface;
use Oro\Bundle\MigrationBundle\Migration\ArrayLogger;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedMigrationQuery;

class UpdateSegmentSnapshotDataQuery extends ParametrizedMigrationQuery
{
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        $logger = new ArrayLogger();
        $this->updateSnapshotData($logger, true);

        return $logger->getMessages();
    }

    /**
     * {@inheritdoc}
     */
    public function execute(LoggerInterface $logger)
    {
        $this->updateSnapshotData($logger);
    }

    /**
     * Collect integer_entity_id field in oro_segment_snapshot table
     *
     * @param LoggerInterface $logger
     * @param bool            $dryRun
     */
    protected function updateSnapshotData(LoggerInterface $logger, $dryRun = false)
    {
        $query = <<<SQL
UPDATE oro_segment_snapshot set integer_entity_id = CAST(entity_id as int) WHERE entity_id %s '^[0-9]+$';
SQL;
        $function = 'REGEXP';
        if ($this->connection->getDriver()->getName() === DatabaseDriverInterface::DRIVER_POSTGRESQL) {
            $function = '~';
        }
        $query = sprintf($query, $function);

        $this->logQuery($logger, $query);
        if (!$dryRun) {
            $this->connection->prepare($query)->execute();
        }
    }
}

<?php

namespace Oro\Bundle\SegmentBundle\Migrations\Schema\v1_3;

use Psr\Log\LoggerInterface;

use Oro\Bundle\EntityBundle\ORM\DatabaseDriverInterface;
use Oro\Bundle\MigrationBundle\Migration\ArrayLogger;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedMigrationQuery;

class UpdateSegmentSnapshotDataQuery extends ParametrizedMigrationQuery
{
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        $logger = new ArrayLogger();
        $this->updateSnapshotData($logger, true);

        return $logger->getMessages();
    }

    /**
     * {@inheritdoc}
     */
    public function execute(LoggerInterface $logger)
    {
        $this->updateSnapshotData($logger);
    }

    /**
     * Collect integer_entity_id field in oro_segment_snapshot table
     *
     * @param LoggerInterface $logger
     * @param bool            $dryRun
     */
    protected function updateSnapshotData(LoggerInterface $logger, $dryRun = false)
    {
        $query = <<<SQL
UPDATE oro_segment_snapshot set integer_entity_id = CAST(entity_id as %s) WHERE entity_id %s '^[0-9]+$';
SQL;
        $type = 'UNSIGNED';
        $function = 'REGEXP';
        if ($this->connection->getDriver()->getName() === DatabaseDriverInterface::DRIVER_POSTGRESQL) {
            $function = '~';
            $type = 'int';
        }
        $query = sprintf($query, $type, $function);

        $this->logQuery($logger, $query);
        if (!$dryRun) {
            $this->connection->prepare($query)->execute();
        }
    }
}

CRM-2628: Optimize Static segments
  - fix migration for mySQL


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015-2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\UserBundle\DataFixtures\ORM;

use Darvin\UserBundle\Entity\BaseUser;
use Darvin\UserBundle\User\UserFactoryInterface;
use Darvin\Utils\DataFixtures\ORM\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * User data fixture
 */
class LoadUserData extends AbstractFixture
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager): void
    {
        $manager->persist($this->createUser());
        $manager->flush();
    }

    /**
     * @return \Darvin\UserBundle\Entity\BaseUser
     */
    private function createUser(): BaseUser
    {
        return $this->getUserFactory()->createUser()
            ->setEmail('admin@example.com')
            ->setPlainPassword('admin')
            ->setRoles([
                'ROLE_SUPER_ADMIN',
            ]);
    }

    /**
     * @return \Darvin\UserBundle\User\UserFactoryInterface
     */
    private function getUserFactory(): UserFactoryInterface
    {
        return $this->container->get('darvin_user.user.factory');
    }
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015-2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\UserBundle\DataFixtures\ORM;

use Darvin\UserBundle\Entity\BaseUser;
use Darvin\UserBundle\User\UserFactoryInterface;
use Darvin\Utils\DataFixtures\ORM\AbstractFixture;
use Doctrine\Persistence\ObjectManager;

/**
 * User data fixture
 */
class LoadUserData extends AbstractFixture
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager): void
    {
        $manager->persist($this->createUser());
        $manager->flush();
    }

    /**
     * @return \Darvin\UserBundle\Entity\BaseUser
     */
    private function createUser(): BaseUser
    {
        return $this->getUserFactory()->createUser()
            ->setEmail('admin@example.com')
            ->setPlainPassword('admin')
            ->setRoles([
                'ROLE_SUPER_ADMIN',
            ]);
    }

    /**
     * @return \Darvin\UserBundle\User\UserFactoryInterface
     */
    private function getUserFactory(): UserFactoryInterface
    {
        return $this->container->get('darvin_user.user.factory');
    }
}

Enhance compatibility with Symfony 5.

Enhance compatibility with Symfony 5.


<?php
/**
* Created by PhpStorm.
* User: Danny
* Date: 15/06/2017
* Time: 06:37 PM
*/

namespace App\Http\Controllers;

use App\Notifications\ReviewerNotifier;
use App\SlackToken;
use App\User;
use function dd;
use Illuminate\Http\Request;
use Illuminate\Notifications\Notifiable;
use function json_decode;

class NotifierController
{
    use Notifiable;

    /**
    * Trigger the notification
    *
    * @param Request $request
    */
    public function index(Request $request)
    {
        $notification = json_decode($request->toArray()["payload"], true);

        if (!$notification) return;
        if ($notification["action"] !== "review_requested") return;

        $username = $notification["requested_reviewer"]["login"];
        $slackToken = SlackToken::where("github_username", $username)->first();

        if ($slackToken) {
            $user = User::where("id", $slackToken->user_id)->first();
            $user->notify(new ReviewerNotifier($notification));
        }
    }

    public function noAllowed()
    {
        return view("notifier.notallowed");
    }
}

<?php
/**
* Created by PhpStorm.
* User: Danny
* Date: 15/06/2017
* Time: 06:37 PM
*/

namespace App\Http\Controllers;

use App\Notifications\ReviewerNotifier;
use App\SlackToken;
use App\User;
use function dd;
use Illuminate\Http\Request;
use Illuminate\Notifications\Notifiable;
use function json_decode;

class NotifierController
{
    use Notifiable;

    /**
    * Trigger the notification
    *
    * @param Request $request
    */
    public function index(Request $request)
    {
        $notification = json_decode($request->toArray()["payload"], true);

        // We need this because Github send us a request to verify if the given endpoint exists
        if(is_null(array_key_exists("action", $notification))) return;

        if ($notification["action"] !== "review_requested") return;

        $username = $notification["requested_reviewer"]["login"];
        $slackToken = SlackToken::where("github_username", $username)->first();

        if ($slackToken) {
            $user = User::where("id", $slackToken->user_id)->first();
            $user->notify(new ReviewerNotifier($notification));
        }
    }

    public function noAllowed()
    {
        return view("notifier.notallowed");
    }
}

Validate the test github request

Validate the test github request


<?php

namespace Application\Controller;

use Application\Service\RepositoryRetriever;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ContributorsController extends AbstractActionController
{
    const LIST_LIMIT = 36;

    /**
     * @var RepositoryRetriever
     */
    protected $repositoryRetriever;

    /**
     * @var array
     */
    protected $repositoryData;

    /**
     * @param RepositoryRetriever $repositoryRetriever
     * @param array $repositoryData
     */
    public function __construct(RepositoryRetriever $repositoryRetriever, array $repositoryData)
    {
        $this->repositoryRetriever = $repositoryRetriever;
        $this->repositoryData = $repositoryData;
    }

    public function indexAction()
    {
        $contributors = $this->repositoryRetriever->getContributors($this->repositoryData['owner'], $this->repositoryData['name'], self::LIST_LIMIT);
        $metadata = $this->repositoryRetriever->getUserRepositoryMetadata($this->repositoryData['owner'], $this->repositoryData['name']);

        return new ViewModel([
            'contributors' => $contributors,
            'metadata' => $metadata,
        ]);
    }
}

<?php

namespace Application\Controller;

use Application\Service\RepositoryRetriever;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ContributorsController extends AbstractActionController
{
    const LIST_LIMIT = 36;

    /**
     * @var RepositoryRetriever
     */
    private $repositoryRetriever;

    /**
     * @var array
     */
    private $repositoryData;

    /**
     * @param RepositoryRetriever $repositoryRetriever
     * @param array $repositoryData
     */
    public function __construct(RepositoryRetriever $repositoryRetriever, array $repositoryData)
    {
        $this->repositoryRetriever = $repositoryRetriever;
        $this->repositoryData = $repositoryData;
    }

    public function indexAction()
    {
        $contributors = $this->repositoryRetriever->getContributors($this->repositoryData['owner'], $this->repositoryData['name'], self::LIST_LIMIT);
        $metadata = $this->repositoryRetriever->getUserRepositoryMetadata($this->repositoryData['owner'], $this->repositoryData['name']);

        return new ViewModel([
            'contributors' => $contributors,
            'metadata' => $metadata,
        ]);
    }
}

Fix: Reduce visibility of protected class members to private


<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

    public function __construct($options = array())
    {
        $this->options = array_merge($this->options, $options);
    }

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getPath())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
    }
}

<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

    public function __construct($options = array())
    {
        $this->options = array_merge($this->options, $options);
    }

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@^{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@^{$path}(/.*)?$@", $app->request->getResourceUri());
    }
}

Fix regexp logic when installed into subfolder


<?php

namespace NyroDev\NyroCmsBundle\Model\Entity;

use NyroDev\NyroCmsBundle\Model\User as UserModel;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * User.
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="NyroDev\NyroCmsBundle\Repository\Orm\UserRepository")
 * @Gedmo\Loggable(logEntryClass="NyroDev\NyroCmsBundle\Model\Entity\Log\UserLog")
 * @Gedmo\SoftDeleteable(fieldName="deleted", timeAware=false)
 */
class User extends UserModel
{
    /**
     * @ORM\ManyToMany(targetEntity="UserRole", cascade={"persist"})
     * @ORM\JoinTable(name="user_user_role")
     */
    protected $userRoles;
}

<?php

namespace NyroDev\NyroCmsBundle\Model\Entity;

use NyroDev\NyroCmsBundle\Model\User as UserModel;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * User.
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="NyroDev\NyroCmsBundle\Repository\Orm\UserRepository")
 * @Gedmo\Loggable(logEntryClass="NyroDev\NyroCmsBundle\Model\Entity\Log\UserLog")
 * @Gedmo\SoftDeleteable(fieldName="deleted", timeAware=false)
 * @ORM\HasLifecycleCallbacks
 */
class User extends UserModel
{
    /**
     * @ORM\ManyToMany(targetEntity="UserRole", cascade={"persist"})
     * @ORM\JoinTable(name="user_user_role")
     */
    protected $userRoles;

	/**
	* @ORM\PreRemove()
	*/
	public function preRemove()
    {
        $this->setEmail('_deleted_'.time().$this->getEmail());
        $this->setPasswordKey(null);
	}
}

Add preRemove callbcok for user to change email


<?php

/**
* # Page View Model
*
* Automaticly load page based on slug, throw 404 if page doesn't exist.
*
* @package		Flatfile
* @category		View Model
* @author		Ziopod <ziopod@gmail.com>
* @copyright	(c) 2013-2014 Ziopod
* @license		http://opensource.org/licenses/MIT
**/

class Flatfile_View_Page extends View_App{

	/**
	* @var	object	Flafile page object
	**/
	public $page;

	public function __construct()
	{
		// Try to load Flatfile
		try
		{
			$this->page = new Model_Page(Request::initial()->param('slug'));
		}
		catch (Kohana_Exception $e)
		{
			throw HTTP_Exception::factory(404, __("Unable to find URI :uri"), array(':uri' => Request::initial()->uri()	));
		}

		// HTML meta data
		if ( ! $this->title)
			$this->title = $this->page->title;

		$this->author = $this->page->author;
		$this->license = $this->page->license;
		$this->description = $this->page->description;
	}
}

<?php

/**
* # Page View Model
*
* Automaticly load page based on slug, throw 404 if page doesn't exist.
*
* @package		Flatfile
* @category		View Model
* @author		Ziopod <ziopod@gmail.com>
* @copyright	(c) 2013-2014 Ziopod
* @license		http://opensource.org/licenses/MIT
**/

class Flatfile_View_Page extends View_App{

	/**
	* @var	object	Flafile page object
	**/
	public $page;

	public function __construct()
	{
		// Try to load Flatfile
		try
		{
			$this->page = new Model_Page(Request::initial()->param('slug'));
		}
		catch (Kohana_Exception $e)
		{
			throw HTTP_Exception::factory(404, __("Unable to find URI :uri"), array(':uri' => Request::initial()->uri()	));
		}

		// HTML meta data
		if ($this->page->title)
			$this->title = $this->page->title;

		$this->author = $this->page->author;
		$this->license = $this->page->license;
		$this->description = $this->page->description;
	}
}

Use markdown file title by defautl

Use markdown file title by defautl


<?php require_once 'config.php';

if ($env == 'production')
{
  error_reporting(E_ERROR | E_PARSE);
}

function print_files($url, $dir)
{
  $hide = ".";

  $directory = opendir($dir);

  if ($directory)
  {
    while ($entry_name = readdir($directory))
    {
      $directory_array[] = $entry_name;
    }

    closedir($directory);

    $index_count = count($directory_array);

    sort($directory_array);

    $json = array();

    for ($index = 0; $index < $index_count; $index++)
    {
      if (substr("$directory_array[$index]", 0, 1) != $hide)
      {
        $name = $directory_array[$index];
        $name_href = $directory_array[$index];
        $json[] = array('name' => $name, 'url' => $url .'/'. $name_href);
        echo("

            $name

        ");
      }
    }
    unlink('gifs.json');
    $fp = fopen('gifs.json', 'w');
    fwrite( $fp, json_encode($json) );
    fclose($fp);
  }
  else
  {
    echo("

Couldn't open the directory specified.

    ");
  }
}

<?php require_once 'config.php';

if ($env == 'production')
{
  error_reporting(E_ERROR | E_PARSE);
}

function print_files($url, $dir)
{
  $hide = ".";

  $directory = opendir($dir);

  if ($directory)
  {
    while ($entry_name = readdir($directory))
    {
      $directory_array[] = $entry_name;
    }

    closedir($directory);

    $index_count = count($directory_array);

    sort($directory_array);

    $json = array();

    for ($index = 0; $index < $index_count; $index++)
    {
      if ( substr("$directory_array[$index]", 0, 1) != $hide )
      {
        $name = $directory_array[$index];
        $name_href = $directory_array[$index];
        $category = get_category($name);
        $json[] = array(
          'name' => $name,
          'url' => $url .'/'. $name_href,
          'category' => $category
        );
        echo("

            $name

        ");
      }
    }
    unlink('gifs.json');
    $fp = fopen('gifs.json', 'w');
    fwrite( $fp, json_encode($json) );
    fclose($fp);
  }
  else
  {
    echo("

Couldn't open the directory specified.

    ");
  }
}

function get_category($name)
{
  if ( preg_match("/-/", $name) )
  {
    $string = explode('-', $name);
    return $string[0];
  }
}

Add categories to the JSON file

Add categories to the JSON file


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '10.0.2.2', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Allow access to vagrant webserver

Allow access to vagrant webserver


<?php

namespace Bkstg\CoreBundle\Twig;

use Symfony\Component\Security\Core\User\UserProviderInterface;

class UserExtension extends \Twig_Extension
{
    private $user_provider;

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

    public function getFunctions()
    {
        return [
            new \Twig_Function('get_user', [$this, 'loadUser']),
        ];
    }

    public function loadUser(string $username)
    {
        return $this->user_provider->loadUserByUsername($username);
    }
}

<?php

namespace Bkstg\CoreBundle\Twig;

use Symfony\Component\Security\Core\User\UserProviderInterface;

class UserExtension extends \Twig_Extension
{
    private $user_provider;
    private $cache = [];

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

    public function getFunctions()
    {
        return [
            new \Twig_Function('get_user', [$this, 'loadUser']),
        ];
    }

    public function loadUser(string $username)
    {
        if (!isset($this->cache[$username])) {
            $this->cache[$username] = $this->user_provider->loadUserByUsername($username);
        }
        return $this->cache[$username];
    }
}

Add static caching to twig get_user function.


<?php

namespace Finite\Bundle\FiniteBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class FiniteFiniteExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
        $factoryDefinition = $container->getDefinition('finite.factory');

        foreach ($config as $key => $stateMachineConfig) {
            $definition = clone $container->getDefinition('finite.array_loader');
            $definition->addArgument($stateMachineConfig);
            $definition->addTag('finite.loader');

            $serviceId  = 'finite.loader.'.$key;
            $container->setDefinition($serviceId, $definition);

            $factoryDefinition->addMethodCall('addLoader', array(new Reference($serviceId)));
        }

        $container->removeDefinition('finite.array_loader');
    }
}

<?php

namespace Finite\Bundle\FiniteBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class FiniteFiniteExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
        $factoryDefinition = $container->getDefinition('finite.factory');

        foreach ($config as $key => $stateMachineConfig) {
            $definition = clone $container->getDefinition('finite.array_loader');
            $definition->addArgument($stateMachineConfig);
            $definition->addTag('finite.loader');
            $definition->setLazy(true);

            $serviceId  = 'finite.loader.'.$key;
            $container->setDefinition($serviceId, $definition);

            $factoryDefinition->addMethodCall('addLoader', array(new Reference($serviceId)));
        }

        $container->removeDefinition('finite.array_loader');
    }
}

Add lazy flag to avoid circular reference


<?php

namespace SimplyTestable\WebClientBundle\Controller;

class TestNotificationController extends TestViewController
{
    public function urlLimitAction($test_id, $website) {
        $testRetrievalOutcome = $this->getTestRetrievalOutcome($website, $test_id);
        if ($testRetrievalOutcome->hasResponse()) {
            return $this->sendNotFoundResponse();
        }

        $this->getTestService()->setUser($this->getUser());

        $this->setTemplate('SimplyTestableWebClientBundle:Partials:test-url-limit-notification.html.twig');
        return $this->sendResponse(array(
            'is_logged_in' => !$this->getUserService()->isPublicUser($this->getUser()),
            'remote_test_summary' => $this->getTestService()->getRemoteTestSummary()
        ));
    }
}

<?php

namespace SimplyTestable\WebClientBundle\Controller;

class TestNotificationController extends TestViewController
{
    public function urlLimitAction($test_id, $website) {
        $this->getTestService()->setUser($this->getUser());

        $testRetrievalOutcome = $this->getTestRetrievalOutcome($website, $test_id);
        if ($testRetrievalOutcome->hasResponse()) {
            return $this->sendNotFoundResponse();
        }

        $this->setTemplate('SimplyTestableWebClientBundle:Partials:test-url-limit-notification.html.twig');
        return $this->sendResponse(array(
            'is_logged_in' => !$this->getUserService()->isPublicUser($this->getUser()),
            'remote_test_summary' => $this->getTestService()->getRemoteTestSummary()
        ));
    }
}

Set user for core app service correctly

Set user for core app service correctly


<?php
namespace Aura\Html\Helper\Input;

return array(
    'button'            => function () { return new Generic; },
    'checkbox'          => function () { return new Checkbox; },
    'color'             => function () { return new Generic; },
    'date'              => function () { return new Generic; },
    'datetime'          => function () { return new Generic; },
    'datetime-local'    => function () { return new Generic; },
    'email'             => function () { return new Generic; },
    'file'              => function () { return new Generic; },
    'hidden'            => function () { return new Generic; },
    'image'             => function () { return new Generic; },
    'month'             => function () { return new Generic; },
    'number'            => function () { return new Generic; },
    'password'          => function () { return new Generic; },
    'radio'             => function () { return new Radio; },
    'range'             => function () { return new Generic; },
    'reset'             => function () { return new Generic; },
    'search'            => function () { return new Generic; },
    'select'            => function () { return new Select; },
    'submit'            => function () { return new Generic; },
    'tel'               => function () { return new Generic; },
    'text'              => function () { return new Generic; },
    'textarea'          => function () { return new Textarea; },
    'time'              => function () { return new Generic; },
    'url'               => function () { return new Generic; },
    'week'              => function () { return new Generic; },
];

<?php
namespace Aura\Html\Helper\Input;

return array(
    'button'            => function () { return new Generic; },
    'checkbox'          => function () { return new Checkbox; },
    'color'             => function () { return new Generic; },
    'date'              => function () { return new Generic; },
    'datetime'          => function () { return new Generic; },
    'datetime-local'    => function () { return new Generic; },
    'email'             => function () { return new Generic; },
    'file'              => function () { return new Generic; },
    'hidden'            => function () { return new Generic; },
    'image'             => function () { return new Generic; },
    'month'             => function () { return new Generic; },
    'number'            => function () { return new Generic; },
    'password'          => function () { return new Generic; },
    'radio'             => function () { return new Radio; },
    'range'             => function () { return new Generic; },
    'reset'             => function () { return new Generic; },
    'search'            => function () { return new Generic; },
    'select'            => function () { return new Select; },
    'submit'            => function () { return new Generic; },
    'tel'               => function () { return new Generic; },
    'text'              => function () { return new Generic; },
    'textarea'          => function () { return new Textarea; },
    'time'              => function () { return new Generic; },
    'url'               => function () { return new Generic; },
    'week'              => function () { return new Generic; },
);

Convert left over 5.4 closing bracket

Convert left over 5.4 closing bracket

Closing bracked of array was not converted to 5.3 style


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Exception;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

Fix CS issues reported by php-cs-fixer

Fix CS issues reported by php-cs-fixer

- Remove unused use


<?php
/*************************************************************************************************
 * Copyright 2015 MajorLabel -- This file is a part of MajorLabel coreBOS Customizations.
 * Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
 * file except in compliance with the License. You can redistribute it and/or modify it
 * under the terms of the License. MajorLabel reserves all rights not expressly
 * granted by the License. coreBOS distributed by MajorLabel 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. Unless required by
 * applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing
 * permissions and limitations under the License. You may obtain a copy of the License
 * at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
*************************************************************************************************
*  Author       : MajorLabel, Guido Goluke
*************************************************************************************************/
include('modules/ExactOnline/classes/ExactSettingsDB.class.php');
include('modules/ExactOnline/classes/ExactOAuth.class.php');
include('modules/ExactOnline/classes/ExactApi.class.php');
include('modules/ExactOnline/classes/ExactAccounts.class.php');
include('modules/ExactOnline/classes/ExactItems.class.php');
include('modules/ExactOnline/classes/ExactSalesInvoice.class.php');
?>

<?php
/*************************************************************************************************
 * Copyright 2015 MajorLabel -- This file is a part of MajorLabel coreBOS Customizations.
 * Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
 * file except in compliance with the License. You can redistribute it and/or modify it
 * under the terms of the License. MajorLabel reserves all rights not expressly
 * granted by the License. coreBOS distributed by MajorLabel 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. Unless required by
 * applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing
 * permissions and limitations under the License. You may obtain a copy of the License
 * at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
*************************************************************************************************
*  Author       : MajorLabel, Guido Goluke
*************************************************************************************************/
include('modules/ExactOnline/classes/ExactSettingsDB.class.php');
include('modules/ExactOnline/classes/ExactOAuth.class.php');
include('modules/ExactOnline/classes/ExactApi.class.php');
include('modules/ExactOnline/classes/ExactAccounts.class.php');
include('modules/ExactOnline/classes/ExactItems.class.php');
include('modules/ExactOnline/classes/ExactSalesInvoice.class.php');
include('modules/ExactOnline/classes/ExactPaymentCond.class.php');
?>

Include the new PaymentCondition class in the classinclude file


<?php
namespace Sarcofag\Service\SPI\Widget;

use Sarcofag\Exception\RuntimeException;
use Sarcofag\Service\API\WP;
use Sarcofag\Service\API\WP\Widget as WPWidget;
use Sarcofag\Service\SPI\Widget\Params\RenderableInterface;
use Sarcofag\View\Renderer\RendererInterface;

class ACFWidget extends GenericWidget
{
    /**
     * @var WP
     */
    protected $wpService;

    /**
     * ACFWidget constructor.
     *
     * @param RenderableInterface $widgetParams
     * @param WPWidget $wpWidget
     * @param WP $wpService
     * @param FiltrationInterface|null $filtrationService
     */
    public function __construct(RenderableInterface $widgetParams,
                                WPWidget $wpWidget,
                                WP $wpService,
                                FiltrationInterface $filtrationService = null)
    {
        parent::__construct($widgetParams, $wpWidget, $filtrationService);
        $this->wpService = $wpService;
    }

    /**
     * @param $name
     *
     * @return mixed
     */
    protected function getField($name)
    {
        return $this->wpService->get_field($name, 'widget_'.$this->wpWidget->id);
    }
}

<?php
namespace Sarcofag\Service\SPI\Widget;

use Sarcofag\Exception\RuntimeException;
use Sarcofag\Service\API\WP;
use Sarcofag\Service\API\WP\Widget as WPWidget;
use Sarcofag\Service\SPI\Widget\Params\RenderableInterface;
use Sarcofag\View\Renderer\RendererInterface;

class ACFWidget extends GenericWidget
{
    /**
     * @var WP
     */
    protected $wpService;

    /**
     * ACFWidget constructor.
     *
     * @param RenderableInterface $widgetParams
     * @param WPWidget $wpWidget
     * @param WP $wpService
     * @param FiltrationInterface|null $filtrationService
     */
    public function __construct(RenderableInterface $widgetParams,
                                WPWidget $wpWidget,
                                WP $wpService,
                                FiltrationInterface $filtrationService = null)
    {
        parent::__construct($widgetParams, $wpWidget, $filtrationService);
        $this->wpService = $wpService;
    }

    /**
     * @param $name
     *
     * @return mixed
     */
    protected function getField($name)
    {
        return $this->wpService->get_field($name, 'widget_'.$this->wpWidget->id);
    }

    /**
     * @param array $placeholderParams
     * @param array $settings
     *
     * @return string
     */
    public function render(array $placeholderParams = [], array $settings)
    {
        return $this->renderer->render($this->params->getThemeTemplate(),
            $placeholderParams + ['wpWidget' => $this->wpWidget,
                                  'settings' => $settings,
                                  'getField' => function ($name){return $this->getField($name);}]);
    }
}

Add simple function directly to the view as closure to help get a widget specific Advanced Custom Field


<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
		'App\Console\Commands\Inspire',
		'App\Console\Commands\BackupDatabase',
		'App\Console\Commands\RenameUser',
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule)
	{
		$schedule->command('inspire')
				 ->hourly();
	}

}

<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
		'App\Console\Commands\Inspire',
		'App\Console\Commands\BackupDatabase',
		'App\Console\Commands\RenameUser',
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule)
	{
		$schedule->command('inspire')
				 ->hourly();
	    $schedule->call(function()
	    {
	    	// Do some task...

	    })->hourly();
	    $schedule->exec('composer self-update')->daily();
	    $schedule->command('foo')->cron('* * * * *');
	    $schedule->command('foo')->everyFiveMinutes();
	    $schedule->command('foo')->everyTenMinutes();
	    $schedule->command('foo')->everyThirtyMinutes();
	    $schedule->command('foo')->daily();
	    $schedule->command('foo')->dailyAt('15:00');
	    $schedule->command('foo')->twiceDaily();
	    $schedule->command('foo')->weekdays();
	    $schedule->command('foo')->weekly();
	    $schedule->command('foo')->weeklyOn(1, '8:00');
	    $schedule->command('foo')->monthly();
	    $schedule->command('foo')->mondays();
        $schedule->command('foo')->tuesdays();
        $schedule->command('foo')->thursdays();
        $schedule->command('foo')->fridays();
        $schedule->command('foo')->saturdays();
        $schedule->command('foo')->sundays();
        $schedule->command('foo')->monthly()->environments('production');
        $schedule->command('foo')->monthly()->evenInMaintenanceMode();
        $schedule->command('foo')->monthly()->when(function()
		{
		    return true;
		});
		$schedule->command('foo')->sendOutputTo($filePath)->emailOutputTo('foo@example.com');
		$schedule->command('foo')->sendOutputTo($filePath);
		$schedule->command('foo')->thenPing($url);
	}

}

Add some boilerplate scheduling artisan commands to run some scheduled jobs.


Pending surveys

			Survey ID	Description	Date Scheduled	Accession	Survey Note

@foreach ($pendingSurveys as $pending)

			surveyId)}}">{{ $pending->surveyId }}
			machineId) }}">{{ $pending->description }}
			{{ $pending->test_date}}
			{{ $pending->accession }}
			{{ $pending->notes }}

@endforeach

Pending surveys

			Survey ID	Description	Date Scheduled	Accession	Survey Note

@foreach ($pendingSurveys as $pending)

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

@endforeach

Add link to edit test date information to Pending page

Fixes #177


<?php

global $project;
$project = 'mysite';

global $database;
$database = 'deploynaut';

require_once('conf/ConfigureFromEnv.php');

MySQLDatabase::set_connection_charset('utf8');

SSViewer::set_theme('deploynaut');

BasicAuth::protect_entire_site(true);

DNData::set_builds_dir(BASE_PATH.'/../deploynaut-resources/builds');
DNData::set_environment_dir(BASE_PATH.'/../deploynaut-resources/envs');

<?php

global $project;
$project = 'mysite';

global $database;
$database = 'deploynaut';

require_once('conf/ConfigureFromEnv.php');

MySQLDatabase::set_connection_charset('utf8');

SSViewer::set_theme('deploynaut');

BasicAuth::protect_entire_site(true);

if(defined('DEPLOYNAUT_BUILD_DIR')) {
	DNData::set_builds_dir(DEPLOYNAUT_BUILD_DIR);
} else {
	DNData::set_builds_dir(BASE_PATH.'/../deploynaut-resources/builds');
}

if(defined('DEPLOYNAUT_ENVIRONMENT_DIR')) {
	DNData::set_environment_dir(DEPLOYNAUT_ENVIRONMENT_DIR);
} else {
	DNData::set_environment_dir(BASE_PATH.'/../deploynaut-resources/envs');
}

Allow SS Environment to define the deploynaut external resources


<?php

namespace FD\PrivateMessageBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * ConversationRepository
 */
class ConversationRepository extends EntityRepository
{
    /**
     * Get all conversations of a user being involved in as recipient or author.
     *
     * @param UserInterface $user : instance of the user.
     * @return array
     */
    public function getAllByRecipient(UserInterface $user)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->where('r.id = :user OR c.author = :user')
            ->setParameter('user', $user)
            ->orderBy('c.created', 'DESC');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get a conversation by ID.
     * Related private messages, authors, recipients are loaded by a JOIN statement.
     *
     * @param int $cid : technical ID of the conversation.
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function getOneById($cid)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->join('c.messages', 'm')
            ->join('m.author', 'a')
            ->addSelect('r')
            ->addSelect('m')
            ->addSelect('a')
            ->where('c.id = :cid')
            ->setParameter('cid', $cid)
            ->orderBy('m.created', 'ASC');

        return $qb->getQuery()->getOneOrNullResult();
    }
}

<?php

namespace FD\PrivateMessageBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * ConversationRepository
 */
class ConversationRepository extends EntityRepository
{
    /**
     * Get all conversations of a user being involved in as recipient or author.
     *
     * @param UserInterface $user : instance of the user.
     * @return array
     */
    public function getAllByRecipient(UserInterface $user)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->where('r.id = :user')
            ->setParameter('user', $user)
            ->orderBy('c.created', 'DESC');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get a conversation by ID.
     * Related private messages, authors, recipients are loaded by a JOIN statement.
     *
     * @param int $cid : technical ID of the conversation.
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function getOneById($cid)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->join('c.messages', 'm')
            ->join('m.author', 'a')
            ->addSelect('r')
            ->addSelect('m')
            ->addSelect('a')
            ->where('c.id = :cid')
            ->setParameter('cid', $cid)
            ->orderBy('m.created', 'ASC');

        return $qb->getQuery()->getOneOrNullResult();
    }
}

Update conversation repository: get a conversation by recipient only (not by its author)


<?php

namespace SimplePHPEasyPlus\Iterator;

class CallbackIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testIterate()
    {
        $items = array(1, 2);
        $iteratorable = $this->getMock('SimplePHPEasyPlus\Iterator\IteratorableInterface', array('getItems'), array(), '');
        $iteratorable->expects($this->once())
            ->method('getItems')
            ->will($this->returnValue($items));
        $closure = function($item) { $item++; };
        $iterator = new CallbackIterator($closure);
        $iterator->iterate($iteratorable);
        $this->assertSame(array(2, 3), $items);
    }
}

<?php

namespace SimplePHPEasyPlus\Iterator;

class CallbackIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testIterate()
    {
        $itemMock = $this->getMock('stdClass', array('test'));
        $itemMock->expects($this->once())
            ->method('test');
        $items = array($itemMock);
        $iteratorable = $this->getMock('SimplePHPEasyPlus\Iterator\IteratorableInterface', array('getItems'), array(), '');
        $iteratorable->expects($this->once())
            ->method('getItems')
            ->will($this->returnValue($items));
        $closure = function($item) { $item->test(); };
        $iterator = new CallbackIterator($closure);
        $iterator->iterate($iteratorable);
    }
}

Improve and fix CallbacIterator unit test


<?php

class Bulk_tag extends MX_Controller {
	function index(){
		$data['title'] = 'Bulk Tagging Tool';
		$data['scripts'] = array('bulk_tag_app');
		$data['js_lib'] = array('core', 'angular', 'select2', 'location_capture_widget', 'googleapi', 'google_map');

		$this->load->model("registry/data_source/data_sources","ds");
		$this->load->model("registry/registry_object/registry_objects","ro");
	 	$dataSources = $this->ds->getOwnedDataSources();
		$items = array();
		foreach($dataSources as $ds){
			$item = array();
			$item['title'] = $ds->title;
			$item['key'] = $ds->key;
			array_push($items, $item);
		}
		$data['dataSources'] = $items;

		$data['themepages'] = $this->ro->getAllThemePages();

		$this->load->view('bulk_tag_index', $data);
	}

	function __construct(){
		parent::__construct();
		acl_enforce('ORCA_SOURCE_ADMIN');
	}
}

<?php

class Bulk_tag extends MX_Controller {
	function index(){
		$data['title'] = 'Bulk Tagging Tool';
		$data['scripts'] = array('bulk_tag_app');
		$data['js_lib'] = array('core', 'angular', 'select2', 'location_capture_widget', 'googleapi', 'google_map');

		$this->load->model("registry/data_source/data_sources","ds");
		$this->load->model("registry/registry_object/registry_objects","ro");
	 	$dataSources = $this->ds->getOwnedDataSources();
		$items = array();
		foreach($dataSources as $ds){
			$item = array();
			$item['title'] = $ds->title;
			$item['key'] = $ds->key;
			array_push($items, $item);
		}
		$data['dataSources'] = $items;

		$data['themepages'] = $this->ro->getAllThemePages();

		$this->load->view('bulk_tag_index', $data);
	}

	function __construct(){
		parent::__construct();
		acl_enforce('REGISTRY_USER');
	}
}

Fix - Allow DSA to access bulk tag

Fix - Allow DSA to access bulk tag


<?php

namespace Flugg\Responder\Exceptions;

use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use HandlesApiErrors;

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  Exception                $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function render($request, Exception $exception)
    {
        if ($request->expectsJson()) {
            $this->transformException($exception);

            if ($exception instanceof ApiException) {
                return $this->renderApiError($exception);
            }
        }

        return parent::render($request, $exception);
    }
}

<?php

namespace Flugg\Responder\Exceptions;

use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use HandlesApiErrors;

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  Exception                $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function render($request, Exception $exception)
    {
        $this->transformException($exception);

        if ($exception instanceof ApiException) {
            return $this->renderApiError($exception);
        }

        return parent::render($request, $exception);
    }
}

Revert "only transform exceptions if the request is expecting a json response."

This reverts commit 32c6f94210fe91933e20198de3d73d1d855c5416.