<?php

final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery {

  protected function newQueryFuture() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $commit = $this->getAnchorCommit();

    $options = array(
      '-M',
      '-C',
      '--no-ext-diff',
      '--no-color',
      '--src-prefix=a/',
      '--dst-prefix=b/',
      '-U'.(int)$this->getLinesOfContext(),
    );

    $against = $this->getAgainstCommit();
    if ($against === null) {
      // Check if this is the root commit by seeing if it has parents, since
      // `git diff X^ X` does not work if "X" is the initial commit.
      list($parents) = $repository->execxLocalCommand(
        'log --format=%s %s --',
        '%P',
        $commit);

      if (strlen(trim($parents))) {
        $against = $commit.'^';
      } else {
        $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT;
      }
    }

    $path = $drequest->getPath();
    if (!strlen($path)) {
      $path = '.';
    }

    return $repository->getLocalCommandFuture(
      'diff %Ls %s %s -- %s',
      $options,
      $against,
      $commit,
      $path);
  }

}

<?php

final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery {

  protected function newQueryFuture() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $commit = $this->getAnchorCommit();

    $options = array(
      '-M',
      '-C',
      '--no-ext-diff',
      '--no-color',
      '--src-prefix=a/',
      '--dst-prefix=b/',
      '-U'.(int)$this->getLinesOfContext(),
    );

    $against = $this->getAgainstCommit();
    if ($against === null) {
      // Check if this is the root commit by seeing if it has parents, since
      // `git diff X^ X` does not work if "X" is the initial commit.
      list($parents) = $repository->execxLocalCommand(
        'log -n 1 --format=%s %s --',
        '%P',
        $commit);

      if (strlen(trim($parents))) {
        $against = $commit.'^';
      } else {
        $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT;
      }
    }

    $path = $drequest->getPath();
    if (!strlen($path)) {
      $path = '.';
    }

    return $repository->getLocalCommandFuture(
      'diff %Ls %s %s -- %s',
      $options,
      $against,
      $commit,
      $path);
  }

}

Stop doing an excessive amount of work in `diffusion.rawdiffquery`

Ref T11665.

Without `-n 1`, this logs the ENTIRE history of the repository. We
actually get the right result, but this is egregiously slow. Add `-n 1`
to return only one result.

It appears that I wrote this wrong way back in 2011, in D953. This
query is rarely used (until recently) which is likely why it has
escaped notice for so long.

Test Plan: Used Conduit console to execute `diffusion.rawdiffquery`.
Got the same results but spent 8ms instead of 200ms executing this
command, in a very small repository.


<?php
return array(
    'wizard' => array(
        'default_layout_template' => 'wizard/layout',
        'default_class'           => 'Wizard\Wizard',
    ),
    'service_manager' => array(
        'factories' => array(
            'Wizard\Config'         => 'Wizard\Factory\ConfigFactory',
            'Wizard\Factory'        => 'Wizard\Factory\WizardFactoryFactory',
            'Wizard\WizardRenderer' => 'Wizard\Factory\WizardRendererFactory',
        ),
        'invokables' => array(
            'Wizard\Form\Element\Button\Cancel'   => 'Wizard\Form\Element\Button\Cancel',
            'Wizard\Form\Element\Button\Next'     => 'Wizard\Form\Element\Button\Next',
            'Wizard\Form\Element\Button\Previous' => 'Wizard\Form\Element\Button\Previous',
            'Wizard\Form\Element\Button\Valid'    => 'Wizard\Form\Element\Button\Valid',
            'Wizard\Form\FormFactory'             => 'Wizard\Form\FormFactory',
        ),
    ),

    'view_manager' => array(
        'template_map' => array(
            'wizard/layout'  => __DIR__ . '/../view/wizard/layout.phtml',
            'wizard/header'  => __DIR__ . '/../view/wizard/header.phtml',
            'wizard/buttons' => __DIR__ . '/../view/wizard/buttons.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

<?php
return array(
    'wizard' => array(
        'default_layout_template' => 'wizard/layout',
        'default_class'           => 'Wizard\Wizard',
    ),
    'service_manager' => array(
        'invokables' => array(
            'Wizard\Form\Element\Button\Cancel'   => 'Wizard\Form\Element\Button\Cancel',
            'Wizard\Form\Element\Button\Next'     => 'Wizard\Form\Element\Button\Next',
            'Wizard\Form\Element\Button\Previous' => 'Wizard\Form\Element\Button\Previous',
            'Wizard\Form\Element\Button\Valid'    => 'Wizard\Form\Element\Button\Valid',
            'Wizard\Form\FormFactory'             => 'Wizard\Form\FormFactory',
        ),
        'factories' => array(
            'Wizard\Config'         => 'Wizard\Factory\ConfigFactory',
            'Wizard\Factory'        => 'Wizard\Factory\WizardFactoryFactory',
            'Wizard\WizardRenderer' => 'Wizard\Factory\WizardRendererFactory',
        ),
        'abstract_factories' => array(
            'Wizard\WizardAbstractServiceFactory'
        ),
    ),

    'view_manager' => array(
        'template_map' => array(
            'wizard/layout'  => __DIR__ . '/../view/wizard/layout.phtml',
            'wizard/header'  => __DIR__ . '/../view/wizard/header.phtml',
            'wizard/buttons' => __DIR__ . '/../view/wizard/buttons.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

Declare wizard abstract factory in service manager


<?php
/**
 * PHP Unit Testing
 */

use PHPUnit\Framework\TestCase;

class AppTest extends TestCase
{
    public function testProducerFirst()
    {
		$app = new Core\App;
		$this->assertTrue(true);
        return 'first';
    }

    /**
     * @depends testProducerFirst
     */
    public function testConsumer()
    {
        $this->assertEquals(
            ['first'],
            func_get_args()
        );
    }
}
?>

<?php
/**
 * PHP Unit Testing
 */

use PHPUnit\Framework\TestCase;

class AppTest extends TestCase
{
    public function testProducerFirst()
    {
		$app = new Core\App;
		$app->link('database', Core\Database::connect());
		$app->link('cachemanager', Core\Cache::init());
		$app->link('success', true);
		Core\Sharer::share('app', $app);
		$test = Core\Sharer::get();
		if($test['app']->success == true){
			$this->assertTrue(true);
		}else{
			$this->assertTrue(false);
		}
		$this->assertTrue(true);
        return 'first';
    }

    /**
     * @depends testProducerFirst
     */
    public function testConsumer()
    {
        $this->assertEquals(
            ['first'],
            func_get_args()
        );
    }
}
?>

Add PHP Unit Testing for App

Add PHP Unit Testing for App


<?php

// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.

$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();

$conn_w = $active_table->establishConnection('w');

$active_auto = head(queryfx_one(
  $conn_w,
  'SELECT auto_increment FROM information_schema.tables
    WHERE table_name = %s
    AND table_schema = DATABASE()',
  $active_table->getTableName()));

$active_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $active_table->getTableName()));

$archive_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $archive_table->getTableName()));

$initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max);

queryfx(
  $conn_w,
  'INSERT IGNORE INTO %T (counterName, counterValue)
    VALUES (%s, %d)',
  LiskDAO::COUNTER_TABLE_NAME,
  $active_table->getTableName(),
  $initial_counter + 1);

// Drop AUTO_INCREMENT from the ID column.
queryfx(
  $conn_w,
  'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL',
  $active_table->getTableName());

<?php

// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.

$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();

$conn_w = $active_table->establishConnection('w');

$active_auto = head(queryfx_one(
  $conn_w,
  'SELECT auto_increment FROM information_schema.tables
    WHERE table_name = %s
    AND table_schema = DATABASE()',
  $active_table->getTableName()));

$active_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $active_table->getTableName()));

$archive_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $archive_table->getTableName()));

$initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max);

queryfx(
  $conn_w,
  'INSERT INTO %T (counterName, counterValue)
    VALUES (%s, %d)
    ON DUPLICATE KEY UPDATE counterValue = %d',
  LiskDAO::COUNTER_TABLE_NAME,
  $active_table->getTableName(),
  $initial_counter + 1,
  $initial_counter + 1);

// Drop AUTO_INCREMENT from the ID column.
queryfx(
  $conn_w,
  'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL',
  $active_table->getTableName());

Make Lisk counters patch more robust

Make Lisk counters patch more robust

Summary:
We need to revert this patch and we will need to re-apply it later.
We can't drop the table and delete these rows as we need to run both versions for a temporary period.

Test Plan: Applied it.

Reviewers: epriestley, nh

Reviewed By: epriestley

CC: aran, Korvin

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


<?php

namespace Ob\CampaignBundle\Utils;

use Knp\Snappy\Image;

class Snapshot
{
    /**
     * @var string
     */
    private $folder;

    /**
     * @var string
     */
    private $binaryPath;

    /**
     * @param null   $folder     The folder where to save the image
     * @param string $binaryPath The path to the wkhtmltoimage binary
     */
    public function __construct($folder = null, $binaryPath = '/usr/local/bin/wkhtmltoimage')
    {
        $this->folder = $folder;
        $this->binaryPath = $binaryPath;
    }

    /**
     * @param string $html
     * @param null   $fileName
     *
     * @return string
     */
    public function render($html, $fileName = null)
    {
        if (null == $fileName) {
            $fileName = uniqid() . '.jpg';
        }

        $filePath = $this->folder . $fileName;

        $snappy = new Image($this->binaryPath);
        $snappy->setTimeout(0);
        $snappy->generateFromHtml($html, $filePath);

        return $fileName;
    }
}

<?php

namespace Ob\CampaignBundle\Utils;

use Knp\Snappy\Image;

class Snapshot
{
    /**
     * @var string
     */
    private $folder;

    /**
     * @var string
     */
    private $binaryPath;

    /**
     * @param null   $folder     The folder where to save the image
     * @param string $binaryPath The path to the wkhtmltoimage binary
     */
    public function __construct($folder = null, $binaryPath = '/usr/local/bin/wkhtmltoimage')
    {
        $this->folder = $folder;
        $this->binaryPath = $binaryPath;
    }

    /**
     * @param string $html
     * @param null   $fileName
     *
     * @return string
     */
    public function render($html, $fileName = null)
    {
        if (null == $fileName) {
            $fileName = uniqid() . '.jpg';
        }

        $filePath = $this->folder . $fileName;

        $snappy = new Image($this->binaryPath);
        $snappy->setOption('disable-javascript', true);
        $snappy->setTimeout(0);
        $snappy->generateFromHtml($html, $filePath);

        return $fileName;
    }
}

Update snapshot util, disable javascript

My CentOs server was segfaulting without this option, and having
javascript on to render email templates just don't make any sense
anyway


<?php

class BaseTest extends PHPUnit_Framework_TestCase {

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockAuth;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockClient;

    public function setUp()
    {
        $this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([
            'YOUR_USERNAME',
            'YOUR_PASSWORD',
        ])->getMock();
        $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
    }

    public function testConstructor()
    {
        $client = new \BulkSmsCenter\Client();
        $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
    }

    public function testHttpClientMock()
    {
        $this->mockClient->expects($this->atLeastOnce())->method('setAuth');
        $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');
        $client = new \BulkSmsCenter\Client($this->auth,$this->mockClient);
    }

}

<?php

class BaseTest extends PHPUnit_Framework_TestCase {

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockAuth;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockClient;

    public function setUp()
    {
        $this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([
            'YOUR_USERNAME',
            'YOUR_PASSWORD',
        ])->getMock();
        $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
    }

    public function testConstructor()
    {
        $client = new \BulkSmsCenter\Client();
        $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
    }

    public function testHttpClientMock()
    {
        $this->mockClient->expects($this->atLeastOnce())->method('setAuth');
        $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');

        $client = new \BulkSmsCenter\Client($this->mockAuth,$this->mockClient);
    }

}

Use Auth mock for Client

Use Auth mock for Client


<?php
/**
 * Clean up the_excerpt()
 */
function roots_excerpt_more($more) {
  return ' … ' . __('Continued', 'roots') . '';
}
add_filter('excerpt_more', 'roots_excerpt_more');

/**
 * Manage output of wp_title()
 */
function roots_wp_title($title) {
  if (is_feed()) {
    return $title;
  }

  $title .= get_bloginfo('name');

  return $title;
}
add_filter('wp_title', 'roots_wp_title', 10);

function add_search_to_wp_menu($items, $args) {
  if($args->theme_location === 'footer_navigation') {
    $items .= '
';
    $items .= load_template_part('templates/searchform');
    $items .= '
';
  }

  return $items;
}
add_filter('wp_nav_menu_items','add_search_to_wp_menu',10,2);

function load_template_part($template_name, $part_name=null) {
    ob_start();
    get_template_part($template_name, $part_name);
    $var = ob_get_contents();
    ob_end_clean();
    return $var;
}

Include navigation bar in footer nav

Include navigation bar in footer nav


<form role="search" method="get" class="navbar-form" action="<?php echo esc_url(home_url('/')); ?>">
  <?php _e('Search for:', 'roots'); ?>

    <input type="search" value="<?php echo get_search_query(); ?>" name="s" class="search-field form-control" required>

      <button type="submit" class="search-submit btn btn-default"><?php _e('Search', 'roots'); ?></button>

</form>

<form role="search" method="get" class="navbar-form" action="<?php echo esc_url(home_url('/')); ?>">

    <input type="search" value="<?php echo get_search_query(); ?>" name="s" class="search-field form-control" required>

      <button type="submit" class="search-submit btn btn-default" aria-label="検索"></button>

</form>

Change a search form for the navbar

Change a search form for the navbar


<?php

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

class CreateUserTokensTable extends Migration
{
    /**
     * @var string $table - Table name.
     */
    protected $table;

    /**
     * @var string $foreignKey - Column name for foreign keys.
     */
    protected $foreignKey;

    /**
     * Initialise the migration.
     */
    public function __construct()
    {
        $this->table = $this->config('token_table');

        $this->foreignKey = $this->config('user_foreign_key');
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->increments('id');
            $table->integer($this->foreignKey)->unsigned();
            $table->string('token')->index();
            $table->timestamps();

            $table->foreign($this->foreignKey)->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->table);
    }

    /**
     * Retrieve a setting from the package configuration.
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    private function config($key, $default = null)
    {
        return config("jwt.{$key}", $default);
    }
}

<?php

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

class CreateUserTokensTable extends Migration
{

    /**
     * @var string $tableName - Table name.
     */
    protected $tableName;

    /**
     * Initialise the migration.
     */
    public function __construct()
    {
        $this->tableName = Config::get('jwt.claim_table_name');
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableName, function (Blueprint $table) {
            $table->increments('id');
            $table->string('subject')->unsigned();
            $table->string('audience')->unsigned();
            $table->string('jwt_id')->index();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->tableName);
    }

}

Update migration according to the new structure


<?php
var_dump('vendor/bin/condorcet-doc "'.__DIR__.'/Documentation/"');
    shell_exec('vendor/bin/condorcet-doc "'.__DIR__.'/Documentation/"');

<?php
    $cmd = 'vendor/bin/condorcet-doc "'.__DIR__.'/Documentation"';
    $cmd = str_replace('/', DIRECTORY_SEPARATOR, $cmd);

    shell_exec($cmd);

Fix update documentation (need more tests)


<?php

use Illuminate\Database\Migrations\Migration;

class RenameClientTable extends Migration
{
    /**
     * The raw MongoDB interface.
     * @var MongoDB
     */
    protected $mongodb;

    public function __construct()
    {
        $this->mongodb = app('db')->getMongoDB();
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // The 'jenssegers/laravel-mongodb' package doesn't support Schema::rename so...
        $this->mongodb->execute('db.api_keys.renameCollection("clients");');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $this->mongodb->execute('db.clients.renameCollection("api_keys");');
    }
}

<?php

use Illuminate\Database\Migrations\Migration;

class RenameClientTable extends Migration
{
    /**
     * The raw MongoDB interface.
     * @var MongoDB
     */
    protected $mongodb;

    public function __construct()
    {
        $this->mongodb = app('db')->getMongoDB();
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // The 'jenssegers/laravel-mongodb' package doesn't support Schema::rename so...
        $this->mongodb->execute('db.api_keys.renameCollection("clients", true);');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $this->mongodb->execute('db.clients.renameCollection("api_keys", true);');
    }
}

Update migration to overwrite existing destination table.

I think migrations were failing because a "lookup" would end up creating
the destination table in the QA/Thor database, and then trying to use
the `renameCollection` method would silently fail because the table
already existed.

See:
https://docs.mongodb.org/manual/reference/method/db.collection.renameCollection/


<?php
/**
 * Este archivo contiene toda la logica de negocio asociada a los detalles de las vacaciones.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.controllers
 * @since           Pragtico v 1.0.0
 * @version         $Revision: 971 $
 * @modifiedby      $LastChangedBy: mradosta $
 * @lastmodified    $Date: 2009-09-16 11:51:11 -0300 (Wed, 16 Sep 2009) $
 * @author          Martin Radosta <mradosta@pragmatia.com>
 */
/**
 * La clase encapsula la logica de negocio asociada a los detalles de las vacaciones.
 *
 * @package     pragtico
 * @subpackage  app.controllers
 */
class VacacionesDetallesController extends AppController {

}
?>

<?php
/**
 * Este archivo contiene toda la logica de negocio asociada a los detalles de las vacaciones.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.controllers
 * @since           Pragtico v 1.0.0
 * @version         $Revision: 971 $
 * @modifiedby      $LastChangedBy: mradosta $
 * @lastmodified    $Date: 2009-09-16 11:51:11 -0300 (Wed, 16 Sep 2009) $
 * @author          Martin Radosta <mradosta@pragmatia.com>
 */
/**
 * La clase encapsula la logica de negocio asociada a los detalles de las vacaciones.
 *
 * @package     pragtico
 * @subpackage  app.controllers
 */
class VacacionesDetallesController extends AppController {

	var $uses = 'VacacionesDetalle';

}
?>

Add model to controller to avoid inflection error


        @if (isset($selectedDominion) && ($selectedDominion->round->isActive()))
            @php
            $diff = $selectedDominion->round->start_date->diff(Carbon\Carbon::now());
            $plusoneday = $diff->days + 1;
            $roundDurationInDays = $selectedDominion->round->start_date->diffInDays($selectedDominion->round->end_date);

            echo "Day {$plusoneday}/{$roundDurationInDays}, hour {$diff->h}.";

            @endphp
        @endif
        Version: {!! $version !!}

     View this project on GitHub

        @if (isset($selectedDominion) && ($selectedDominion->round->isActive()))
            @php
            $diff = $selectedDominion->round->start_date->subDays(1)->diff(Carbon\Carbon::now());
            $roundDurationInDays = $selectedDominion->round->start_date->diffInDays($selectedDominion->round->end_date);

            echo "Day {$diff->d}/{$roundDurationInDays}, hour {$diff->h}.";

            @endphp
        @endif
        Version: {!! $version !!}

     View this project on GitHub

Refactor 'one day to counter' (was actually -1, not +1)


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Routing\Exception;

use Cake\Core\Exception\Exception;

/**
 * Exception raised when a URL cannot be reverse routed
 * or when a URL cannot be parsed.
 */
class MissingRouteException extends Exception
{

    /**
     * {@inheritDoc}
     */
    protected $_messageTemplate = 'A route matching "%s" could not be found.';

    /**
     * Message template to use when the requested method is included.
     *
     * @var  string
     */
    protected $_messageTemplateWithMethod = 'A "%s" route matching "%s" could not be found.';

    /**
     * {@inheritDoc}
     */
    public function __construct($message, $code = 404)
    {
        if (is_array($message)) {
            if (isset($message['message'])) {
                $this->_messageTemplate = $message['message'];
            } elseif (isset($message['method']) && $message['method']) {
                $this->_messageTemplate = $this->_messageTemplateWithMethod;
            }
        }
        parent::__construct($message, $code);
    }
}

Fix double space in doc string.

Fix double space in doc string.

Refs #9995


<?php

namespace Emergence\SiteAdmin;

use Person;
use User;

class DashboardRequestHandler extends \RequestHandler
{
    public static function handleRequest()
    {
        $GLOBALS['Session']->requireAccountLevel('Administrator');

        return static::respond('dashboard', [
            'metrics' => [
                [
                    'label' => 'People',
                    'value' => Person::getCount(),
                    'link' => '/people'
                ],
                [
                    'label' => 'Users',
                    'value' => User::getCount(['Username IS NOT NULL']),
                    'link' => '/people?q=class:User'
                ],
                [
                    'label' => 'Administrators',
                    'value' => User::getCount(['AccountLevel' => 'Administrator']),
                    'link' => '/people?q=accountlevel:Administrator'
                ],
                [
                    'label' => 'Developers',
                    'value' => User::getCount(['AccountLevel' => 'Developer']),
                    'link' => '/people?q=accountlevel:Developer'
                ]
            ]
        ]);
    }
}

<?php

namespace Emergence\SiteAdmin;

use Site;
use Person;
use User;
use Emergence\Util\ByteSize;

class DashboardRequestHandler extends \RequestHandler
{
    public static function handleRequest()
    {
        $GLOBALS['Session']->requireAccountLevel('Administrator');

        // get available memory
        $availableMemory = null;
        $availableSwap = null;

        $memoryOutput = explode(PHP_EOL, trim(shell_exec('free -b')));
        array_shift($memoryOutput);

        foreach ($memoryOutput AS $line) {
            $line = preg_split('/\s+/', $line);

            if ($line[0] == 'Mem:') {
                $availableMemory = $line[3];
            } elseif ($line[0] == 'Swap:') {
                $availableSwap = $line[3];
            }
        }

        // render
        return static::respond('dashboard', [
            'metrics' => [
                [
                    'label' => 'People',
                    'value' => Person::getCount(),
                    'link' => '/people'
                ],
                [
                    'label' => 'Users',
                    'value' => User::getCount(['Username IS NOT NULL']),
                    'link' => '/people?q=class:User'
                ],
                [
                    'label' => 'Administrators',
                    'value' => User::getCount(['AccountLevel' => 'Administrator']),
                    'link' => '/people?q=accountlevel:Administrator'
                ],
                [
                    'label' => 'Developers',
                    'value' => User::getCount(['AccountLevel' => 'Developer']),
                    'link' => '/people?q=accountlevel:Developer'
                ],
                [
                    'label' => 'Available Storage',
                    'value' => ByteSize::format(exec('df --output=avail ' . escapeshellarg(Site::$rootPath)))
                ],
                [
                    'label' => 'Available Memory',
                    'value' => $availableMemory ? ByteSize::format($availableMemory) : null
                ],
                [
                    'label' => 'Available Swap',
                    'value' => $availableSwap ? ByteSize::format($availableSwap) : null
                ]
            ]
        ]);
    }
}

Add disk and memory stats to dashboard

Add disk and memory stats to dashboard


<?php
/**
 * Created by PhpStorm.
 * User: sonja
 * Date: 1/26/18
 * Time: 10:30 AM
 */

namespace AppBundle\API\Sharing;

use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Permissions;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;

class Projects
{
    private $manager;

    const ERROR_NOT_LOGGED_IN = "Error. You are not logged in.";

    /**
     * Projects constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    public function execute($email, $projectId, $action){
        $user = $this->manager->getRepository(FennecUser::class)->findOneBy(array(
            'email' => $email
        ));
        $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array(
            'webuserDataId' => $projectId
        ));
        $permission = new Permissions();
        $permission->setWebuser($user);
        $permission->setWebuserData($project);
        $permission->setPermission($action);
        $this->manager->persist($permission);
        $this->manager->flush();
        $message = "The permission '".$action."' of project ".$projectId." was granted to ".$user->getUsername()." successfully.";
        return $message;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: sonja
 * Date: 1/26/18
 * Time: 10:30 AM
 */

namespace AppBundle\API\Sharing;

use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Permissions;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;

class Projects
{
    private $manager;

    const ERROR_NOT_LOGGED_IN = "Error. You are not logged in.";
    const ERROR_PERMISSION_EXISTS = "Error. The permission for the user and the project exists.";

    /**
     * Projects constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    public function execute($email, $projectId, $action){
        $user = $this->manager->getRepository(FennecUser::class)->findOneBy(array(
            'email' => $email
        ));
        $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array(
            'webuserDataId' => $projectId
        ));
        $permission = $this->manager->getRepository(Permissions::class)->findOneBy(array(
            'webuser' => $user->getId(),
            'webuserData' => $projectId,
            'permission' => $action
        ));
        if($permission !== null){
            return Projects::ERROR_PERMISSION_EXISTS;
        }
        $permission = new Permissions();
        $permission->setWebuser($user);
        $permission->setWebuserData($project);
        $permission->setPermission($action);
        $this->manager->persist($permission);
        $this->manager->flush();
        $message = "The permission '".$action."' of project ".$projectId." was granted to ".$user->getUsername()." successfully.";
        return $message;
    }
}

Add simple check to throw error if permissions exists


<?php
/*
 * This file is part of the PayBreak/basket package.
 *
 * (c) PayBreak <dev@paybreak.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PayBreak\Sdk\Entities\Product;

use WNowicki\Generic\AbstractEntity;

/**
 * Merchant Fees Entity
 *
 * @author EB
 * @method $this setPercentage(int $percentage)
 * @method int|null getPercentage()
 * @method $this setMinimumAmount(int $minimumAmount)
 * @method int|null getMinimumAmount()
 * @method $this setMaximumAmount(int $maximumAmount)
 * @method int|null getMaximumAmount()
 * @method $this setCancellation(int $cancellation)
 * @method int|null getCancellation()
 * @package PayBreak\Sdk\Entities
 */
class MerchantFeesEntity extends AbstractEntity
{
    protected $properties = [
        'percentage',
        'minimum_amount',
        'maximum_amount',
        'cancellation',
    ];
}

<?php
/*
 * This file is part of the PayBreak/basket package.
 *
 * (c) PayBreak <dev@paybreak.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PayBreak\Sdk\Entities\Product;

use WNowicki\Generic\AbstractEntity;

/**
 * Merchant Fees Entity
 *
 * @author EB
 * @method $this setPercentage(int $percentage)
 * @method int|null getPercentage()
 * @method $this setMinimumAmount(int $minimumAmount)
 * @method int|null getMinimumAmount()
 * @method $this setMaximumAmount(int $maximumAmount)
 * @method int|null getMaximumAmount()
 * @method $this setCancellation(int $cancellation)
 * @method int|null getCancellation()
 * @method $this setLiabilityClawback(int $liabilityClawback)
 * @method int|null getLiabilityClawback()
 * @package PayBreak\Sdk\Entities
 */
class MerchantFeesEntity extends AbstractEntity
{
    protected $properties = [
        'percentage',
        'minimum_amount',
        'maximum_amount',
        'cancellation',
        'liability_clawback',
    ];
}

Add LC fee to entity

Add LC fee to entity


<?php

declare(strict_types=1);

namespace App\EventListener;

use App\Service\Config;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;

/**
 * Sends errors to symfony
 */
class SentryCaptureListener
{
    /**
     * @var bool
     */
    protected $errorCaptureEnabled;

    public function __construct(
        Config $config,
        string $sentryDSN
    ) {
        $this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
        if ($this->errorCaptureEnabled) {
            sentryInit(['dsn' => $sentryDSN]);
        }
    }

    public function onKernelException(ExceptionEvent $event)
    {
        if ($this->errorCaptureEnabled) {
            $exception = $event->getThrowable();
            //don't report 404s to Sentry
            if ($exception instanceof NotFoundHttpException) {
                return;
            }
            sentryCaptureException($exception);
        }
    }
}

<?php

declare(strict_types=1);

namespace App\EventListener;

use App\Classes\SessionUserInterface;
use App\Service\Config;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Sentry\State\Scope;

use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;
use function Sentry\configureScope as sentryConfigureScope;

/**
 * Sends errors to symfony
 */
class SentryCaptureListener
{
    /**
     * @var bool
     */
    protected $errorCaptureEnabled;

    /**
     * @var TokenStorageInterface
     */
    protected TokenStorageInterface $tokenStorage;

    public function __construct(
        Config $config,
        TokenStorageInterface $tokenStorage,
        string $sentryDSN
    ) {
        $this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
        if ($this->errorCaptureEnabled) {
            sentryInit(['dsn' => $sentryDSN]);
        }
        $this->tokenStorage = $tokenStorage;
    }

    public function onKernelException(ExceptionEvent $event)
    {
        if ($this->errorCaptureEnabled) {
            $exception = $event->getThrowable();
            //don't report 404s to Sentry
            if ($exception instanceof NotFoundHttpException) {
                return;
            }
            $token = $this->tokenStorage->getToken();
            if ($token) {
                /** @var SessionUserInterface $sessionUser */
                $sessionUser = $token->getUser();
                sentryConfigureScope(function (Scope $scope) use ($sessionUser): void {
                    $scope->setUser([
                        'id' => $sessionUser->getId(),
                    ]);
                });
            }

            sentryCaptureException($exception);
        }
    }
}

Add userId to sentry errors

Add userId to sentry errors

If a user is authenticated we can add their ID to our logs and possibly
determine the source of some errors more clearly.


<?php

namespace App\Command\Email;

class SendAdminNotificationEmailCommand extends AbstractSendEmailCommand
{
    /**
     * @var string
     */
    protected $userName;

    public function __construct(string $recipient, string $userName)
    {
        parent::__construct($recipient);
        $this->userName = $userName;
    }

    /**
     * @return string
     */
    public function getUsername(): string
    {
        return $this->userName;
    }
}

<?php

namespace App\Command\Email;

class SendAdminNotificationEmailCommand extends AbstractSendEmailCommand
{
    /**
     * @var string
     */
    protected $userName;

    public function __construct(string $recipient, string $userName, string $userOrganization)
    {
        parent::__construct($recipient);
        $this->userName = $userName;
        $this->userOrganization = $userOrganization;
    }

    /**
     * @return string
     */
    public function getUsername(): string
    {
        return $this->userName;
    }

    /**
     * @return string
     */
    public function getOrganization(): string
    {
      return $this->userOrganization;
    }
}

Add user organization to admin notofiy command.


    getFilename() }}">

	@if ($page->publish)

		<video
			id="{{ $page->getFilename() }}"
			class="video-js vjs-default-skin vjs-fluid vjs-16-9 vjs-big-play-centered"
			controls
			poster="{{ $page->poster }}"
			data-setup='{ "techOrder": ["youtube"], "sources": [{ "type": "video/youtube", "src": "{{ $page->video }}"}] }'
		></video>

	@else

		poster }}" class="unpublished" alt="{{ $page->posterAlt }}"/>

	@endif

Add anchor links to videos

Add anchor links to videos


<?php

namespace Michaeljennings\Carpenter\Pagination;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\BootstrapThreePresenter;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;

class IlluminateDriver implements PaginatorContract
{
    /**
     * An instance of the IOC container.
     *
     * @var mixed
     */
    protected $app;

    /**
     * The illuminate paginator.
     *
     * @var mixed
     */
    protected $paginator;

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

    /**
     * Create a new paginator.
     *
     * @param  string|integer $total
     * @param  string|integer $perPage
     * @return mixed
     */
    public function make($total, $perPage)
    {
        $this->paginator = new LengthAwarePaginator([], $total, $perPage, $this->app['request']->input('page'), [
            'path' => $this->app['request']->url(),
        ]);

        return $this->paginator;
    }

    /**
     * Get the pagination links.
     *
     * @return string
     */
    public function links()
    {
        return $this->paginator->render(new BootstrapThreePresenter($this->paginator));
    }

    /**
     * Get the current page.
     *
     * @return integer|string
     */
    public function currentPage()
    {
        return $this->paginator->currentPage();
    }
}

<?php

namespace Michaeljennings\Carpenter\Pagination;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\BootstrapThreePresenter;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;

class IlluminateDriver implements PaginatorContract
{
    /**
     * An instance of the IOC container.
     *
     * @var mixed
     */
    protected $app;

    /**
     * The illuminate paginator.
     *
     * @var mixed
     */
    protected $paginator;

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

    /**
     * Create a new paginator.
     *
     * @param  string|integer $total
     * @param  string|integer $perPage
     * @return mixed
     */
    public function make($total, $perPage)
    {
        $this->paginator = new LengthAwarePaginator([], $total, $perPage, $this->app['request']->input('page'), [
            'path' => $this->app['request']->url(),
        ]);

        return $this;
    }

    /**
     * Get the pagination links.
     *
     * @return string
     */
    public function links()
    {
        return $this->paginator->render(new BootstrapThreePresenter($this->paginator));
    }

    /**
     * Get the current page.
     *
     * @return integer|string
     */
    public function currentPage()
    {
        return $this->paginator->currentPage();
    }
}

Update illuminate paginator return instance rather than paginator on make


<?php

	if(KEY == '' || $_GET['key'] != KEY) {
		header("Location: /");
		die();
	}

	$subdirs = array(	'overall' => 21,
						'3month' => 21,
						'6month' => 21,
						'12month' => 21,
						'weekly' => 7,
						'group' =>7
					);
	$imagedir = "./images/";

	echo "
" . $_SERVER['SERVER_NAME'] . "
";
	echo "Cleanup on " . date("D M j G:i:s T Y");

	foreach($subdirs AS $subdir => $days) {
		echo "
" . $subdir . "

";
		$handle=opendir($imagedir . $subdir . "/");
		while ($file = readdir($handle)) {
			if($file != ".." && $file != "." && (filemtime($imagedir . $subdir . "/" . $file) < (time()-(60*60*24*$days)))) {
				if(isset($_GET['simulate']) || unlink($imagedir . $subdir . "/" . $file))
					echo "deleted: " . $imagedir . $subdir . "/" . $file . "
";
			}
		}
		closedir($handle);
	}

<?php

	require_once("defines.php");

	if(KEY == '' || $_GET['key'] != KEY) {
		header("Location: /");
		die();
	}

	$subdirs = array(	'overall' => 21,
						'3month' => 21,
						'6month' => 21,
						'12month' => 21,
						'weekly' => 7,
						'group' =>7
					);
	$imagedir = "./images/";

	echo "
" . $_SERVER['SERVER_NAME'] . "
";
	echo "Cleanup on " . date("D M j G:i:s T Y");

	foreach($subdirs AS $subdir => $days) {
		echo "
" . $subdir . "

";
		$handle=opendir($imagedir . $subdir . "/");
		while ($file = readdir($handle)) {
			if($file != ".." && $file != "." && (filemtime($imagedir . $subdir . "/" . $file) < (time()-(60*60*24*$days)))) {
				if(isset($_GET['simulate']) || unlink($imagedir . $subdir . "/" . $file))
					echo "deleted: " . $imagedir . $subdir . "/" . $file . "
";
			}
		}
		closedir($handle);
	}

Include defines while cleaning up

Include defines while cleaning up


<?php
return [
    'SplunkDao' => [
        'urls' => [
            'fetchFivehundredsForAlertWidget' => ':baseUrl:/services/search/jobs/export',
        ],
    ],
];

<?php
return [
    'SplunkDao' => [
        'urls' => [
            'fetchFivehundredsForAlertWidget' => ':baseUrl:/services/search/jobs',
        ],
    ],
];

Switch Splunk Dao from export endpoint to normal search/job endpoint as suggested in splunk docs


<?php

namespace Oro\Bundle\TagBundle\EventListener;

use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\DataGridBundle\Datagrid\RequestParameters;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Event\BuildAfter;

class TagSearchResultsGridListener
{
    /** @var  RequestParameters */
    protected $requestParams;

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

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

    public function onBuildAfter(BuildAfter $event)
    {
        $datasource = $event->getDatagrid()->getDatasource();
        if ($datasource instanceof OrmDatasource) {
            /** @var QueryBuilder $query */
            $queryBuilder = $datasource->getQuery();

            $queryBuilder->setParameter('tag', $this->requestParams->get('tag_id', 0));

            $searchEntity = $this->requestParams->get('from', '*');
            if ($searchEntity != '*' && !empty($searchEntity)) {
                $queryBuilder->andWhere('tt.alias = :alias')
                    ->setParameter('alias', $searchEntity);
            }
        }
    }
}

<?php

namespace Oro\Bundle\TagBundle\EventListener;

use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\DataGridBundle\Datagrid\RequestParameters;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Event\BuildAfter;

class TagSearchResultsGridListener
{
    /** @var  RequestParameters */
    protected $requestParams;

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

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

    /**
     * Adjust query for tag-results-grid (tag search result grid)
     * after datasource has been built
     *
     * @param BuildAfter $event
     */
    public function onBuildAfter(BuildAfter $event)
    {
        $datasource = $event->getDatagrid()->getDatasource();
        if ($datasource instanceof OrmDatasource) {
            /** @var QueryBuilder $query */
            $queryBuilder = $datasource->getQuery();

            $queryBuilder->setParameter('tag', $this->requestParams->get('tag_id', 0));

            $searchEntity = $this->requestParams->get('from', '*');
            if ($searchEntity != '*' && !empty($searchEntity)) {
                $queryBuilder->andWhere('tt.alias = :alias')
                    ->setParameter('alias', $searchEntity);
            }
        }
    }
}

BAP-1835: Change all grids
- add phpdoc for tag grid listener


<?php

namespace Knp\Bundle\SnappyBundle\Snappy\Response;

use Symfony\Component\HttpFoundation\Response as Base;

abstract class SnappyResponse extends Base
{
    public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array())
    {
        $contentDispositionDirectives = ['inline', 'attachment'];
        if (!in_array($contentDisposition, $contentDispositionDirectives)) {
            throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition));
        }

        parent::__construct($content, $status, $headers);
        $this->headers->add(array('Content-Type' => $contentType));
        $this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName)));
    }
}

<?php

namespace Knp\Bundle\SnappyBundle\Snappy\Response;

use Symfony\Component\HttpFoundation\Response as Base;

abstract class SnappyResponse extends Base
{
    public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array())
    {
        $contentDispositionDirectives = array('inline', 'attachment');
        if (!in_array($contentDisposition, $contentDispositionDirectives)) {
            throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition));
        }

        parent::__construct($content, $status, $headers);
        $this->headers->add(array('Content-Type' => $contentType));
        $this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName)));
    }
}

Fix php5.3 incompatible array definition


<?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\ThemeBundle\Tests\Manager\Admin;

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

/**
 * Class ThemeManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ThemeManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('theme.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\ThemeBundle\Tests\Manager\Admin;

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

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

Return types in manager tests

Return types in manager tests


<?php namespace SendGrid\Mail;

class Category implements \JsonSerializable
{
    private $category;

    public function __construct(string $category=null)
    {
        if(isset($category)) $this->setCategory($category);
    }

    public function getCategory()
    {
        return $this->category;
    }

    public function setCategory(string $category)
    {
        $this->category = $category;
    }

    public function jsonSerialize()
    {
        return $this->getCategory();
    }
}

<?php namespace SendGrid\Mail;

class Category implements \JsonSerializable
{
    private $category;

    public function __construct($category=null)
    {
        if(isset($category)) $this->setCategory($category);
    }

    public function getCategory()
    {
        return $this->category;
    }

    public function setCategory($category)
    {
        $this->category = $category;
    }

    public function jsonSerialize()
    {
        return $this->getCategory();
    }
}

Remove Type Hinting for PHP 5 compatibility


<?php

namespace Behat\Mink\Tests\Driver;

use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Tests\Driver\Util\FixturesKernel;
use Symfony\Component\HttpKernel\Client;

class BrowserKitConfig extends AbstractConfig
{
    public static function getInstance()
    {
        return new self();
    }

    /**
     * {@inheritdoc}
     */
    public function createDriver()
    {
        $client = new Client(new FixturesKernel());

        return new BrowserKitDriver($client);
    }

    /**
     * {@inheritdoc}
     */
    public function getWebFixturesUrl()
    {
        return 'http://localhost';
    }

    protected function supportsJs()
    {
        return false;
    }

    public function skipMessage($testCase, $test)
    {
        if (
            'Behat\Mink\Tests\Driver\Form\Html5Test' === $testCase
            && in_array($test, array(
                'testHtml5FormAction',
                'testHtml5FormMethod',
            ))
            && !method_exists('Symfony\Component\DomCrawler\Tests\FormTest', 'testGetMethodWithOverride')
        ) {
            return 'Mink BrowserKit doesn\'t support HTML5 form attributes before Symfony 3.3';
        }

        return parent::skipMessage($testCase, $test);
    }
}

<?php

namespace Behat\Mink\Tests\Driver;

use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Tests\Driver\Util\FixturesKernel;
use Symfony\Component\HttpKernel\Client;

class BrowserKitConfig extends AbstractConfig
{
    public static function getInstance()
    {
        return new self();
    }

    /**
     * {@inheritdoc}
     */
    public function createDriver()
    {
        $client = new Client(new FixturesKernel());

        return new BrowserKitDriver($client);
    }

    /**
     * {@inheritdoc}
     */
    public function getWebFixturesUrl()
    {
        return 'http://localhost';
    }

    protected function supportsJs()
    {
        return false;
    }

    public function skipMessage($testCase, $test)
    {
        if (
            'Behat\Mink\Tests\Driver\Form\Html5Test' === $testCase
            && in_array($test, array(
                'testHtml5FormAction',
                'testHtml5FormMethod',
            ))
            && !method_exists('Symfony\Component\DomCrawler\Tests\FormTest', 'testGetMethodWithOverride')
            // Symfony 4.4 removed tests from dist archives, making the previous detection return a false-positive
            && !method_exists('Symfony\Component\DomCrawler\Form', 'getName')
        ) {
            return 'Mink BrowserKit doesn\'t support HTML5 form attributes before Symfony 3.3';
        }

        return parent::skipMessage($testCase, $test);
    }
}

Fix the detection of HTML5 support in the testsuite

The detection relied on detecting the test method added when introducing
the feature in symfony/dom-crawler. But as of Symfony 4.4, tests are
stripped from the dist archives. An additional detection based on a new
method added in later Symfony version is now used to filter out the
false positives (not detecting 4.4 and newer as being <3.3).


<?php

namespace WyriHaximus\React\Tests\ChildProcess\Pool;

use WyriHaximus\React\ChildProcess\Pool\FlexiblePool;
use WyriHaximus\React\ChildProcess\Pool\PoolInterface;

class FlexiblePoolTest extends AbstractPoolTest
{
    /**
     * @return PoolInterface
     */
    public function getPool()
    {
        return new FlexiblePool($this->process, $this->loop);
    }
}

<?php

namespace WyriHaximus\React\Tests\ChildProcess\Pool;

use WyriHaximus\React\ChildProcess\Pool\FlexiblePool;
use WyriHaximus\React\ChildProcess\Pool\PoolInterface;

class FlexiblePoolTest extends AbstractPoolTest
{
    /**
     * @return PoolInterface
     */
    public function getPool()
    {
        return new FlexiblePool($this->process, $this->loop, [
            'min_size' => 1,
        ]);
    }
}

Set min size to one

Set min size to one


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            $this->addUsernameReferer();
        }

        $this->redirectToWebsite();
    }

    private function addUsernameReferer()
    {
        $sUsername = $this->httpRequest->get('aff');

        if ((new ExistsCoreModel)->username($sUsername, DbTableName::AFFILIATE)) {
            (new Affiliate)->addRefer($sUsername);
        }
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            $this->addReferer();
        }

        $this->redirectToWebsite();
    }

    private function addReferer()
    {
        $sUsername = $this->httpRequest->get('aff');

        if ((new ExistsCoreModel)->username($sUsername, DbTableName::AFFILIATE)) {
            (new Affiliate)->addRefer($sUsername);
        }
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

Rename method name to shorter one

Rename method name to shorter one


<?php
 //markdown CMS default config (same as ../site-config.php until changed for new website)
 if(function_exists("Md_RequestRoot")){
 $MD_SETTINGS = array(
        "SITE_NAME" => "↓markdown↓CMS↓",
        "SITE_LOGO" => "/md/images/markdown-cms-logo.png",
        "FAVICON" => "/md/images/markdown-cms.ico",
        "HOME" => Md_RequestRoot(),
        "EXTENSIONS" => "md,php,html,txt,zip",
        "INFO_TOP_FILE" => "info.top.txt",
        "SITE_SEARCH" => "search.code.txt",
        "PAGE_END_FILE" => "page.end.txt",
        "NO_COOKIE_MESSAGE" => "",
        "XML_SITEMAP_REFRESH" => "-1 week"
    );
 }
    //Filters for index page and sitemap.
    $NO_INDEX=array('images'=>'*',
                    'md'=>'*');
    //Array used to rename entries on Index page
    $INDEX_RENAME=array();

    date_default_timezone_set("UTC");   //change as required
?>

<?php
 //markdown CMS default config (same as ../site-config.php until changed for new website)
 if(function_exists("Md_RequestRoot")){
 $MD_SETTINGS = array(
        "SITE_NAME" => "↓markdown↓CMS↓",
        "SITE_LOGO" => "/md/images/markdown-cms-logo.png",
        "FAVICON" => "/md/images/markdown-cms.ico",
        "HOME" => Md_RequestRoot(),
        "EXTENSIONS" => "md,php,html,txt,zip",
        "INFO_TOP_FILE" => "info.top.txt",
        "SITE_SEARCH" => "search.code.txt",
        "PAGE_END_FILE" => "page.end.txt",
        "NO_COOKIE_MESSAGE" => "",
        //"SHARE_BUTTONS" => "",
        "XML_SITEMAP_REFRESH" => "-1 week"
    );
 }
    //Filters for index page and sitemap.
    $NO_INDEX=array('images'=>'*',
                    'md'=>'*');
    //Array used to rename entries on Index page
    $INDEX_RENAME=array();

    date_default_timezone_set("UTC");   //change as required
?>

Add ability to configure share buttons.

Add ability to configure share buttons.

Social media sharing buttons can be turned on or off.


<?php

$loader = require_once __DIR__.'/../vendor/autoload.php';
$loader->add('Sitemap\\', __DIR__);

<?php

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Sitemap\\', __DIR__);

Use require instead of require_once

Use require instead of require_once


<?php

namespace ATPCore\Model;

class Module extends \ATP\ActiveRecord
{
	public function getActiveModules()
	{
		return $this->loadMultiple("is_active = 1");
	}

	public function getActiveModuleNames()
	{
		$names = array();
		foreach($this->getActiveModules() as $module)
		{
			$names[] = $module->name;
		}

		return $names;
	}
}
Module::init();

<?php

namespace ATPCore\Model;

class Module extends \ATP\ActiveRecord
{
	public function displayName()
	{
		return $this->name;
	}

	public function getActiveModules()
	{
		return $this->loadMultiple("is_active = 1");
	}

	public function getActiveModuleNames()
	{
		$names = array();
		foreach($this->getActiveModules() as $module)
		{
			$names[] = $module->name;
		}

		return $names;
	}
}
Module::init();

Change module model display name from id to name


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

namespace Flarum\Event;

/**
 * Configure forum routes.
 *
 * This event is fired when routes for the forum client are being registered.
 */
class ConfigureForumRoutes extends AbstractConfigureRoutes
{
    /**
     * {@inheritdoc}
     */
    public function get($url, $name, $handler = 'Flarum\Forum\Action\ClientAction')
    {
        parent::get($url, $name, $handler);
    }
}

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

namespace Flarum\Event;

/**
 * Configure forum routes.
 *
 * This event is fired when routes for the forum client are being registered.
 */
class ConfigureForumRoutes extends AbstractConfigureRoutes
{
    /**
     * {@inheritdoc}
     */
    public function get($url, $name, $handler = 'Flarum\Forum\Controller\ClientController')
    {
        parent::get($url, $name, $handler);
    }
}

Fix default forum route controller

Fix default forum route controller


<?php

namespace acd;

trait Singleton {

    /** @var static Singleton instance */
    protected static $instance;

    /**
     * Get Instance
     * @return void Returns self instance
     */
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }

    final private function __construct() { }

    final private function __clone() { }

    final private function __wakeup() { }

}

<?php

namespace acd;

trait Singleton {

    /** @var static Singleton instance */
    protected static $instance;

    /**
     * Get Instance
     * @return void Returns self instance
     */
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }

    protected function __construct() { }

    protected function __clone() { }

    protected function __wakeup() { }

}

Change singleton trait access methods

Change singleton trait access methods


<?php
include('vendor/autoload.php');

use TddFizzBuzz\FizzBuzzBang;

$fizzer = new FizzBuzzBang();

foreach(range(1,5000) as $num) {
    $message = $fizzer->run($num);
    echo "$message ";
    if ('BangBangBangBang' === $message) {
        echo '!' . PHP_EOL;
        exit;
    }
}

<?php
include('vendor/autoload.php');

use TddFizzBuzz\FizzBuzzBang;

$fizzer = new FizzBuzzBang();

foreach(range(1,5000) as $num) {
    $message = $fizzer->run($num);
    if ('BangBangBang' === $message) {
        echo "{$message}!" . PHP_EOL;
        exit;
    }
    echo "$message ";
}

Reduce string check to 'BangBangBang' because it sounds better than 4 bangs.


<?php
/*
Template Name: Partner
*/
?>

    <?php get_template_part('templates/page', 'header'); ?>
    <?php get_template_part('templates/content', 'page'); ?>

        <?php if( have_rows('partner_logos') ) { ?>

            <?php while ( have_rows('partner_logos') ) { the_row(); ?>

                    <?php $sub = get_sub_field('logo_image'); ?>
                    <img src="<?php echo $sub['url']; ?>">

            <?php } ?>

        <?php } ?>

Fix amount of partner logos.

Fix amount of partner logos.


<?php

if (version_compare(PHP_VERSION, '5.4.0', '<')) {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

	}

} else {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

		/**
		 * Provide iterator for bulk loading from.
		 * Records are expected to be 1 dimensional key-value arrays.
		 * @return Iterator
		 */
		abstract public function getIterator();

	}

}

<?php

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

	}

Fix issue with php version 5.3.3

Fix issue with php version 5.3.3


<?php

/**
 * Add to Pages you want changes recorded for
 *
 * @author stephen@silverstripe.com.au
 * @license BSD License http://silverstripe.org/bsd-license/
 */
class SiteTreeChangeRecordable extends ChangeRecordable {

	public function onAfterPublish(&$original) {
		$this->dataChangeTrackService->track($this->owner, 'Publish');
	}

	public function onAfterUnpublish() {
		$this->dataChangeTrackService->track($this->owner, 'Unpublish');
	}

	public function updateCMSFields(FieldList $fields) {
		//Get all data changes relating to this page filter them by publish/unpublish
		$dataChanges = DataChangeRecord::get()->filter('ClassID', $this->owner->ID)->exclude('ChangeType', 'Change');
		//create a gridfield out of them
		$gridFieldConfig = GridFieldConfig_RecordViewer::create();
		$publishedGrid = new GridField('PublishStates', 'Published States', $dataChanges, $gridFieldConfig);
		$dataColumns = $publishedGrid->getConfig()->getComponentByType('GridFieldDataColumns');
		$dataColumns->setDisplayFields(array('ChangeType'			=> 'Change Type',
												'ObjectTitle'		=> 'Page Title',
												'ChangedBy.Title' 	=> 'User',
												'Created'			=> 'Modification Date',
						));

		//linking through to the datachanges modeladmin

		$fields->addFieldsToTab('Root.PublishedState', $publishedGrid);
		return $fields;
	}
}

<?php

/**
 * Add to Pages you want changes recorded for
 *
 * @author stephen@silverstripe.com.au
 * @license BSD License http://silverstripe.org/bsd-license/
 */
class SiteTreeChangeRecordable extends ChangeRecordable {

	public function onAfterPublish(&$original) {
		$this->dataChangeTrackService->track($this->owner, 'Publish');
	}

	public function onAfterUnpublish() {
		$this->dataChangeTrackService->track($this->owner, 'Unpublish');
	}

	public function updateCMSFields(FieldList $fields) {
		if (Permission::check('CMS_ACCESS_DataChangeAdmin')) {
			//Get all data changes relating to this page filter them by publish/unpublish
			$dataChanges = DataChangeRecord::get()->filter('ClassID', $this->owner->ID)->exclude('ChangeType', 'Change');
			//create a gridfield out of them
			$gridFieldConfig = GridFieldConfig_RecordViewer::create();
			$publishedGrid = new GridField('PublishStates', 'Published States', $dataChanges, $gridFieldConfig);
			$dataColumns = $publishedGrid->getConfig()->getComponentByType('GridFieldDataColumns');
			$dataColumns->setDisplayFields(array('ChangeType'			=> 'Change Type',
													'ObjectTitle'		=> 'Page Title',
													'ChangedBy.Title' 	=> 'User',
													'Created'			=> 'Modification Date',
							));

			//linking through to the datachanges modeladmin

			$fields->addFieldsToTab('Root.PublishedState', $publishedGrid);
			return $fields;
		}
	}
}

FIX Ensure only those with perms to datachanges can view published state


<?php
namespace akilli;

use ErrorException;
use Throwable;

/**
 * Initialize application
 */
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
    include_once $file;
}

/**
 * Error handler
 */
set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
);
set_exception_handler(
    function (Throwable $e) {
        echo '
' . (string) $e . '
';
    }
);
register_shutdown_function(
    function () {
        $error = error_get_last();
        $errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];

        if ($error && in_array($error['type'], $errors)) {
            echo '
' . print_r($error, 1) . '
';
        }
    }
);

/**
 * Run application
 */
app();

<?php
namespace akilli;

use ErrorException;
use Throwable;

/**
 * Initialize application
 */
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
    include_once $file;
}

/**
 * Error handler
 */
set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
);
set_exception_handler(
    function (Throwable $e) {
        critical((string) $e);
    }
);
register_shutdown_function(
    function () {
        $error = error_get_last();
        $errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];

        if ($error && in_array($error['type'], $errors)) {
            critical(print_r($error, 1));
        }
    }
);

/**
 * Run application
 */
app();

Use the logger within exception handler and shutdown function


<?php namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Session;
use Redirect;
use App\Business;
use Flash;

class BusinessController extends Controller {

	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->middleware('auth');
	}

	public function getHome()
	{
		$business = Business::find( Session::get('selected.business_id') );
		if (empty($business)) {
			Flash::warning(trans('user.business.msg.please_select_a_business'));
			return Redirect::route('user.businesses.list');
		}
		return view('user.businesses.show', compact('business'));
	}

	public function getList()
	{
		$businesses = Business::all();
		return view('user.businesses.index', compact('businesses'));
	}

	public function getSelect($business_slug)
	{
		try {
			$business_id = Business::where('slug', $business_slug)->first()->id;
		} catch (Exception $e) {
			return 'ERROR';
		}
		Session::set('selected.business_id', $business_id);
		return Redirect::route('user.businesses.home');
	}

	public function getSuscriptions()
	{
		$contacts = \Auth::user()->contacts;
		return view('user.businesses.suscriptions', compact('contacts'));
	}
}

<?php namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Session;
use Redirect;
use App\Business;
use Flash;

class BusinessController extends Controller {

	public function getHome()
	{
		$business = Business::find( Session::get('selected.business_id') );
		if (empty($business)) {
			Flash::warning(trans('user.business.msg.please_select_a_business'));
			return Redirect::route('user.businesses.list');
		}
		return view('user.businesses.show', compact('business'));
	}

	public function getList()
	{
		$businesses = Business::all();
		return view('user.businesses.index', compact('businesses'));
	}

	public function getSelect($business_slug)
	{
		try {
			$business_id = Business::where('slug', $business_slug)->first()->id;
		} catch (Exception $e) {
			return 'ERROR';
		}
		Session::set('selected.business_id', $business_id);
		return Redirect::route('user.businesses.home');
	}

	public function getSuscriptions()
	{
		$contacts = \Auth::user()->contacts;
		return view('user.businesses.suscriptions', compact('contacts'));
	}
}

Remove middleware already declarated on routes


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name'              => 'required|string|min:1',
            'last_name'               => 'required|string|min:1',
            'email'                   => 'email',
            'password_confirm'        => 'sometimes|required_with:password',
        ];
    }
}

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name'              => 'required|string|min:1',
            'email'                   => 'email',
            'password_confirm'        => 'sometimes|required_with:password',
        ];
    }
}

Remove last name requirement from Form Request


<?php
/**
 *@file
 * Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator.
 */

namespace Drupal\AppConsole\Generator;

class PluginImageEffectGenerator extends Generator
{
  /**
   * Generator Plugin Image Effect
   * @param  string $module         Module name
   * @param  string $class_name     Plugin Class name
   * @param  string $plugin_label   Plugin label
   * @param  string $plugin_id      Plugin id
   * @param  string $description    Plugin description
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $description)
  {

    $parameters = [
      'module'   => $module,
      'class'     => [
        'name'      => $class_name,
      ],
      'plugin_label' => $plugin_label,
      'plugin_id' => $plugin_id,
      'description' => $description,
    ];

    $this->renderFile(
      'module/plugin-imageeffect.php.twig',
      $this->getPluginPath($module, 'ImageEffect').'/'.$class_name.'.php',
      $parameters
    );
  }
}

<?php
/**
 *@file
 * Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator.
 */

namespace Drupal\AppConsole\Generator;

class PluginImageEffectGenerator extends Generator
{
  /**
   * Generator Plugin Image Effect
   * @param  string $module         Module name
   * @param  string $class_name     Plugin Class name
   * @param  string $plugin_label   Plugin label
   * @param  string $plugin_id      Plugin id
   * @param  string $description    Plugin description
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $description)
  {

    $parameters = [
      'module'   => $module,
      'class_name' => $class_name,
      'plugin_label' => $plugin_label,
      'plugin_id' => $plugin_id,
      'description' => $description,
    ];

    $this->renderFile(
      'module/plugin-imageeffect.php.twig',
      $this->getPluginPath($module, 'ImageEffect').'/'.$class_name.'.php',
      $parameters
    );
  }
}

Rename argument, remove unusued one

Rename argument, remove unusued one


<?php

namespace OpenClassrooms\Bundle\DoctrineCacheExtensionBundle\DependencyInjection\Compiler;

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

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class ServiceCompilerPass implements CompilerPassInterface
{
    /**
     * @var string[]
     */
    public static $types =
        [
            'apc',
            'array',
            'couchbase',
            'file_system',
            'memcache',
            'memcached',
            'mongodb',
            'php_file',
            'redis',
            'riak',
            'wincache',
            'xcache',
            'zenddata',
        ];

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $factoryService = $this->getFactoryService();
        foreach (self::$types as $type) {
            $definition = $container->findDefinition('doctrine_cache.abstract.'.$type);
            $definition->setFactory([new Reference($factoryService), 'create']);
            $definition->addArgument($type);
        }
    }

    /**
     * @return string
     */
    protected function getFactoryService()
    {
        return 'oc.doctrine_cache_extensions.cache_provider_decorator_factory';
    }
}

<?php

namespace OpenClassrooms\Bundle\DoctrineCacheExtensionBundle\DependencyInjection\Compiler;

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

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class ServiceCompilerPass implements CompilerPassInterface
{
    /**
     * @var string[]
     */
    public static $types =
        [
            'apc',
            'apcu',
            'array',
            'couchbase',
            'file_system',
            'memcache',
            'memcached',
            'mongodb',
            'php_file',
            'redis',
            'riak',
            'wincache',
            'xcache',
            'zenddata',
        ];

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $factoryService = $this->getFactoryService();
        foreach (self::$types as $type) {
            $definition = $container->findDefinition('doctrine_cache.abstract.'.$type);
            $definition->setFactory([new Reference($factoryService), 'create']);
            $definition->addArgument($type);
        }
    }

    /**
     * @return string
     */
    protected function getFactoryService()
    {
        return 'oc.doctrine_cache_extensions.cache_provider_decorator_factory';
    }
}

Add support for apcu cache

Add support for apcu cache


<?php

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

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer;

class RepeatedType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->appendClientTransformer(new ValueToDuplicatesTransformer(array(
                $options['first_name'],
                $options['second_name'],
            )))
            ->add($options['first_name'], $options['type'], $options['options'])
            ->add($options['second_name'], $options['type'], $options['options'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultOptions(array $options)
    {
        return array(
            'type'              => 'text',
            'options'           => array(),
            'first_name'        => 'first',
            'second_name'       => 'second',
            'error_bubbling'    => false,
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'repeated';
    }
}

<?php

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

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer;

class RepeatedType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->appendClientTransformer(new ValueToDuplicatesTransformer(array(
                $options['first_name'],
                $options['second_name'],
            )))
            ->add($options['first_name'],  $options['type'], 0 < count($options['first_options'])  ? $options['first_options']  : $options['options'])
            ->add($options['second_name'], $options['type'], 0 < count($options['second_options']) ? $options['second_options'] : $options['options'])

        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultOptions(array $options)
    {
        return array(
            'type'           => 'text',
            'options'        => array(),
            'first_options'  => array(),
            'second_options' => array(),
            'first_name'     => 'first',
            'second_name'    => 'second',
            'error_bubbling' => false,
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'repeated';
    }
}

[Form] Allow setting different options to repeating fields


<?php
declare(strict_types=1);

namespace WoohooLabs\Zen\Examples;

use WoohooLabs\Zen\Config\AbstractCompilerConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfigInterface;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfig;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfigInterface;
use WoohooLabs\Zen\Examples\Controller\AbstractController;
use WoohooLabs\Zen\Examples\Controller\ControllerInterface;

class CompilerConfig extends AbstractCompilerConfig
{
    public function getContainerNamespace(): string
    {
        return "WoohooLabs\\Zen\\Examples";
    }

    public function getContainerClassName(): string
    {
        return "Container";
    }

    public function useConstructorInjection(): bool
    {
        return true;
    }

    public function usePropertyInjection(): bool
    {
        return true;
    }

    public function getAutoloadConfig(): AutoloadConfigInterface
    {
        return AutoloadConfig::enabledGlobally(realpath(__DIR__  . "/.."))
            ->setAlwaysAutoloadedClasses(
                [
                    ControllerInterface::class,
                ]
            )
            ->setExcludedClasses(
                [
                    AbstractController::class
                ]
            );
    }

    public function getFileBasedDefinitionConfig(): FileBasedDefinitionConfigInterface
    {
        return FileBasedDefinitionConfig::disabledGlobally("Definitions/");
    }

    public function getContainerConfigs(): array
    {
        return [
            new ContainerConfig(),
        ];
    }
}

<?php
declare(strict_types=1);

namespace WoohooLabs\Zen\Examples;

use WoohooLabs\Zen\Config\AbstractCompilerConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfigInterface;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfig;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfigInterface;
use WoohooLabs\Zen\Examples\Controller\AbstractController;
use WoohooLabs\Zen\Examples\Controller\ControllerInterface;

class CompilerConfig extends AbstractCompilerConfig
{
    public function getContainerNamespace(): string
    {
        return "WoohooLabs\\Zen\\Examples";
    }

    public function getContainerClassName(): string
    {
        return "Container";
    }

    public function useConstructorInjection(): bool
    {
        return true;
    }

    public function usePropertyInjection(): bool
    {
        return true;
    }

    public function getAutoloadConfig(): AutoloadConfigInterface
    {
        ;
        return AutoloadConfig::enabledGlobally(dirname(__DIR__))
            ->setAlwaysAutoloadedClasses(
                [
                    ControllerInterface::class,
                ]
            )
            ->setExcludedClasses(
                [
                    AbstractController::class
                ]
            );
    }

    public function getFileBasedDefinitionConfig(): FileBasedDefinitionConfigInterface
    {
        return FileBasedDefinitionConfig::disabledGlobally("Definitions/");
    }

    public function getContainerConfigs(): array
    {
        return [
            new ContainerConfig(),
        ];
    }
}

Use dirname instead of realpath

Use dirname instead of realpath


<?php

use Illuminate\Database\Migrations\Migration;

use App\Models\Queues\WaitTime;

class RemoveQlessQueues extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        WaitTime::find(1980)->delete();
        WaitTime::find(1981)->delete();
        WaitTime::find(1982)->delete();
        WaitTime::find(1983)->delete();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
    }
}

<?php

use Illuminate\Database\Migrations\Migration;

use App\Models\Queues\WaitTime;

class RemoveQlessQueues extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        WaitTime::destroy(1980,1981,1982,1983);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
    }
}

Update syntax of database deletes to account for them not existing [API-178]


<?php
/**
 * @package module.twitterconnect
 */
class twitterconnect_ListAuthorizedaccountsbywebsiteService extends BaseService
{
	/**
	 * @var twitterconnect_ListAccountsbywebsiteService
	 */
	private static $instance;
	private $items = null;

	/**
	 * @return twitterconnect_ListAccountsbywebsiteService
	 */
	public static function getInstance()
	{
		if (is_null(self::$instance))
		{
			self::$instance = self::getServiceClassInstance(get_class());
		}
		return self::$instance;
	}

	/**
	 * @return array<list_Item>
	 */
	public final function getItems()
	{
		try
		{
			$request = Controller::getInstance()->getContext()->getRequest();
			$websiteId = intval($request->getParameter('websiteId', 0));
			$website = DocumentHelper::getDocumentInstance($websiteId);
		}
		catch (Exception $e)
		{
			if (Framework::isDebugEnabled())
			{
				Framework::debug(__METHOD__ . ' EXCEPTION: ' . $e->getMessage());
			}
			return array();
		}

		$items = array();
		foreach (twitterconnect_AccountService::getInstance()->getAuthorizedByWebsite($website) as $account)
		{
			$items[] = new list_Item(
				$account->getLabel(),
				$account->getId()
			);
		}
		return $items;
	}
}

<?php
/**
 * @package module.twitterconnect
 */
class twitterconnect_ListAuthorizedaccountsbywebsiteService extends BaseService
{
	/**
	 * @var twitterconnect_ListAccountsbywebsiteService
	 */
	private static $instance;
	private $items = null;

	/**
	 * @return twitterconnect_ListAccountsbywebsiteService
	 */
	public static function getInstance()
	{
		if (is_null(self::$instance))
		{
			self::$instance = self::getServiceClassInstance(get_class());
		}
		return self::$instance;
	}

	/**
	 * @return array<list_Item>
	 */
	public function getItems()
	{
		try
		{
			$request = Controller::getInstance()->getContext()->getRequest();
			$websiteId = intval($request->getParameter('websiteId', 0));
			$website = DocumentHelper::getDocumentInstance($websiteId);
		}
		catch (Exception $e)
		{
			if (Framework::isDebugEnabled())
			{
				Framework::debug(__METHOD__ . ' EXCEPTION: ' . $e->getMessage());
			}
			return array();
		}

		$items = array();
		foreach (twitterconnect_AccountService::getInstance()->getAuthorizedByWebsite($website) as $account)
		{
			$items[] = new list_Item(
				$account->getLabel(),
				$account->getId()
			);
		}
		return $items;
	}
}

[REFACTOR] Remove "final" keyword on getItems and getDefaultId methods in dynamic list services.


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ValidationRequest;
use App\Models\ValidatorInvite;
use App\Models\Company;
use App\Models\Validator;
use App\Models\Alert;
use App\Notifications\NewAlerts;
use App\Notifications\ValidationsPending;

class Cleanup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cleanup:all';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Does the cleanup and other daily tasks for Talented Europe entities';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        ValidationRequest::cleanup();
        ValidatorInvite::cleanup();
        $validators = Validator::whereHas('user', function ($query) {
            $query->where('notify_me', true);
        })->whereHas('validationRequest')->get();
        $alerts = Alert::get();
        foreach ($validators as $val) {
            $val->user->notify(new ValidationsPending($val->user));
        }
        foreach ($alerts as $al) {
            $al->target->notify(new NewAlerts($al->target));
        }
    }
}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ValidationRequest;
use App\Models\ValidatorInvite;
use App\Models\Company;
use App\Models\Validator;
use App\Models\Alert;
use App\Notifications\NewAlerts;
use App\Notifications\ValidationsPending;

class Cleanup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cleanup:all';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Does the cleanup and other daily tasks for Talented Europe entities';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        ValidationRequest::cleanup();
        ValidatorInvite::cleanup();
        $validators = Validator::whereHas('user', function ($query) {
            $query->where('notify_me', true);
        })->whereHas('validationRequest.student.user', function ($f) {
            $f->where('valid', '!=', 'validated');
        })->get();

        $alerts = Alert::get();
        foreach ($validators as $val) {
            $val->user->notify(new ValidationsPending($val->user));
        }
        foreach ($alerts as $al) {
            $al->target->notify(new NewAlerts($al->target));
        }
    }
}

Fix mailing all validators even when they have their students validated


<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title><?php wp_title('|', true, 'right'); ?></title>
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<?php wp_head(); ?>

	<link href='//ajax.googleapis.com' rel='dns-prefetch' />
    <% if (includeHumans) { %>
	<link href='<?php echo get_stylesheet_directory_uri(); ?>/humans.txt' rel='author' type='text/plain' />
    <% } %>
    <% if (includeLogo) { %>
	<link href='<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logo.svg' rel='logo' type='image/svg' />
    <% } %>
	<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">

	<meta content='false' http-equiv='imagetoolbar' />
	<meta content='éGz - http://egztudio.com/' name='author' />
</head>

<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title><?php wp_title('|', true, 'right'); ?></title>
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<?php wp_head(); ?>

	<link href='//ajax.googleapis.com' rel='dns-prefetch' />
    <% if (includeHumans) { %>
	<link href='<?php echo get_stylesheet_directory_uri(); ?>/humans.txt' rel='author' type='text/plain' />
    <% } %>
    <% if (includeLogo) { %>
	<link href='<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logo.svg' rel='logo' type='image/svg' />
    <% } %>
	<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo esc_url(get_feed_link()); ?>">

	<meta content='false' http-equiv='imagetoolbar' />
	<meta content='éGz - http://egztudio.com/' name='author' />
</head>

Use get_feed_link for RSS URL

Use get_feed_link for RSS URL


<?php

namespace Matthias\Codesniffer\Sequence\Expectation;

use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;

class Quantity implements ExpectationInterface
{
    const ANY = null;

    private $innerExpectation;
    private $minimum;
    private $maximum;

    public function __construct(ExpectationInterface $innerExpectation, $minimum, $maximum)
    {
        $this->innerExpectation = $innerExpectation;
        $this->minimum = $minimum;
        $this->maximum = $maximum;
    }

    public function match(SequenceInterface $sequence)
    {
        $occurrences = 0;

        while (!$sequence->endOfSequence()) {
            try {
                $this->innerExpectation->match($sequence);
                $occurrences++;
                $sequence->next();
            } catch (ExpectationNotMatched $exception) {
                break;
            }
        }

        $this->matchOccurrences($occurrences);
    }

    private function matchOccurrences($occurrences)
    {
        if ($this->minimum !== null && $occurrences < $this->minimum) {
            throw new ExpectationNotMatched();
        }

        if ($this->maximum !== null && $occurrences > $this->maximum) {
            throw new ExpectationNotMatched();
        }
    }
}

<?php

namespace Matthias\Codesniffer\Sequence\Expectation;

use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;

class Quantity implements ExpectationInterface
{
    const ANY = null;

    /**
     * @var $innerExpectation ExpectationInterface[]
     */
    private $innerExpectations;
    private $minimum;
    private $maximum;

    public function __construct($innerExpectation, $minimum, $maximum)
    {
        // TODO this should be refactored, probably introduce an "iterator" expectation
        $this->innerExpectations = is_array($innerExpectation) ? $innerExpectation : array($innerExpectation);
        $this->minimum = $minimum;
        $this->maximum = $maximum;
    }

    public function match(SequenceInterface $sequence)
    {
        $occurrences = 0;

        while (!$sequence->endOfSequence()) {
            try {
                foreach ($this->innerExpectations as $innerExpectation) {
                    $innerExpectation->match($sequence);
                    $sequence->next();
                }

                $occurrences++;
            } catch (ExpectationNotMatched $exception) {
                break;
            }
        }

        $this->matchOccurrences($occurrences);
    }

    private function matchOccurrences($occurrences)
    {
        if ($this->minimum !== null && $occurrences < $this->minimum) {
            throw new ExpectationNotMatched();
        }

        if ($this->maximum !== null && $occurrences > $this->maximum) {
            throw new ExpectationNotMatched();
        }
    }
}

Add option for multiple inner expectations


Extemporaneous Conference Caling

Enter two or more telephone numbers and submit the form.  Each number will be called and, if they pick up, will be bridged to a conference.

<form method="get" id="theForm" action="/api/bridge">

<input name="numbers[]" class="input" type="text" />

<input name="numbers[]" class="input" type="text" />

<input type="submit" />
</form>

Extemporaneous Conference Calling

Enter two or more telephone numbers and submit the form.  Each number will be called and, if they pick up, will be bridged to a conference.

<form method="get" id="theForm" action="/api/bridge">

<input name="numbers[]" class="input" type="text" />

<input name="numbers[]" class="input" type="text" />

<input type="submit" />
</form>

Fix typographical error in markup.

Fix typographical error in markup.


<?php

/**
* Using to correctly generate  urls
*/
class UrlHelper{

	//returns string url for admin home page
	static function adminHomeLink(): string{
		return '/admin';
	}

	//returns string url for admin page index link
	static function indexLinkFor(string $model): string{
		return self::adminHomeLink().'/'.$model::slug();
	}

	//returns string url to add new item to model
	static function addLinkFor(string $model): string{
		return self::indexLinkFor($model).'/add';
	}

	//return string url to edit an item
	static function editLinkFor(string $model, int $itemId): string{
		return self::indexLinkFor($model).'/edit/'.$itemId;
	}
}

<?php

/**
* Using to correctly generate  urls
*/
class UrlHelper{

	//string added to urls to represent 'add' action
	static function addVerb(): string{
		return 'add';
	}

	//string added to urls to represent 'edit' action
	static function editVerb(): string{
		return 'edit';
	}

	//returns string url for admin home page
	static function adminHomeLink(): string{
		return '/admin';
	}

	//returns string url for admin page index link
	static function indexLinkFor(string $model): string{
		return self::adminHomeLink().'/'.$model::slug();
	}

	//returns string url to add new item to model
	static function addLinkFor(string $model): string{
		return self::indexLinkFor($model).'/'.self::addVerb();
	}

	//return string url to edit an item
	static function editLinkFor(string $model, int $itemId): string{
		return self::indexLinkFor($model).'/'.self::editVerb().'/'.$itemId;
	}
}

Add constants to url helper for add and edit actions