<?php
/*
Plugin Name: Lists in a Shortcode
Description: MU Plugin that lets you get lists of posts, pages and sites in a network
Author: Jude Rosario
Author URI: http://premium.wpmudev.org/
Version: 1.1
*/

?>

<?php
/*
Plugin Name: Lists in a Shortcode
Description: MU Plugin that lets you get lists of posts, pages and sites in a network
Author: Jude Rosario
Author URI: http://premium.wpmudev.org/
Version: 1.1
*/

add_shortcode( 'list-posts', 'post_listing_shortcode' );

function post_listing_shortcode( $atts ) {

    extract( shortcode_atts( array (
        'type' => 'post',
        'order' => 'date',
        'orderby' => 'title',
        'posts_per_page' => -1,
        'category' => '',
        'post_status' => 'published',
    ), $atts ) );

    $options = array(
        'post_type' => $type,
        'order' => $order,
        'orderby' => $orderby,
        'posts_per_page' => $posts_per_page,
        'category_name' => $category,
        'post_status' => $post_status,
    );

    $query = new WP_Query( $options );

    ob_start();
    if ( $query->have_posts() ) { ?>

            <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

            <?php endwhile;
            wp_reset_postdata(); ?>

 <?php
    }
    ob_end_flush();
}

?>

Add function to list posts

Add function to list posts


<?php

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

class CreateAttendanceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attendance', function (Blueprint $table) {
            $table->increments('id');
            $table->string('attendable_type');
            $table->unsignedInteger('attendable_id');
            $table->integer('gtid')->length(9)->nullable();
            $table->string('source');
            $table->unsignedInteger('recorded_by')->nullable();
            $table->timestamps();

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

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

<?php

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

class CreateAttendanceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attendance', function (Blueprint $table) {
            $table->increments('id');
            $table->string('attendable_type');
            $table->unsignedInteger('attendable_id');
            $table->integer('gtid')->length(9)->nullable();
            $table->string('source')->nullable();
            $table->unsignedInteger('recorded_by')->nullable();
            $table->timestamps();
            $table->softDeletes();

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

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

Make source nullable; Add soft deletes

Make source nullable; Add soft deletes


<?php

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

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

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

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

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

<?php

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

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

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

Delete ip security (distant server)

Delete ip security (distant server)


<?php

namespace Rogue\Models;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['eventable_id', 'eventable_type', 'content', 'user'];

    /**
     * Attributes that can be queried when filtering.
     *
     * This array is manually maintained. It does not necessarily mean that
     * any of these are actual indexes on the database... but they should be!
     *
     * @var array
     */
    public static $indexes = [
        'eventable_id',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'content' => 'array',
    ];

    public function eventable()
    {
        return $this->morphTo();
    }

    public function scopeForSignup($query, $id)
    {
        return $query->where('eventable_type', 'Rogue\Models\Signup')
                     ->where('eventable_id', $id);
    }
}

<?php

namespace Rogue\Models;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['content', 'user'];

    /**
     * Attributes that can be queried when filtering.
     *
     * This array is manually maintained. It does not necessarily mean that
     * any of these are actual indexes on the database... but they should be!
     *
     * @var array
     */
    public static $indexes = [
        'eventable_id',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'content' => 'array',
    ];

    public function eventable()
    {
        return $this->morphTo();
    }

    public function scopeForSignup($query, $id)
    {
        return $query->where('eventable_type', 'Rogue\Models\Signup')
                     ->where('eventable_id', $id);
    }
}

Remove event attributes that should not be fillable.


<?php
namespace Imbo\EventListener\AccessToken;

use Imbo\EventListener\AccessToken\AccessTokenGenerator,
    Imbo\EventListener\AccessToken\SHA256;

class MultipleAccessTokenGenerators extends AccessTokenGenerator {
    /**
     * The params array for this generator allows you to define a set of access token signature generators to be used
     * for different url parameters if present. Each will be tried in the sequence defined.
     *
     * 'generators' => [
     *     'accessToken' => new SHA256(),
     *     'dummy' => new Dummy(),
     * ]
     *
     * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying
     * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token
     * validation schemes while keeping backwards compatible signature algorithms valid.
     *
     * @param array $params Parameters to the MultipleAccessTokenGenerators.
     */
    public function __construct(array $params = []) {
        if (!isset($params['generators'])) {
            $params['generators'] = [];
        }

        parent::__construct($params);
    }

    public function generateSignature($argumentKey, $data, $privateKey) {
        return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey);
    }

    public function getArgumentKeys() {
        return array_keys($this->params['generators']);
    }
}

<?php
namespace Imbo\EventListener\AccessToken;

use Imbo\EventListener\AccessToken\AccessTokenGenerator,
    Imbo\EventListener\AccessToken\SHA256;
use Imbo\Exception\RuntimeException;

class MultipleAccessTokenGenerators extends AccessTokenGenerator {
    /**
     * The params array for this generator allows you to define a set of access token signature generators to be used
     * for different url parameters if present. Each will be tried in the sequence defined.
     *
     * 'generators' => [
     *     'accessToken' => new SHA256(),
     *     'dummy' => new Dummy(),
     * ]
     *
     * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying
     * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token
     * validation schemes while keeping backwards compatible signature algorithms valid.
     *
     * @param array $params Parameters to the MultipleAccessTokenGenerators.
     */
    public function __construct(array $params = []) {
        if (!isset($params['generators']) || !is_array($params['generators'])) {
            $params['generators'] = [];
        } else {
            foreach ($params['generators'] as $generator) {
                if (!$generator instanceof AccessTokenInterface) {
                    throw new RuntimeException('AccessTokenGenerators must implement AccessTokenInterface');
                }
            }
        }

        parent::__construct($params);
    }

    public function generateSignature($argumentKey, $data, $privateKey) {
        return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey);
    }

    public function getArgumentKeys() {
        return array_keys($this->params['generators']);
    }
}

Throw exception of generator doesn't implement AccessTokenInterface


<?php

namespace Mockery\Generator;

class DefinedTargetClass
{
    private $rfc;

    public function __construct(\ReflectionClass $rfc)
    {
        $this->rfc = $rfc;
    }

    public static function factory($name)
    {
        return new static(new \ReflectionClass($name));
    }

    public function getName()
    {
        return $this->rfc->getName();
    }

    public function isAbstract()
    {
        return $this->rfc->isAbstract();
    }

    public function isFinal()
    {
        return $this->rfc->isFinal();
    }

    public function getMethods()
    {
        return array_map(function ($method) {
            return new Method($method);
        }, $this->rfc->getMethods());
    }

    public function getInterfaces()
    {
        return array_map(function ($interface) {
            return new static($interface);
        }, $this->rfc->getInterfaces());
    }

    public function __toString()
    {
        return $this->getName();
    }

    public function getNamespaceName()
    {
        return $this->rfc->getNamespaceName();
    }

    public function inNamespace()
    {
        return $this->rfc->inNamespace();
    }

    public function getShortName()
    {
        return $this->rfc->getShortName();
    }
}

<?php

namespace Mockery\Generator;

class DefinedTargetClass
{
    private $rfc;

    public function __construct(\ReflectionClass $rfc)
    {
        $this->rfc = $rfc;
    }

    public static function factory($name)
    {
        return new self(new \ReflectionClass($name));
    }

    public function getName()
    {
        return $this->rfc->getName();
    }

    public function isAbstract()
    {
        return $this->rfc->isAbstract();
    }

    public function isFinal()
    {
        return $this->rfc->isFinal();
    }

    public function getMethods()
    {
        return array_map(function ($method) {
            return new Method($method);
        }, $this->rfc->getMethods());
    }

    public function getInterfaces()
    {
        return array_map(function ($interface) {
            return new self($interface);
        }, $this->rfc->getInterfaces());
    }

    public function __toString()
    {
        return $this->getName();
    }

    public function getNamespaceName()
    {
        return $this->rfc->getNamespaceName();
    }

    public function inNamespace()
    {
        return $this->rfc->inNamespace();
    }

    public function getShortName()
    {
        return $this->rfc->getShortName();
    }
}

Use self for php 5.3

Use self for php 5.3


<?php
/**
 * @see https://developers.podio.com/doc/users
 */
class PodioUserStatus extends PodioObject {
  public function __construct($attributes = array()) {
    $this->property('properties', 'hash');
    $this->property('inbox_new', 'integer');
    $this->property('calendar_code', 'string');
    $this->property('task_mail', 'string');
    $this->property('mailbox', 'string');

    $this->has_one('user', 'User');
    $this->has_one('profile', 'Contact');

    $this->init($attributes);
  }

  /**
   * @see https://developers.podio.com/doc/users/get-user-status-22480
   */
  public static function get() {
    return self::member(Podio::get("/user/status"));
  }

}

<?php
/**
 * @see https://developers.podio.com/doc/users
 */
class PodioUserStatus extends PodioObject {
  public function __construct($attributes = array()) {
    // Removed for now since the name clashes with an
    // internal variable.
    // $this->property('properties', 'hash');
    $this->property('inbox_new', 'integer');
    $this->property('calendar_code', 'string');
    $this->property('task_mail', 'string');
    $this->property('mailbox', 'string');

    $this->has_one('user', 'User');
    $this->has_one('profile', 'Contact');

    $this->init($attributes);
  }

  /**
   * @see https://developers.podio.com/doc/users/get-user-status-22480
   */
  public static function get() {
    return self::member(Podio::get("/user/status"));
  }

}

Remove 'properties' from UserStatus temporarily due to naming conflict.


<?php

namespace App\Providers;

use App\Services\CsvGenerator;
use App\Services\Response;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            \App\Solvers\SolverInterface::class,
            \App\Solvers\HatSolver::class
        );
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

<?php

namespace App\Providers;

use App\Services\CsvGenerator;
use App\Services\Response;
use DrawCrypt;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;
use Queue;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            \App\Solvers\SolverInterface::class,
            \App\Solvers\HatSolver::class
        );
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Queue::createPayloadUsing(function ($connection, $queue, $payload) {
            return [
                'data' => array_merge($payload['data'], [
                    'iv' => base64_encode(DrawCrypt::getIV())
                ])
            ];
        });

        $this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) {
            if (isset($event->job->payload()['data']['iv'])) {
                DrawCrypt::setIV(base64_decode($event->job->payload()['data']['iv']));
            }
        });
    }
}

Add iv in job data when queueing

Add iv in job data when queueing


<?php

namespace Flint\Config\Normalizer;

use Pimple;

/**
 * @package Flint
 */
class PimpleAwareNormalizer extends \Flint\PimpleAware implements NormalizerInterface
{
    const PLACEHOLDER = '{%%|%([a-z0-9_.]+)%}';

    /**
     * @param Pimple $pimple
     */
    public function __construct(Pimple $pimple = null)
    {
        $this->setPimple($pimple);
    }

    /**
     * @param  string $contents
     * @return string
     */
    public function normalize($contents)
    {
        return preg_replace_callback(static::PLACEHOLDER, array($this, 'callback'), $contents);
    }

    /**
     * @param  array $matches
     * @return mixed
     */
    protected function callback($matches)
    {
        if (!isset($matches[1])) {
            return '%%';
        }

        return $this->scarlarToString($this->pimple[$matches[1]]);
    }

    /**
     * @param  mixed $value
     * @return mixed
     */
    protected function scarlarToString($value)
    {
        switch (gettype($value)) {
            case 'resource':
            case 'object':
                throw new \RuntimeException('Unable to replace placeholder if its replacement is an object or resource.');
            case 'boolean':
                return $value ? 'true' : 'false';
            case 'NULL':
                return 'null';
            default:
                return (string) $value;
        }
    }
}

<?php

namespace Flint\Config\Normalizer;

use Pimple;

/**
 * @package Flint
 */
class PimpleAwareNormalizer extends \Flint\PimpleAware implements NormalizerInterface
{
    const PLACEHOLDER = '{%%|%([a-z0-9_.]+)%}';

    /**
     * @param Pimple $pimple
     */
    public function __construct(Pimple $pimple = null)
    {
        $this->setPimple($pimple);
    }

    /**
     * @param  string $contents
     * @return string
     */
    public function normalize($contents)
    {
        return preg_replace_callback(static::PLACEHOLDER, array($this, 'callback'), $contents);
    }

    /**
     * @param  array $matches
     * @return mixed
     */
    protected function callback($matches)
    {
        if (!isset($matches[1])) {
            return '%%';
        }

        return $this->scalarToString($this->pimple[$matches[1]]);
    }

    /**
     * @param  mixed $value
     * @return mixed
     */
    protected function scalarToString($value)
    {
        switch (gettype($value)) {
            case 'resource':
            case 'object':
                throw new \RuntimeException('Unable to replace placeholder if its replacement is an object or resource.');
            case 'boolean':
                return $value ? 'true' : 'false';
            case 'NULL':
                return 'null';
            default:
                return (string) $value;
        }
    }
}

Fix typo in `scarlarToString` method name.

This is a protected function and is not called anywhere else but this class, so this is safe to rename.


<?php
return [
    'csv' => [
        'delimiter' => ';',
        'enclosure' => '"',
        'escape' => '\\',
        'single_item' => false,
        'first_row_as_keys' => false,
        'keys' => [],
    ],
    'date.backend' => 'Y-m-d',
    'date.frontend' => 'Y-m-d',
    'date.view' => 'd.m.Y',
    'datetime.backend' => 'Y-m-d H:i:s',
    'datetime.frontend' => 'Y-m-d\TH:i',
    'datetime.view' => 'd.m.Y H:i',
    'i18n.charset' => 'utf-8',
    'i18n.lang' => 'de',
    'i18n.locale' => 'de-DE',
    'i18n.timezone' => 'Europe/Berlin',
    'import.end' => '<!-- IMPORT_END -->',
    'import.start' => '<!-- IMPORT_START -->',
    'import.toc' => 'import.csv',
    'limit.admin' => 20,
    'limit.index' => 20,
    'limit.pager' => 5,
    'page.url' => '.html',
    'privilege' => '_all_',
    'project' => 1,
    'theme' => 'base',
    'time.backend' => 'H:i:s',
    'time.frontend' => 'H:i',
    'time.view' => 'H:i',
];

<?php
return [
    'csv' => [
        'delimiter' => ';',
        'enclosure' => '"',
        'escape' => '\\',
        'single_item' => false,
        'first_row_as_keys' => false,
        'keys' => [],
    ],
    'date.backend' => 'Y-m-d',
    'date.frontend' => 'Y-m-d',
    'date.view' => 'd.m.Y',
    'datetime.backend' => 'Y-m-d H:i:s',
    'datetime.frontend' => 'Y-m-d\TH:i',
    'datetime.view' => 'd.m.Y H:i',
    'i18n.charset' => 'utf-8',
    'i18n.lang' => 'de',
    'i18n.locale' => 'de-DE',
    'i18n.timezone' => 'Europe/Berlin',
    'import.end' => '<!-- IMPORT_END -->',
    'import.start' => '<!-- IMPORT_START -->',
    'import.toc' => 'toc.txt',
    'limit.admin' => 20,
    'limit.index' => 20,
    'limit.pager' => 5,
    'page.url' => '.html',
    'privilege' => '_all_',
    'project' => 1,
    'theme' => 'base',
    'time.backend' => 'H:i:s',
    'time.frontend' => 'H:i',
    'time.view' => 'H:i',
];

Use old import toc name to avoid migration problems


<?php namespace GeneaLabs\Bones\Keeper;

use Illuminate\Support\ServiceProvider;

class BonesKeeperServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        if (! $this->app->routesAreCached()) {
            require __DIR__ . '/../../../routes.php';
        }

        $this->publishes([__DIR__ . '/../../../config/config.php' => config_path('/genealabs/bones-keeper.php')], 'genealabs-bones-keeper');
        $this->publishes([
            __DIR__ . '/../../../../public' => public_path('genealabs/bones-keeper')], 'genealabs-bones-keeper');
        $this->loadViewsFrom(__DIR__.'/../../../views', 'genealabs-bones-keeper');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }

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

<?php namespace GeneaLabs\Bones\Keeper;

use Illuminate\Support\ServiceProvider;

class BonesKeeperServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        if (! $this->app->routesAreCached()) {
            require __DIR__ . '/../../../routes.php';
        }

        $this->publishes([__DIR__ . '/../../../config/config.php' => config_path('/genealabs/bones-keeper.php')], 'genealabs-bones-keeper');
        $this->publishes([__DIR__ . '/../../../../public' => public_path('genealabs/bones-keeper')], 'genealabs-bones-keeper');
        $this->loadViewsFrom(__DIR__.'/../../../views', 'genealabs-bones-keeper');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }

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

Fix public asset publish location

Fix public asset publish location


<?php

class EchoExecuteFirstArgumentStub implements PHPUnit_Framework_MockObject_Stub {
	public function invoke( PHPUnit_Framework_MockObject_Invocation $invocation ) {
		if ( !$invocation instanceof PHPUnit_Framework_MockObject_Invocation_Static ) {
			throw new PHPUnit_Framework_Exception( 'wrong invocation type' );
		}
		if ( !$invocation->arguments ) {
			throw new PHPUnit_Framework_Exception( 'Method call must have an argument' );
		}

		return call_user_func( reset( $invocation->arguments ) );
	}

	public function toString() {
		return 'return result of call_user_func on first invocation argument';
	}
}

<?php

use PHPUnit\Framework\MockObject\Invocation;
use PHPUnit\Framework\MockObject\Invocation\StaticInvocation;
use PHPUnit\Framework\MockObject\Stub;

class EchoExecuteFirstArgumentStub implements Stub {
	public function invoke( Invocation $invocation ) {
		if ( !$invocation instanceof StaticInvocation ) {
			throw new PHPUnit\Framework\Exception( 'wrong invocation type' );
		}
		if ( !$invocation->arguments ) {
			throw new PHPUnit\Framework\Exception( 'Method call must have an argument' );
		}

		return call_user_func( reset( $invocation->arguments ) );
	}

	public function toString() {
		return 'return result of call_user_func on first invocation argument';
	}
}

Use PHPUnit 6 class names

Use PHPUnit 6 class names

Bug: T192167
Change-Id: Id309ad5933371dd835ec431ded80f650e228099c


<?php

declare(strict_types=1);

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version21000Date20201120141228 extends SimpleMigrationStep {
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		if ($schema->hasTable('dav_job_status')) {
			$schema->dropTable('dav_job_status');
		}

		if ($schema->hasTable('systemtag')) {
			$table = $schema->getTable('systemtag');
			if ($table->hasColumn('systemtag')) {
				$table->dropColumn('assignable');
			}
		}

		if ($schema->hasTable('share')) {
			$table = $schema->getTable('share');
			if ($table->hasColumn('attributes')) {
				$table->dropColumn('attributes');
			}
		}

		return $schema;
	}
}

<?php

declare(strict_types=1);

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version21000Date20201120141228 extends SimpleMigrationStep {
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		if ($schema->hasTable('authtoken')) {
			$table = $schema->getTable('authtoken');
			$loginNameColumn = $table->getColumn('login_name');
			if ($loginNameColumn->getLength() !== 255) {
				$loginNameColumn->setLength(255);
			}
		}

		if ($schema->hasTable('dav_job_status')) {
			$schema->dropTable('dav_job_status');
		}

		if ($schema->hasTable('systemtag')) {
			$table = $schema->getTable('systemtag');
			if ($table->hasColumn('systemtag')) {
				$table->dropColumn('assignable');
			}
		}

		if ($schema->hasTable('share')) {
			$table = $schema->getTable('share');
			if ($table->hasColumn('attributes')) {
				$table->dropColumn('attributes');
			}
		}

		return $schema;
	}
}

Move authtoken login_name column to varchar(255)

Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>


<?php

require_once ('Base.php');

/**
 * Paymill API wrapper for transactions resource
 */
class Services_Paymill_Preauthorizations extends Services_Paymill_Transactions
{
    /**
     * {@inheritDoc}
     */
    protected $_serviceResource = 'preauthorizations/';

    /**
     * General REST PUT verb
     * Update resource item
     *
     * @param array $itemData
     *
     * @return array item updated or null
     */
    public function update(array $itemData = array())
    {
        throw new Services_Paymill_Exception( __CLASS__ . " does not support " . __METHOD__, "404");
    }

    /**
     * General REST DELETE verb
     * Delete or inactivate/cancel resource item
     *
     * @param string $clientId
     *
     * @return array item deleted
     */
    public function delete($clientId = null)
    {
        throw new Services_Paymill_Exception( __CLASS__ . " does not support " . __METHOD__, "404");
    }
}

<?php

require_once ('Base.php');

/**
 * Paymill API wrapper for transactions resource
 */
class Services_Paymill_Preauthorizations extends Services_Paymill_Transactions
{
    /**
     * {@inheritDoc}
     */
    protected $_serviceResource = 'preauthorizations/';
}

Remove duplicate methods from preauth service


<?php

use Slim\Http\Request;
use Slim\Http\Response;

// Routes

$app->get('/', function (Request $request, Response $response, $args) {
    // Render response
    return $response->write("Hello!");
});

$app->post('/invoice/new', function(Request $request, Response $response, $args) {
    // Retrieve our JSON payload as a PHP array.
    $payload = $request->getParsedBody();

    var_dump($payload);
})->add(function(Request $request, Response $response, $next) {
    // Only continue if our payload is JSON from Zapier.
    if ( $request->getMediaType() == 'application/json' && $request->getHeader('User-Agent')[0] == 'Zapier' ) {
        $response = $next($request, $response);

        return $response;
    }

    // Error out, because our payload is invalid.
    return $response
        ->withStatus(400, "Data must be JSON from Zapier.");
});

<?php

use Slim\Http\Request;
use Slim\Http\Response;

// Routes

$app->get('/', function (Request $request, Response $response, $args) {
    // Render response
    return $response->write("Hello!");
});

$app->post('/invoice/new', function(Request $request, Response $response, $args) {

})->add(function(Request $request, Response $response, $next) {
    // Only continue if our payload is JSON from Zapier.
    if ( $request->getMediaType() == 'application/json' && $request->getHeader('User-Agent')[0] == 'Zapier' ) {
        $response = $next($request, $response);

        return $response;
    }

    // Error out, because our payload is invalid.
    return $response
        ->withStatus(400, "Data must be JSON from Zapier.");
})->add(function(Request $request, Response $response, $next) {
    // Retrieve our JSON payload as a PHP array.
    $payload = $request->getParsedBody();

    if (isset($payload['recurring_invoice_id'])) {
        $response = $next($request, $response);

        return $response;
    }

    return $response
        ->withStatus(200, "Invoice not a recurring one.");
});

Add middleware to check whether or not it's a recurring invoice


<?php
/**
 * Mockery
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://github.com/padraic/mockery/blob/master/LICENSE
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to padraic@php.net so we can send you a copy immediately.
 *
 * @category   Mockery
 * @package    Mockery
 * @copyright  Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
 * @license    http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
 */

namespace Mockery\Matcher;

class AnyOf extends MatcherAbstract
{
    /**
     * Check if the actual value does not match the expected (in this
     * case it's specifically NOT expected).
     *
     * @param mixed $actual
     * @return bool
     */
    public function match(&$actual)
    {
        foreach ($this->_expected as $exp) {
            if ($actual === $exp) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return a string representation of this Matcher
     *
     * @return string
     */
    public function __toString()
    {
        return '<AnyOf>';
    }
}

<?php
/**
 * Mockery
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://github.com/padraic/mockery/blob/master/LICENSE
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to padraic@php.net so we can send you a copy immediately.
 *
 * @category   Mockery
 * @package    Mockery
 * @copyright  Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
 * @license    http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
 */

namespace Mockery\Matcher;

class AnyOf extends MatcherAbstract
{
    /**
     * Check if the actual value does not match the expected (in this
     * case it's specifically NOT expected).
     *
     * @param mixed $actual
     * @return bool
     */
    public function match(&$actual)
    {
        return in_array($actual, $this->_expected, true);
    }

    /**
     * Return a string representation of this Matcher
     *
     * @return string
     */
    public function __toString()
    {
        return '<AnyOf>';
    }
}

Simplify foreach with in_array function

Simplify foreach with in_array function


<?php

namespace Igniter\Flame\Foundation\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

<?php

namespace Igniter\Flame\Foundation\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     *
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function handle($request, Closure $next)
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->inExceptArray($request) ||
            $this->tokensMatch($request)
        ) {
            return tap($next($request), function ($response) use ($request) {
                if ($this->shouldAddXsrfTokenCookie()) {
                    $this->addCookieToResponse($request, $response);
                }
            });
        }

        throw new TokenMismatchException('CSRF token mismatch, please reload the page and try again.');
    }
}

Update CSRF token mismatch error message


<?php

namespace CultuurNet\UDB3\ReadModel;

use CultuurNet\UDB3\Language;

trait MultilingualJsonLDProjectorTrait
{
    /**
     * @param \stdClass $jsonLd
     * @param Language $language
     * @return \stdClass
     */
    protected function setMainLanguage(\stdClass $jsonLd, Language $language)
    {
        $jsonLd->mainLanguage = $language->getCode();
        return $jsonLd;
    }
}

<?php

namespace CultuurNet\UDB3\ReadModel;

use CultuurNet\UDB3\Language;

trait MultilingualJsonLDProjectorTrait
{
    /**
     * @param \stdClass $jsonLd
     * @param Language $language
     * @return \stdClass
     */
    protected function setMainLanguage(\stdClass $jsonLd, Language $language)
    {
        $jsonLd->mainLanguage = $language->getCode();
        return $jsonLd;
    }

    /**
     * @param \stdClass $jsonLd
     * @return Language
     */
    protected function getMainLanguage(\stdClass $jsonLd)
    {
        if (isset($jsonLd->mainLanguage)) {
            return new Language($jsonLd->mainLanguage);
        } else {
            return new Language('nl');
        }
    }
}

III-2159: Add method to read mainLanguage from JSON-LD in projectors


<?php
/**
 * @codingStandardsIgnoreStart
 *
 * @author       Barney Hanlon <barney@shrikeh.net>
 * @copyright    Barney Hanlon 2017
 * @license      https://opensource.org/licenses/MIT
 *
 * @codingStandardsIgnoreEnd
 */

namespace Shrikeh\GuzzleMiddleware\TimerLogger\Formatter\Traits;

use Exception;

/**
 * Trait FormatterStartExceptionTrait.
 */
trait FormatterExceptionTrait
{
    /**
     * @param \Exception|null $e An optional previous Exception
     *
     * @return static
     */
    public static function msg(
        Exception $e = null
    ) {
        return new static(
            static::MSG_MESSAGE,
            static::MSG_CODE,
            $e
        );
    }

    /**
     * @param \Exception|null $e An optional previous Exception
     *
     * @return static
     */
    public static function level(
        Exception $e = null
    ) {
        return new static(
            static::LEVEL_MESSAGE,
            static::LEVEL_CODE,
            $e
        );
    }
}

<?php
/**
 * @codingStandardsIgnoreStart
 *
 * @author       Barney Hanlon <barney@shrikeh.net>
 * @copyright    Barney Hanlon 2017
 * @license      https://opensource.org/licenses/MIT
 *
 * @codingStandardsIgnoreEnd
 */

namespace Shrikeh\GuzzleMiddleware\TimerLogger\Formatter\Traits;

use Exception;

/**
 * Trait FormatterStartExceptionTrait.
 */
trait FormatterExceptionTrait
{
    /**
     * @param \Exception|null $e An optional previous Exception
     *
     * @return static
     */
    public static function msg(
        Exception $e = null
    ) {
        return new static(
            self::MSG_MESSAGE,
            self::MSG_CODE,
            $e
        );
    }

    /**
     * @param \Exception|null $e An optional previous Exception
     *
     * @return static
     */
    public static function level(
        Exception $e = null
    ) {
        return new static(
            self::LEVEL_MESSAGE,
            self::LEVEL_CODE,
            $e
        );
    }
}

Move to self over static

Move to self over static


<?php

declare(strict_types=1);

namespace App\Sync\Task;

use App\Doctrine\ReloadableEntityManagerInterface;
use App\Entity\Repository\SettingsRepository;
use App\Radio\Adapters;
use App\Radio\CertificateLocator;
use Psr\Log\LoggerInterface;

class ReloadFrontendAfterSslChangeTask extends AbstractTask
{
    public function __construct(
        protected Adapters $adapters,
        protected SettingsRepository $settingsRepo,
        ReloadableEntityManagerInterface $em,
        LoggerInterface $logger
    ) {
        parent::__construct($em, $logger);
    }

    public function run(bool $force = false): void
    {
        $threshold = $this->settingsRepo->readSettings()->getSyncLongLastRun();

        $certs = CertificateLocator::findCertificate();

        $pathsToCheck = [
            $certs->getCertPath(),
            $certs->getKeyPath(),
        ];

        $certsUpdated = false;
        foreach ($pathsToCheck as $path) {
            if (filemtime($path) > $threshold) {
                $certsUpdated = true;
                break;
            }
        }

        if ($certsUpdated) {
            $this->logger->info('SSL certificates have updated; hot-reloading stations that support it.');

            foreach ($this->iterateStations() as $station) {
                $frontend = $this->adapters->getFrontendAdapter($station);
                if ($frontend->supportsReload()) {
                    $frontend->reload($station);
                }
            }
        } else {
            $this->logger->info('SSL certificates have not updated.');
        }
    }
}

<?php

declare(strict_types=1);

namespace App\Sync\Task;

use App\Doctrine\ReloadableEntityManagerInterface;
use App\Entity\Repository\SettingsRepository;
use App\Radio\Adapters;
use App\Radio\CertificateLocator;
use Psr\Log\LoggerInterface;

class ReloadFrontendAfterSslChangeTask extends AbstractTask
{
    public function __construct(
        protected Adapters $adapters,
        protected SettingsRepository $settingsRepo,
        ReloadableEntityManagerInterface $em,
        LoggerInterface $logger
    ) {
        parent::__construct($em, $logger);
    }

    public function run(bool $force = false): void
    {
        $threshold = $this->settingsRepo->readSettings()->getSyncLongLastRun();

        $certs = CertificateLocator::findCertificate();

        $pathsToCheck = [
            $certs->getCertPath(),
            $certs->getKeyPath(),
        ];

        $certsUpdated = false;
        foreach ($pathsToCheck as $path) {
            if (file_exists($path) && filemtime($path) > $threshold) {
                $certsUpdated = true;
                break;
            }
        }

        if ($certsUpdated) {
            $this->logger->info('SSL certificates have updated; hot-reloading stations that support it.');

            foreach ($this->iterateStations() as $station) {
                $frontend = $this->adapters->getFrontendAdapter($station);
                if ($frontend->supportsReload()) {
                    $frontend->reload($station);
                }
            }
        } else {
            $this->logger->info('SSL certificates have not updated.');
        }
    }
}

Add "file_exists" check for the CI.

Add "file_exists" check for the CI.


<?php get_header(); ?>

    <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

            <?php the_time('l j F  Y') ?>

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

                <?php the_title(); ?>

<?php comments_number(__('No Comments'), '1 ' . __('Comment'), '% ' . __('Comments')); ?>

                <?php the_content(); ?>

            <?=__('Tags')?>:
            <?php foreach (get_the_tags() as $tag) { ?>
                <a href="<?=get_term_link($tag->term_id)?>" class="post-tag"><?=$tag->name?>
            <?php } ?>

    <?php comments_template(); ?>
    <?php endwhile; ?>

<?php get_footer(); ?>

<?php get_header(); ?>

    <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

            <?php the_time('l j F  Y') ?>

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

                <?php the_title(); ?>

<?php comments_number(__('No Comments'), '1 ' . __('Comment'), '% ' . __('Comments')); ?>

                <?php the_content(); ?>

            <?php if (get_the_tags()) {?>
                <?=__('Tags')?>:
                <?php foreach (get_the_tags() as $tag) { ?>
                    <a href="<?=get_term_link($tag->term_id)?>" class="post-tag"><?=$tag->name?>
                <?php } ?>
            <?php } ?>

    <?php comments_template(); ?>
    <?php endwhile; ?>

<?php get_footer(); ?>

Fix error when there's no tags

Fix error when there's no tags


<?php
/**
 * Created by PhpStorm.
 * User: GeoMash
 * Date: 3/14/14
 * Time: 8:16 PM
 */

<?php
namespace application\nutsNBolts\controller\rest\collection
{
	use application\nutsNBolts\base\RestController;

	class Index extends RestController
	{
		public function init()
		{
			$this->bindPaths
			(
				array
				(
					''					=>'getAll',
					'{int}'				=>'getById'
				)
			);
		}

		/*
		 * sample request: $.getJSON('/rest/message/.json');
		 */
		public function getAll()
		{
			$this->respond
			(
				true,
				'OK',
				$this->model->Collection->read([])
			);
		}

		/*
		 * sample request: $.getJSON('/rest/message/1.json');
		 */
		public function getById()
		{
			$collectionId=$this->getFullRequestPart(2);
			if(isset($collectionId) && is_numeric($collectionId))
			{
				$collection=$this->model->Collection->read(['id'=>$collectionId]);
				if(count($collection))
				{
					$this->setResponseCode(200);
					$this->respond
					(
						true,
						'OK',
						$collection[0]
					);
				}
				else
				{
					// no message by that id
					$this->setResponseCode(404);
					$this->respond
					(
						true,
						'Not Found',
						'Collection not found'
					);
				}
			}
			else
			{
				$this->setResponseCode(404);
				$this->respond
				(
					false,
					'Expecting collection id to be integer.'
				);
			}
		}
	}
}
?>

Add collection to rest controller

Add collection to rest controller


<?php
namespace Rosewood;

use RedBean_Facade as R;

class Database
{
  function __construct()
  {
    $this->config = [];
    R::setup('mysql:host=localhost;dbname=rosewood-test',
      'root','123456'); //mysql
  }

  public function __call($function_name, $arguments)
  {
    call_user_func_array(__NAMESPACE__."R::$function_name", $arguments);
  }

  function __destruct()
  {
    R::close();
  }
}

<?php
namespace Rosewood;

use RedBean_Facade as R;

class Database
{
  function __construct($config = [])
  {
    $this->config = $config;
    if (!empty($this->config)) {
      R::setup($this->connectionString($this->config['host'], $this->config['db']), $this->config['user'], $this->config['pass']);
    }
  }

  public function __call($function_name, $arguments)
  {
    call_user_func_array(__NAMESPACE__."R::$function_name", $arguments);
  }

  function __destruct()
  {
    R::close();
  }

  protected function connectionString($host, $database)
  {
    return "mysql:host=$host;dbname=$database";
  }
}

Change hard coded db configuration

Change hard coded db configuration


<?php

namespace Deployer;

task('buffer:stop', function () {
    $releasesList = get('releases_list');
    // Remove lock files also from previous release because it can be still read by apache/nginx after switching.
    // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release
    // this is why $releasesList[0] have last release and not current.
    $overwriteReleases = ['current'];
    if (!empty($releasesList[0])) {
        $overwriteReleases[] = $releasesList[0];
    }
    foreach ($overwriteReleases as $overwriteRelease) {
        $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease;
        foreach (get('buffer_config') as $key => $buffer) {
            if (!isset($buffer['entrypoint_filename'])) {
                throw new \RuntimeException('entrypoint_filename not set for buffer_data');
            }
            $entrypointFilename = $buffer['entrypoint_filename'];
            if (isset($buffer['locker_filename'])) {
                $lockerFilename = $buffer['locker_filename'];
            } else {
                $lockerFilename = 'buffer.lock';
            }
            if (dirname($entrypointFilename) != '.') {
                $entrypointDirectory = dirname($entrypointFilename) . '/';
            } else {
                $entrypointDirectory = '';
            }
            run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename);
        }
    }
})->desc('Stop buffering reqests to application entrypoints.');

<?php

namespace Deployer;

task('buffer:stop', function () {
    $releasesList = get('releases_list');
    // Remove lock files also from previous release because it can be still read by apache/nginx after switching.
    // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release
    // this is why $releasesList[0] have last release and not current.
    $overwriteReleases = ['current'];
    if (isset($releasesList[0])) {
        $overwriteReleases[] = 'releases/' . $releasesList[0];
    }
    foreach ($overwriteReleases as $overwriteRelease) {
        $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease;
        foreach (get('buffer_config') as $key => $buffer) {
            if (!isset($buffer['entrypoint_filename'])) {
                throw new \RuntimeException('entrypoint_filename not set for buffer_data');
            }
            $entrypointFilename = $buffer['entrypoint_filename'];
            if (isset($buffer['locker_filename'])) {
                $lockerFilename = $buffer['locker_filename'];
            } else {
                $lockerFilename = 'buffer.lock';
            }
            if (dirname($entrypointFilename) != '.') {
                $entrypointDirectory = dirname($entrypointFilename) . '/';
            } else {
                $entrypointDirectory = '';
            }
            run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename);
        }
    }
})->desc('Stop buffering reqests to application entrypoints.');

[BUGFIX] Check for existance of $releasesList[0] before using


<?php

function collect_memory() {
    $memorystr = file_get_contents('/proc/meminfo');

    foreach ($memorystr as $key => $value) {
        // Remove spaces
    	$memory[$key] = trim($value);

        // Only get the value, not the label as well
        $memoryarray = explode(":", $memory[$key]);

        // Only get the raw value, without the kB suffix
        $memory[$key] = $memoryarray[0];

        // Return string contains the raw values separated by a comma
        $return = $return.",".$memory[$key];
    }

    return $return;
}

?>

<?php

function collect_memory() {
    $return = "";

    $memorystr = file_get_contents('/proc/meminfo');
    $memoryarr = explode("\n", $memorystr);

    foreach ($memoryarr as $key => $value) {
        // Remove spaces
    	$memory[$key] = trim($value);

        // Only get the value, not the label as well
        $memoryarray = explode(":", $memory[$key]);

        // Only get the raw value, without the kB suffix
        $memory[$key] = $memoryarray[0];

        // Return string contains the raw values separated by a comma
        $return = $return.",".$memory[$key];
    }

    return $return;
}

?>

Use array instead of string on the foreach


<?php

use Mockery as m;
use Illuminate\Support\Facades\Response;

class SupportFacadeResponseTest extends PHPUnit_Framework_TestCase {

	public function tearDown()
	{
		m::close();
	}

	public function testArrayifyDataBeforeSendingAsJson()
	{
		$data = m::mock('Illuminate\Support\Contracts\ArrayableInterface');
		$data->shouldReceive('toArray')->andReturn(array('foo' => 'bar'));

		$response = Response::json($data);
		$this->assertEquals('{"foo":"bar"}', $response->getContent());
	}

}

<?php

use Mockery as m;
use Illuminate\Support\Facades\Response;

class SupportFacadeResponseTest extends PHPUnit_Framework_TestCase {

	public function tearDown()
	{
		m::close();
	}

	public function testArrayableSendAsJson()
	{
		$data = m::mock('Illuminate\Support\Contracts\ArrayableInterface');
		$data->shouldReceive('toArray')->andReturn(array('foo' => 'bar'));

		$response = Response::json($data);
		$this->assertEquals('{"foo":"bar"}', $response->getContent());
	}

}

Make unit test name simpler

Make unit test name simpler


<?php

namespace LastCall\Crawler\Test\Helper;

use LastCall\Crawler\Helper\ProfilerHelper;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\Console\Style\OutputStyle;

class ProfilerHelperTest extends \PHPUnit_Framework_TestCase {

    public function testGetTraceableDispatcher() {
        $helper = new ProfilerHelper();
        $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher());
        $this->assertInstanceOf(TraceableEventDispatcher::class, $dispatcher);
    }

    public function testRenderProfile() {
        $helper = new ProfilerHelper();
        $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher());
        $dispatcher->dispatch('foo');

        $io = $this->prophesize(OutputStyle::class);
        $io->table(['Listener', 'Time'], [['foo', 0]])->shouldBeCalled();
        $helper->renderProfile($io->reveal());
    }
}

<?php

namespace LastCall\Crawler\Test\Helper;

use LastCall\Crawler\Helper\ProfilerHelper;
use Prophecy\Argument;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\Console\Style\OutputStyle;

class ProfilerHelperTest extends \PHPUnit_Framework_TestCase {

    public function testGetTraceableDispatcher() {
        $helper = new ProfilerHelper();
        $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher());
        $this->assertInstanceOf(TraceableEventDispatcher::class, $dispatcher);
    }

    public function testRenderProfile() {
        $helper = new ProfilerHelper();
        $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher());
        $dispatcher->dispatch('foo');

        $io = $this->prophesize(OutputStyle::class);
        $io->table(['Listener', 'Time'], Argument::that(function($rows) {
            return count($rows) === 1 && $rows[0][0] === 'foo' && is_numeric($rows[0][1]);
        }))->shouldBeCalled();
        $helper->renderProfile($io->reveal());
    }
}

Fix failing test on ProfilerHelper

Fix failing test on ProfilerHelper


<?php

function ex($object, $coords, $default = null)
{
    if (!is_array($object) and !is_object($object))
    {
        return $default;
    }

    $keys = explode('.', $coords);
    foreach ($keys as $key)
    {
        if (is_array($object))
        {
            if (isset($object[$key]))
            {
                $object = $object[$key];
            }
            else
            {
                return $default;
            }
        }
        elseif (is_object($object))
        {
            $test = $object->$key;
            if ($test)
            {
                $object = $test;
            }
            else
            {
                return $default;
            }
        }
        else
        {
            return $default;
        }
    }
    return $object ? $object : $default;
}

<?php

function ex($object, $coords, $default = null)
{
    if (!is_array($object) and !is_object($object))
    {
        return $default;
    }

    $keys = explode('.', $coords);
    foreach ($keys as $key)
    {
        if (is_array($object))
        {
            if (isset($object[$key]))
            {
                $object = $object[$key];
            }
            else
            {
                return $default;
            }
        }
        elseif (is_object($object))
        {
            if (isset($object->$key))
            {
                $object = $object->$key;
            }
            else
            {
                return $default;
            }
        }
        else
        {
            return $default;
        }
    }
    return $object ? $object : $default;
}

Fix issue on object crawling, again.

Fix issue on object crawling, again.


<?php

class GridRowsExtension extends DataExtension {

  /*
  If you are laying out using some form of grid, e.g. HTML table (ugh) or bootstraps span classes it is useful
  to have the DataSet split by row.  This is what this method does.

  To execute this code from a template, do something like the following:

  <% control SplitSetIntoGridRows(Children|4) %>
  YOur template here
  <% end_control %>

  */
  public function SplitDataListIntoGridRows($itemsInGridMethod,$numberOfCols) {
    $itemsInGrid = $this->owner->$itemsInGridMethod();
    $position = 1;
    $columns = new ArrayList();
    $result = new ArrayList();
    foreach ($itemsInGrid as $key => $item) {
      $columns->push($item);
      if (($position) >= $numberOfCols) {
        $position = 1;
        $row = new ArrayList();
        $row->Columns = $columns;
        $result->push($row);
        $columns = new ArrayList();
      } else {
        $position = $position + 1;
      }
    }

    if ($columns->Count() > 0) {
      $row = new ArrayList();
      $row->Columns = $columns;
      $result->push($row);
    }

    return $result;
  }

}

<?php

class GridRowsExtension extends DataExtension {

  /*
  If you are laying out using some form of grid, e.g. HTML table (ugh) or bootstraps span classes it is useful
  to have the DataList split by row.  Here the DataList is generated from a method accessible to the current cotnroller

  See README.md for a worked example

  */
  public function SplitDataListIntoGridRows($itemsInGridMethod,$numberOfCols) {
    $itemsInGrid = $this->owner->$itemsInGridMethod();
    return $this->createGrid($itemsInGrid,$numberOfCols);
  }

  /*
  If you are laying out using some form of grid, e.g. HTML table (ugh) or bootstraps span classes it is useful
  to have the DataList split by row.  This is what this method does.

  See README.md for a worked example

  */
  public function SplitClassNameDataListIntoGridRows($className,$numberOfCols,$limit,$sort='LastEdited DESC') {
    $clazz = Injector::inst()->create($className);
    $itemsInGrid = $clazz->get()->limit($limit)->sort($sort);
    return $this->createGrid($itemsInGrid,$numberOfCols);
  }

  /*
  The actual method that splits the DataList into an ArrayList of rows that contain an ArrayList of Columns
  */
  private function createGrid($itemsInGrid,$numberOfCols) {
    $position = 1;
    $columns = new ArrayList();
    $result = new ArrayList();
    foreach ($itemsInGrid as $key => $item) {
      $columns->push($item);
      if (($position) >= $numberOfCols) {
        $position = 1;
        $row = new ArrayList();
        $row->Columns = $columns;
        $result->push($row);
        $columns = new ArrayList();
      } else {
        $position = $position + 1;
      }
    }

    if ($columns->Count() > 0) {
      $row = new ArrayList();
      $row->Columns = $columns;
      $result->push($row);
    }

    return $result;
  }

}

ENHANCEMENT: Allow a grid of the latest items of one particular class type


<?php

use App\UserRegistrationRequest;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class RegisterTest extends TestCase
{
  use DatabaseMigrations;

  /**
   * A basic test example.
   */
  public function testExample()
  {
    $code       = new UserRegistrationRequest();
    $code->id   = 1234567;
    $code->code = 'XXXXX-XXXXX-XXXXX';
    $code->save();

    $this->visit('/register')
        ->type($code->id, 'id')
        ->type($code->code, 'code')
        ->type('Fox', 'first_name')
        ->type('Red', 'middle_name')
        ->type('Snow', 'last_name')
        ->type('snow_fox@gmail.com', 'email')
        ->type('fox123', 'password')
        ->type('fox123', 'password_confirmation')
        ->press('Register')
        ->seePageIs('/home');
  }
}

<?php

use App\UserRegistrationRequest;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class RegisterTest extends TestCase
{
  use DatabaseMigrations;

  /**
   * A basic test example.
   */
  public function testRegister()
  {
    $code       = new UserRegistrationRequest();
    $code->id   = 1234567;
    $code->code = 'XXXXX-XXXXX-XXXXX';
    $code->save();

    $this->visit('/register')
        ->type($code->id, 'id')
        ->type($code->code, 'code')
        ->type('Fox', 'first_name')
        ->type('Red', 'middle_name')
        ->type('Snow', 'last_name')
        ->type('snow_fox@gmail.com', 'email')
        ->type('fox123', 'password')
        ->type('fox123', 'password_confirmation')
        ->press('Register')
        ->seePageIs('/home');
  }
}

Rename method 'testExample' to 'testRegister'


<?php

declare(strict_types=1);

return [

    /*
    |--------------------------------------------------------------------------
    | Default Preset
    |--------------------------------------------------------------------------
    |
    | This option controls the default preset that will be used by PHP Insights
    | to make your code reliable, simple, and clean. However, you can always
    | adjust the `Metrics` and `Insights` below in this configuration file.
    |
    | Supported: "default", "laravel", "symfony"
    |
    */

    'preset' => 'symfony',

    /*
    |--------------------------------------------------------------------------
    | Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may adjust all the various `Insights` that will be used by PHP
    | Insights. You can either add, remove or configure `Insights`. Keep in
    | mind, that all added `Insights` must belong to a specific `Metric`.
    |
    */

    'add' => [
        //  ExampleMetric::class => [
        //      ExampleInsight::class,
        //  ]
    ],

    'remove' => [
        //  ExampleInsight::class,
        ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
        ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
    ],

    'config' => [
        //  ExampleInsight::class => [
        //      'key' => 'value',
        //  ],
    ],

];

<?php

declare(strict_types=1);

return [

    /*
    |--------------------------------------------------------------------------
    | Default Preset
    |--------------------------------------------------------------------------
    |
    | This option controls the default preset that will be used by PHP Insights
    | to make your code reliable, simple, and clean. However, you can always
    | adjust the `Metrics` and `Insights` below in this configuration file.
    |
    | Supported: "default", "laravel", "symfony"
    |
    */

    'preset' => 'symfony',

    /*
    |--------------------------------------------------------------------------
    | Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may adjust all the various `Insights` that will be used by PHP
    | Insights. You can either add, remove or configure `Insights`. Keep in
    | mind, that all added `Insights` must belong to a specific `Metric`.
    |
    */

    'add' => [
        //  ExampleMetric::class => [
        //      ExampleInsight::class,
        //  ]
    ],

    'remove' => [
        //  ExampleInsight::class,
        ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
        ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff::class,
        ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
    ],

    'config' => [
        //  ExampleInsight::class => [
        //      'key' => 'value',
        //  ],
    ],

];

Disable some PHP insights sniffs

tests: Disable some PHP insights sniffs


<?php

namespace Kenjis\TranslationTools\Modifier;

use Kenjis\TranslationTools\Document;
use Kenjis\TranslationTools\File;

class AddCopyright
{
    protected $targetLineRegExp;
    protected $copyright;

    public function __construct()
    {
        $this->targetLineRegExp = '!© Copyright 2014 - 20\d\d, British Columbia Institute of Technology\.!u';
        $this->copyright = '
Japanese Translation: CodeIgniter Users Group in Japan';
    }

    public function add(File $html)
    {
        $content = '';
        $check = false;

        $filename = preg_replace('/\.html\z/', '.rst', $html->getName());

        foreach ($html as $line) {
            if ($check) {
                if (! preg_match('/' . preg_quote($this->copyright, '/') . '/u', $line, $matches)) {
                    $line = rtrim($line) . $this->copyright . "\n";
                    echo 'Added Copyright link: ' . $html->getName() . PHP_EOL;
                }
                $check = false;
            }

            if (preg_match($this->targetLineRegExp, $line, $matches)) {
                $check = true;
            }

            $content .= $line;
        }

        return $content;
    }
}

<?php

namespace Kenjis\TranslationTools\Modifier;

use Kenjis\TranslationTools\Document;
use Kenjis\TranslationTools\File;

class AddCopyright
{
    protected $targetLineRegExp;
    protected $copyright;

    public function __construct()
    {
        $this->targetLineRegExp = '!© Copyright 2014 - 20\d\d, British Columbia Institute of Technology\.!u';
        $this->copyright = '
Japanese Translation: CodeIgniter Users Group in Japan（この日本語訳のライセンスは、LICENSE.md を参照してください）';
    }

    public function add(File $html)
    {
        $content = '';
        $check = false;

        $filename = preg_replace('/\.html\z/', '.rst', $html->getName());

        foreach ($html as $line) {
            if ($check) {
                if (! preg_match('/' . preg_quote($this->copyright, '/') . '/u', $line, $matches)) {
                    $line = rtrim($line) . $this->copyright . "\n";
                    echo 'Added Copyright link: ' . $html->getName() . PHP_EOL;
                }
                $check = false;
            }

            if (preg_match($this->targetLineRegExp, $line, $matches)) {
                $check = true;
            }

            $content .= $line;
        }

        return $content;
    }
}

Add notice about the license of the translation in the footer


<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);

    /**
     * Create new request
     *
     * @return RequestInterface
     */
    public function newRequest();
}

<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);

    /**
     * Create new request
     *
     * @return RequestInterface
     */
    public function newRequest();

    /**
     * Build query string as required for PSR 7 URI ->withQuery
     *
     * @return string
     */
    public function buildQuery();
}

Extend interface to require a method to create new requests


<?php

class SV_TrendingContentTags_XenForo_DataWriter_Tag extends XFCP_SV_TrendingContentTags_XenForo_DataWriter_Tag
{
    protected function _delete()
    {
        parent::_delete();

        $this->_getDb()->query('
            delete into xf_sv_tag_trending where tag_id = ?
        ', $this->get('tag_id'));
    }

    public function delete()
    {
        parent::delete();

        if ($cacheObject = XenForo_Application::getCache())
        {
            $cacheObject->remove(SV_TrendingContentTags_Globals::sv_trendingTag_cacheId);
        }
    }
}

<?php

class SV_TrendingContentTags_XenForo_DataWriter_Tag extends XFCP_SV_TrendingContentTags_XenForo_DataWriter_Tag
{
    protected function _delete()
    {
        parent::_delete();

        $this->_db->query('
            delete from xf_sv_tag_trending where tag_id = ?
        ', $this->get('tag_id'));
    }

    public function delete()
    {
        parent::delete();

        if ($cacheObject = XenForo_Application::getCache())
        {
            $cacheObject->remove(SV_TrendingContentTags_Globals::sv_trendingTag_cacheId);
        }
    }
}

Fix SQL when purging trending tag table

Fix SQL when purging trending tag table


<?php

class AMP_Options_Menu_Page {
	public function render() {
		echo '

Here is where the form would go if I actually had AMP options.

';
	}
}

<?php

class AMP_Options_Menu_Page {
	public function render() {
		?>

AMP Plugin Options

					This admin panel menu contains configuration options
					for the AMP Plugin.

		<?php
	}
}

Add very simple content to the AMP Options page; we must add a nice full page describing the options available


<?php

    /**
     * HTML Methods
     *
     * @author Edwin Dayot <edwin.dayot@sfr.fr>
     * @copyright 2014
     */

    /**
     * HTML Class
     */
    class HTML
    {

        /**
         * Link method
         *
         * @param string $link
         *
         * @return string Constructed URL
         */
        static function link($link)
        {
            return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/' . trim($link, '/');
        }

        static function getCurrentURL() {
            return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        }
    }

<?php

    /**
     * HTML Methods
     *
     * @author Edwin Dayot <edwin.dayot@sfr.fr>
     * @copyright 2014
     */

    /**
     * HTML Class
     */
    class HTML
    {

        /**
         * Link method
         *
         * @param string $link
         *
         * @return string Constructed URL
         */
        static function link($link)
        {
            $link = !empty($link) ? '/' . trim($link, '/') : '';
            $script_name = trim(dirname(dirname($_SERVER['SCRIPT_NAME']))) != '/' ? '/' . trim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/') : '';
            return $_SERVER['REQUEST_SCHEME'] . '://' . trim($_SERVER['SERVER_NAME'], '/') . $script_name . $link;
        }

        static function getCurrentURL() {
            return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        }
    }

Enable no subdir support for links

Enable no subdir support for links


<?php

namespace Rogue\Http\Controllers;

use Rogue\Models\Campaign;
use Illuminate\Http\Request;
use Rogue\Http\Transformers\CampaignTransformer;

class CampaignsController extends ApiController
{
    /**
     * @var Rogue\Http\Transformers\SignupTransformer;
     */
    protected $transformer;

    /**
     * Create a controller instance.
     *
     */
    public function __construct()
    {
        $this->transformer = new CampaignTransformer;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = $this->newQuery(Campaign::class);

        return $this->paginatedCollection($query, $request);
    }

    /**
     * Display the specified resource.
     *
     * @param  \Rogue\Models\Campaign  $campaign
     * @return \Illuminate\Http\Response
     */
    public function show(Campaign $campaign)
    {
        return $this->item($campaign);
    }
}

Add missing space between method and docblock.


<?php
namespace Concrete\Package\VividStore\Src\VividStore\Utilities;

use Controller;
use Core;
use User;
use Database;

defined('C5_EXECUTE') or die(_("Access Denied."));

class ProductFinder extends Controller
{

    public function getProductMatch()
    {
        $u = new User();
        if (!$u->isLoggedIn()) {
          echo "Access Denied";
          exit;
        }
        if(!$_POST['query']){
            echo "Access Denied";
            exit;
        } else {
            $query = $_POST['query'];
            $db = Database::get();
            $results = $db->query('SELECT * FROM VividStoreProduct WHERE pName LIKE "%'.$query.'%"');

            if($results){
            foreach($results as $result){ ?>

                <li data-product-id="<?=$result['pID']?>"><?=$result['pName']?>

            <?php } //for each
            } else { //if no results ?>

<?=t("I can't find a product by that name")?>

            <?php }
        }

    }

}

<?php
namespace Concrete\Package\VividStore\Src\VividStore\Utilities;

use Controller;
use Core;
use User;
use Database;

defined('C5_EXECUTE') or die(_("Access Denied."));

class ProductFinder extends Controller
{

    public function getProductMatch()
    {
        $u = new User();
        if (!$u->isLoggedIn()) {
          echo "Access Denied";
          exit;
        }
        if(!$_POST['query']){
            echo "Access Denied";
            exit;
        } else {
            $query = $_POST['query'];
            $db = Database::get();
            $results = $db->query('SELECT * FROM VividStoreProducts WHERE pName LIKE "%'.$query.'%"');

            if($results){
            foreach($results as $result){ ?>

                <li data-product-id="<?=$result['pID']?>"><?=$result['pName']?>

            <?php } //for each
            } else { //if no results ?>

<?=t("I can't find a product by that name")?>

            <?php }
        }

    }

}

Fix to Product block product lookup

Fix to Product block product lookup


<?php require_once('inc/header.php'); ?>

<?php
	$lti->requirevalid();
?>

Generate PDF

<button class="makepdf">Generate PDF</button>

Add basic generate PDF functionality

Add basic generate PDF functionality


<?php

namespace Oro\Bundle\SearchBundle\Event;

use Oro\Bundle\DataGridBundle\Datagrid\DatagridInterface;
use Oro\Bundle\SearchBundle\Extension\SearchQueryInterface;
use Symfony\Component\EventDispatcher\Event;

class SearchResultBefore extends Event
{
    const NAME = 'oro_datagrid.search_datasource.result.before';

    /**
     * @var DatagridInterface
     */
    protected $datagrid;

    /**
     * @var SearchQueryInterface
     */
    protected $query;

    /**
     * @param DatagridInterface    $datagrid
     * @param SearchQueryInterface $query
     */
    public function __construct(
        DatagridInterface $datagrid,
        SearchQueryInterface $query
    ) {
        $this->datagrid = $datagrid;
        $this->query    = $query;
    }

    /**
     * @return SearchQueryInterface
     */
    public function getQuery()
    {
        return $this->query;
    }
}

<?php

namespace Oro\Bundle\SearchBundle\Event;

use Symfony\Component\EventDispatcher\Event;

use Oro\Bundle\DataGridBundle\Datagrid\DatagridInterface;
use Oro\Bundle\SearchBundle\Extension\SearchQueryInterface;

class SearchResultBefore extends Event
{
    const NAME = 'oro_datagrid.search_datasource.result.before';

    /**
     * @var DatagridInterface
     */
    protected $datagrid;

    /**
     * @var SearchQueryInterface
     */
    protected $query;

    /**
     * @param DatagridInterface    $datagrid
     * @param SearchQueryInterface $query
     */
    public function __construct(
        DatagridInterface $datagrid,
        SearchQueryInterface $query
    ) {
        $this->datagrid = $datagrid;
        $this->query    = $query;
    }

    /**
     * @return SearchQueryInterface
     */
    public function getQuery()
    {
        return $this->query;
    }
}

BB-4056: Add or adjust implementation of the SKU filters from the grid. Both use StringFilter in the ORM version
- namespace fix


<?php

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

use App\Message;

class AddSeenToMessagesTable extends Migration
{
    public function up()
    {
         $this->schema->table('messages', function (Blueprint $table) {
            $table->boolean('seen')->default(false);
        });

        Message::query()->update(['seen' => true]);
    }

    public function down()
    {
        $this->schema->table('messages', function (Blueprint $table) {
            $table->dropColumn('seen');
        });
    }
}

<?php

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

use App\Message;

class AddSeenToMessagesTable extends Migration
{
    public function up()
    {
        $this->schema->table('messages', function (Blueprint $table) {
            $table->boolean('seen')->default(true);
        });

        $this->schema->table('messages', function (Blueprint $table) {
            $table->boolean('seen')->default(false)->change();
        });
    }

    public function down()
    {
        $this->schema->table('messages', function (Blueprint $table) {
            $table->dropColumn('seen');
        });
    }
}

Fix the latest seen migration, use the default parameter to init the whole seen column to true


<?php

namespace Amp;

final class CombinedCancellationToken implements CancellationToken
{
    private $tokens = [];

    private $nextId = "a";
    private $callbacks = [];
    private $exception;

    public function __construct(CancellationToken ...$tokens)
    {
        foreach ($tokens as $token) {
            $id = $token->subscribe(function ($exception) {
                $this->exception = $exception;

                $callbacks = $this->callbacks;
                $this->callbacks = [];

                foreach ($callbacks as $callback) {
                    asyncCall($callback, $this->exception);
                }
            });

            $this->tokens[] = [$token, $id];
        }
    }

    public function __destruct()
    {
        foreach ($this->tokens as [$token, $id]) {
            /** @var CancellationToken $token */
            $token->unsubscribe($id);
        }
    }

    /** @inheritdoc */
    public function subscribe(callable $callback): string
    {
        $id = $this->nextId++;

        if ($this->exception) {
            asyncCall($callback, $this->exception);
        } else {
            $this->callbacks[$id] = $callback;
        }

        return $id;
    }

    /** @inheritdoc */
    public function unsubscribe(string $id)
    {
        unset($this->callbacks[$id]);
    }

    /** @inheritdoc */
    public function isRequested(): bool
    {
        foreach ($this->tokens as [$token]) {
            if ($token->isRequested()) {
                return true;
            }
        }

        return false;
    }

    /** @inheritdoc */
    public function throwIfRequested()
    {
        foreach ($this->tokens as [$token]) {
            $token->throwIfRequested();
        }
    }
}

<?php

namespace Amp;

final class CombinedCancellationToken implements CancellationToken
{
    private $tokens = [];

    private $nextId = "a";
    private $callbacks = [];
    private $exception;

    public function __construct(CancellationToken ...$tokens)
    {
        foreach ($tokens as $token) {
            $id = $token->subscribe(function ($exception) {
                $this->exception = $exception;

                $callbacks = $this->callbacks;
                $this->callbacks = [];

                foreach ($callbacks as $callback) {
                    asyncCall($callback, $this->exception);
                }
            });

            $this->tokens[] = [$token, $id];
        }
    }

    public function __destruct()
    {
        foreach ($this->tokens as list($token, $id)) {
            /** @var CancellationToken $token */
            $token->unsubscribe($id);
        }
    }

    /** @inheritdoc */
    public function subscribe(callable $callback): string
    {
        $id = $this->nextId++;

        if ($this->exception) {
            asyncCall($callback, $this->exception);
        } else {
            $this->callbacks[$id] = $callback;
        }

        return $id;
    }

    /** @inheritdoc */
    public function unsubscribe(string $id)
    {
        unset($this->callbacks[$id]);
    }

    /** @inheritdoc */
    public function isRequested(): bool
    {
        foreach ($this->tokens as list($token)) {
            if ($token->isRequested()) {
                return true;
            }
        }

        return false;
    }

    /** @inheritdoc */
    public function throwIfRequested()
    {
        foreach ($this->tokens as list($token)) {
            $token->throwIfRequested();
        }
    }
}

Remove PHP 7.1 feature usage for 7.0 compat


<?php

class Denkmal_Component_EventPreview extends Denkmal_Component_Abstract {

    public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) {
        $event = $this->_params->getEvent('event');
        $venue = $this->_params->has('venue') ? $this->_params->getVenue('venue') : $event->getVenue();

        $settings = new Denkmal_App_Settings();
        $fromDate = $event->getFrom();
        $fromDateDisplay = clone $fromDate;
        $fromDateDisplay->sub(new DateInterval('PT' . $settings->getDayOffset() . 'H'));

        if ($fromDate->format('d.m.Y') != $fromDateDisplay->format('d.m.Y')) {
            $viewResponse->set('fromDateDisplay', $fromDateDisplay);
        }

        if ($venue->hasIdRaw()) {
            $viewResponse->set('eventDuplicates', new Denkmal_Paging_Event_EventDuplicates($event->getFrom(), $venue));
        }

        $viewResponse->set('event', $event);
        $viewResponse->set('venue', $venue);

        $this->_params = CM_Params::factory(); // Empty params to not send them to client
    }
}

<?php

class Denkmal_Component_EventPreview extends Denkmal_Component_Abstract {

    public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) {
        $event = $this->_params->getEvent('event');
        $venue = $this->_params->has('venue') ? $this->_params->getVenue('venue') : $event->getVenue();

        $settings = new Denkmal_App_Settings();
        $fromDate = $event->getFrom();
        $fromDateDisplay = clone $fromDate;
        $fromDateDisplay->sub(new DateInterval('PT' . $settings->getDayOffset() . 'H'));

        if ($fromDate->format('d.m.Y') != $fromDateDisplay->format('d.m.Y')) {
            $viewResponse->set('fromDateDisplay', $fromDateDisplay);
        }

        if ($venue->hasIdRaw()) {
            if ($event->hasIdRaw()) {
                $eventDuplicates = new Denkmal_Paging_Event_EventDuplicates($event->getFrom(), $venue, [$event]);
            } else {
                $eventDuplicates = new Denkmal_Paging_Event_EventDuplicates($event->getFrom(), $venue);
            }
            $viewResponse->set('eventDuplicates', $eventDuplicates);
        }

        $viewResponse->set('event', $event);
        $viewResponse->set('venue', $venue);

        $this->_params = CM_Params::factory(); // Empty params to not send them to client
    }
}

Exclude existing event from duplicate paging


<?php

require_once 'PHPUnit/Framework.php';

require_once 'FeedAuthorTest.php';
require_once 'FeedContributorTest.php';
require_once 'FeedIdTest.php';
require_once 'FeedRightsTest.php';
require_once 'FeedSubtitleTest.php';
require_once 'FeedTitleTest.php';
require_once 'FeedUpdatedTest.php';

class Atom10_FeedTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0 Feed');

		$suite->addTestSuite('FeedAuthorTest');
		$suite->addTestSuite('FeedContributorTest');
		$suite->addTestSuite('FeedIdTest');
		$suite->addTestSuite('FeedRightsTest');
		$suite->addTestSuite('FeedSubtitleTest');
		$suite->addTestSuite('FeedTitleTest');
		$suite->addTestSuite('FeedUpdatedTest');

		return $suite;
	}
}

?>

<?php

require_once 'PHPUnit/Framework.php';

require_once 'FeedAuthorTest.php';
require_once 'FeedCategoryTest.php';
require_once 'FeedContributorTest.php';
require_once 'FeedIdTest.php';
require_once 'FeedRightsTest.php';
require_once 'FeedSubtitleTest.php';
require_once 'FeedTitleTest.php';
require_once 'FeedUpdatedTest.php';

class Atom10_FeedTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0 Feed');

		$suite->addTestSuite('FeedAuthorTest');
		$suite->addTestSuite('FeedCategoryTest');
		$suite->addTestSuite('FeedContributorTest');
		$suite->addTestSuite('FeedIdTest');
		$suite->addTestSuite('FeedRightsTest');
		$suite->addTestSuite('FeedSubtitleTest');
		$suite->addTestSuite('FeedTitleTest');
		$suite->addTestSuite('FeedUpdatedTest');

		return $suite;
	}
}

?>

Add that test to the Feed tests.

Add that test to the Feed tests.


Use app storage sub path

Use app storage sub path


<?php

namespace PerFi\PerFiBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Template
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        return [
        ];
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ]);
    }
}

<?php

namespace PerFi\PerFiBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Template
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        return [
        ];
    }
}

Remove not needed part of controller

Remove not needed part of controller


<?php

namespace Adldap\Laravel\Validation\Rules;

use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;

class DenyTrashed extends Rule
{
    /**
     * {@inheritdoc}
     */
    public function isValid()
    {
        if ($this->isTrashed()) {
            Event::dispatch(
                new AuthenticatedModelTrashed($this->user, $this->model)
            );

            return false;
        }

        return true;
    }

    /**
     * Determines if the current model is trashed.
     *
     * @return bool
     */
    protected function isTrashed()
    {
        if ($this->model) {
            return method_exists($this->model, 'trashed') && $this->model->trashed();
        }
        return false;
    }
}

<?php

namespace Adldap\Laravel\Validation\Rules;

use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;

class DenyTrashed extends Rule
{
    /**
     * {@inheritdoc}
     */
    public function isValid()
    {
        if ($this->isTrashed()) {
            Event::dispatch(
                new AuthenticatedModelTrashed($this->user, $this->model)
            );

            return false;
        }

        return true;
    }

    /**
     * Determines if the current model is trashed.
     *
     * @return bool
     */
    protected function isTrashed()
    {
        return $this->model
            ? method_exists($this->model, 'trashed') && $this->model->trashed()
            : false;
    }
}

Make it into single statement.

Make it into single statement.


<?php

final class ArcanistDifferentialRevisionStatus {

  const NEEDS_REVIEW      = 0;
  const NEEDS_REVISION    = 1;
  const ACCEPTED          = 2;
  const CLOSED            = 3;
  const ABANDONED         = 4;

  public static function getNameForRevisionStatus($status) {
    static $map = array(
      self::NEEDS_REVIEW      => 'Needs Review',
      self::NEEDS_REVISION    => 'Needs Revision',
      self::ACCEPTED          => 'Accepted',
      self::CLOSED            => 'Closed',
      self::ABANDONED         => 'Abandoned',
    );

    return idx($map, coalesce($status, '?'), 'Unknown');
  }

}

<?php

final class ArcanistDifferentialRevisionStatus {

  const NEEDS_REVIEW      = 0;
  const NEEDS_REVISION    = 1;
  const ACCEPTED          = 2;
  const CLOSED            = 3;
  const ABANDONED         = 4;
  const CHANGES_PLANNED   = 5;
  const IN_PREPARATION    = 6;

  public static function getNameForRevisionStatus($status) {
    $map = array(
      self::NEEDS_REVIEW      => pht('Needs Review'),
      self::NEEDS_REVISION    => pht('Needs Revision'),
      self::ACCEPTED          => pht('Accepted'),
      self::CLOSED            => pht('Closed'),
      self::ABANDONED         => pht('Abandoned'),
      self::CHANGES_PLANNED   => pht('Changes Planned'),
      self::IN_PREPARATION    => pht('In Preparation'),
    );

    return idx($map, coalesce($status, '?'), 'Unknown');
  }

}

Add "Changes Planned" and "In Preparation" states for revisions

Summary:
Ref T2222. Discussion in T4481. Ref T2543.

Primarily, this will let me fix some of the rough edges that came out of ApplicationTransactions and state-based transitions.

I'm also adding a constant for T2543 while I'm in here.

Test Plan: Used `grep` to look for any weird special behavior, didn't see any.

Reviewers: btrahan

Reviewed By: btrahan

CC: aran

Maniphest Tasks: T2543, T2222

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


<?php

class CM_Http_Response_Resource_Css_VendorTest extends CMTest_TestCase {

    public function testProcess() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Http_Request_Get($render->getUrlResource('vendor-css', 'all.css'));
        $response = new CM_Http_Response_Resource_Css_Vendor($request, $this->getServiceManager());
        $response->process();
        $this->assertContains('body{', $response->getContent());
    }
}

<?php

class CM_Http_Response_Resource_Css_VendorTest extends CMTest_TestCase {

    public function testProcess() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Http_Request_Get($render->getUrlResource('vendor-css', 'all.css'));
        $response = new CM_Http_Response_Resource_Css_Vendor($request, $this->getServiceManager());
        $response->process();
        $this->assertContains('body{', $response->getContent());
        $this->assertNotContains('#mocha', $response->getContent());
    }
}

Test to ensure css-vendor doesn't contain resources from *-source folders


<?php

namespace Enqueue\Bundle\Consumption\Extension;

use Doctrine\DBAL\Connection;
use Enqueue\Consumption\Context;
use Enqueue\Consumption\EmptyExtensionTrait;
use Enqueue\Consumption\ExtensionInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;

class DoctrinePingConnectionExtension implements ExtensionInterface
{
    use EmptyExtensionTrait;

    /**
     * @var RegistryInterface
     */
    protected $registry;

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

    /**
     * {@inheritdoc}
     */
    public function onPreReceived(Context $context)
    {
        /** @var Connection $connection */
        foreach ($this->registry->getConnections() as $connection) {
            if (!$connection->isConnected()) {
                continue;
            }

            if ($connection->ping()) {
                return;
            }

            $context->getLogger()->debug(
                '[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.'
            );

            $connection->close();
            $connection->connect();

            $context->getLogger()->debug(
                '[DoctrinePingConnectionExtension] Connection is active now.'
            );
        }
    }
}

<?php

namespace Enqueue\Bundle\Consumption\Extension;

use Doctrine\DBAL\Connection;
use Enqueue\Consumption\Context;
use Enqueue\Consumption\EmptyExtensionTrait;
use Enqueue\Consumption\ExtensionInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;

class DoctrinePingConnectionExtension implements ExtensionInterface
{
    use EmptyExtensionTrait;

    /**
     * @var RegistryInterface
     */
    protected $registry;

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

    /**
     * {@inheritdoc}
     */
    public function onPreReceived(Context $context)
    {
        /** @var Connection $connection */
        foreach ($this->registry->getConnections() as $connection) {
            if (!$connection->isConnected()) {
                continue;
            }

            if ($connection->ping()) {
                continue;
            }

            $context->getLogger()->debug(
                '[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.'
            );

            $connection->close();
            $connection->connect();

            $context->getLogger()->debug(
                '[DoctrinePingConnectionExtension] Connection is active now.'
            );
        }
    }
}

Fix ping to check each connection, not only first one

(cherry picked from commit 72d4097)


<?php

class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread
{
    protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null)
    {
        $wordcount = 0;

        if (!empty($data['threadmark_count']) && empty($thread['word_count']) ||
            empty($data['threadmark_count']) && !empty($thread['word_count']))
        {
            $wordcount = $this->_getThreadModel()->rebuildThreadWordCount(
                $data['thread_id']
            );
        }

        $metadata = array();
        $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount;

        if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy)
        {
            $indexer->setProxyMetaData($metadata);
        }
        else
        {
            $indexer = new SV_SearchImprovements_Search_IndexerProxy(
                $indexer,
                $metadata
            );
        }

        parent::_insertIntoIndex($indexer, $data, $parentData);
    }

    public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds)
    {
        $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array());

        return parent::quickIndex($indexer, $contentIds);
    }
}

<?php

class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread
{
    protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null)
    {
        $wordcount = 0;

        if (!empty($data['threadmark_count']) && empty($data['word_count']) ||
            empty($data['threadmark_count']) && !empty($data['word_count']))
        {
            $wordcount = $this->_getThreadModel()->rebuildThreadWordCount(
                $data['thread_id']
            );
        }

        $metadata = array();
        $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount;

        if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy)
        {
            $indexer->setProxyMetaData($metadata);
        }
        else
        {
            $indexer = new SV_SearchImprovements_Search_IndexerProxy(
                $indexer,
                $metadata
            );
        }

        parent::_insertIntoIndex($indexer, $data, $parentData);
    }

    public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds)
    {
        $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array());

        return parent::quickIndex($indexer, $contentIds);
    }
}

Fix search indexing populating thread wordcount


<?php
return [
    'adminEmail' => 'kalnyanton@gmail.com',
    'title' => 'Веб студия «Палитра»',
    'title_short' => 'Палитра',
    'title_long' => 'Студия веб дизайна «Палитра»',
    'phone' => '+3 8(099) 008 20 17',
    'vk_link' => 'https://vk.com/id249896813',
    'fb_link' => 'https://www.facebook.com/profile.php?id=100007822838492',
    'tw_link' => 'https://twitter.com/',

    'description' => 'Одним из важнейших условий успешного бизнеса является наличие места для регулярного размещения актуальной информации о компании. Вам необходим ресурс, где можно опубликовать подробные сведения о предоставляемых услугах, условиях заказа, контактах и реквизитах.',
    'keywords' => 'заказать сайт под ключ',
];

<?php
return [
    'title' => 'Веб студия «Палитра»',
    'title_short' => 'Палитра',
    'title_long' => 'Студия веб дизайна «Палитра»',
    'phone' => '+3 8(099) 008 20 17',
    'vk_link' => 'https://vk.com/id249896813',
    'fb_link' => 'https://www.facebook.com/profile.php?id=100007822838492',
    'tw_link' => 'https://twitter.com/',

    'description' => 'Одним из важнейших условий успешного бизнеса является наличие места для регулярного размещения актуальной информации о компании. Вам необходим ресурс, где можно опубликовать подробные сведения о предоставляемых услугах, условиях заказа, контактах и реквизитах.',
    'keywords' => 'заказать сайт под ключ',
];

Remove email from frontend config

Remove email from frontend config


<?php

namespace APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class WorkerStatusController extends Controller
{
    /**
     * @ApiDoc(
     *    description="Get the worker status"
     * )
     * @Rest\Get("/worker_status")
     */
    public function getWorkerStatusAction(Request $request)
    {
        $url = $this->getParameter('worker_url') . '/cxf/heartbeat';
        $status = json_decode(file_get_contents($url), true);
        $output = json_encode($status);
        return new Response($output);
    }
}

<?php

namespace APIBundle\Controller;

use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class WorkerStatusController extends Controller
{
    /**
     * @ApiDoc(
     *    description="Get the worker status"
     * )
     * @Rest\Get("/worker_status")
     */
    public function getWorkerStatusAction(Request $request)
    {
        $url = $this->getParameter('worker_url') . '/cxf/heartbeat';
        /** @var \Httpful\Response $response */
        $response = \Httpful\Request::get($url)->send();
        return new Response(json_encode($response->body), $response->code, $response->headers->toArray());
    }
}

Return an error response when worker is not accessible


<?php
/**
 *
 * @param array &$hookinfo  hookinfo
 */
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	try {
		$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');

		// Parse consent config
		$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));

		// Get all consents for user
		$stats = $consent_storage->getStatistics();

		$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.';

	} catch (Exception $e) {
		$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
	}

}
?>

<?php
/**
 *
 * @param array &$hookinfo  hookinfo
 */
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	try {
		$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');

		// Parse consent config
		$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));

		if (!is_callable(array($consent_storage, 'selftest'))) {
			/* Doesn't support a selftest. */
			return;
		}
		$testres = $consent_storage->selftest();
		if ($testres) {
			$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage selftest OK.';
		} else {
			$hookinfo['errors'][] = '[consentSimpleAdmin] Consent Storage selftest failed.';
		}

	} catch (Exception $e) {
		$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
	}

}
?>

consentSimpleAdmin: Use new selftest-function on database backend.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@3309 44740490-163a-0410-bde0-09ae8108e29a