<?php

$template->assign('PageTopic','Plot A Course');

require_once(get_file_loc('menue.inc'));
create_nav_menue($template,$player);

$container=array();
$container['url'] = 'course_plot_processing.php';
$container['body'] = '';

$template->assign('PlotCourseFormLink',SmrSession::get_new_href($container));
$container['url'] = 'course_plot_nearest_processing.php';
$template->assign('PlotNearestFormLink',SmrSession::get_new_href($container));

if ($ship->hasJump())
{
	$container=create_container('sector_jump_processing.php','');
	$container['target_page'] = 'current_sector.php';
	$template->assign('JumpDriveFormLink',SmrSession::get_new_href($container));
}
if(isset($_REQUEST['xtype']))
		$template->assign('XType',$_REQUEST['xtype']);
$template->assign('AllXTypes',array('Technology','Ships','Weapons','Locations','Goods'));
?>

<?php

$template->assign('PageTopic','Plot A Course');

require_once(get_file_loc('menue.inc'));
create_nav_menue($template,$player);

$container=array();
$container['url'] = 'course_plot_processing.php';
$container['body'] = '';

$template->assign('PlotCourseFormLink',SmrSession::get_new_href($container));
$container['url'] = 'course_plot_nearest_processing.php';
$template->assign('PlotNearestFormLink',SmrSession::get_new_href($container));

if ($ship->hasJump())
{
	$container=create_container('sector_jump_processing.php','');
	$container['target_page'] = 'current_sector.php';
	$template->assign('JumpDriveFormLink',SmrSession::get_new_href($container));
}
if(isset($_REQUEST['xtype']))
	SmrSession::updateVar('XType',$_REQUEST['xtype']);
else if(!isset($var['XType']))
	SmrSession::updateVar('XType','Technology');
$template->assign('XType',$var['XType']);
$template->assign('AllXTypes',array('Technology','Ships','Weapons','Locations','Goods'));
?>

Expand technology section for plot to nearest by default.


<?php

namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;

use Honeybee\Ui\Renderer\ActivityRenderer;

class HtmlActivityRenderer extends ActivityRenderer
{
    protected function getTemplateParameters()
    {
        $activity = $this->getPayload('subject');

        $default_css = [
            'activity',
            'activity-' . strtolower($activity->getName())
        ];

        $params = [];
        $params['css'] = $this->getOption('css', $default_css);
        $params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
        $params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
        $params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
        $params['form_css'] = $this->getOption('form_css');
        $params['activity_map_options'] = $this->getOption('activity_map_options', []);

        return array_replace_recursive(parent::getTemplateParameters(), $params);
    }
}

<?php

namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;

use Honeybee\Ui\Renderer\ActivityRenderer;

class HtmlActivityRenderer extends ActivityRenderer
{
    protected function getTemplateParameters()
    {
        $activity = $this->getPayload('subject');

        $default_css = [
            'activity',
            'activity-' . strtolower($activity->getName())
        ];

        $params = [];
        $params['css'] = $this->getOption('css', $default_css);
        $params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
        $params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
        $params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
        $params['form_css'] = $this->getOption('form_css');
        $params['activity_map_options'] = $this->getOption('activity_map_options', []);
        $params['disabled'] = $this->getOption('disabled', false);
        if ($params['disabled']) {
            $params['css'][] = 'disabled';
        }

        return array_replace_recursive(parent::getTemplateParameters(), $params);
    }
}

Add 'disabled' parameter to Activity renderer


<?php

class Helpers
{
    const SUPERUSER_ID = 1;
    const PAGINATION_DEFAULT_ITEMS = 15;
    const UPLOAD_SLUG_INITIAL_LENGTH = 4;
    const NEW_USER_DAYS = 7; // How long is a user considered "new"
    const API_KEY_LENGTH = 64;
    const DB_CACHE_TIME = 5; // Minutes

    // http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
    /**
     * @param $bytes
     * @param int $precision
     * @return string
     */
    public static function formatBytes($bytes, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1000));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1000, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }

    /**
     * @param $file
     * @return bool
     */
    public static function canHaveExif(SplFileInfo $file)
    {
        $hasExif = false;
        if (function_exists('exif_imagetype')) {
            $hasExif = (exif_imagetype($file) != 0);
        }

        return $hasExif;
    }
}

<?php

class Helpers
{
    const SUPERUSER_ID = 1;
    const PAGINATION_DEFAULT_ITEMS = 15;
    const UPLOAD_SLUG_INITIAL_LENGTH = 3;
    const NEW_USER_DAYS = 7; // How long is a user considered "new"
    const API_KEY_LENGTH = 64;
    const DB_CACHE_TIME = 5; // Minutes

    // http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
    /**
     * @param $bytes
     * @param int $precision
     * @return string
     */
    public static function formatBytes($bytes, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1000));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1000, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }

    /**
     * @param $file
     * @return bool
     */
    public static function canHaveExif(SplFileInfo $file)
    {
        $hasExif = false;
        if (function_exists('exif_imagetype')) {
            $hasExif = (exif_imagetype($file) != 0);
        }

        return $hasExif;
    }
}

Set initial slug length to 3

Set initial slug length to 3


<?php

namespace Rosio\EncryptedCookie;

class CookieFactory
{
	static function createCookie ($name)
	{
		return new EncryptedCookie ($name);
	}

	static function getCookie ($name)
	{
		return new EncryptedCookie($name)->load();
	}
}

<?php

namespace Rosio\EncryptedCookie;

class CookieFactory
{
	private $cryptoSystem;

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

	function createCookie ($name)
	{
		return new EncryptedCookie ($name)->setCryptoSystem($this->cryptoSystem);
	}

	function getCookie ($name)
	{
		return new EncryptedCookie($name)->setCryptoSystem($this->cryptoSystem)->load();
	}
}

Make cookiefactory instanced, set cryptosystem on instantiation


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Queue Driver
	|--------------------------------------------------------------------------
	|
	| The Laravel queue API supports a variety of back-ends via an unified
	| API, giving you convenient access to each back-end using the same
	| syntax for each one. Here you may set the default queue driver.
	|
	| Supported: "sync", "beanstalkd"
	|
	*/

	'default' => 'sync',

	/*
	|--------------------------------------------------------------------------
	| Queue Connections
	|--------------------------------------------------------------------------
	|
	| Here you may configure the connection information for each server that
	| is used by your application. A default configuration has been added
	| for each back-end shipped with Laravel. You are free to add more.
	|
	*/

	'connections' => array(

		'sync' => array(
			'driver' => 'sync',
		),

		'beanstalkd' => array(
			'driver' => 'beanstalkd',
			'host'   => 'localhost',
			'queue'  => 'default',
		),

		'sqs' => array(
			'driver' => 'sqs',
			'key'    => 'your-public-key',
			'secret' => 'your-secret-key',
			'queue'  => 'your-queue-url',
			'region' => 'us-east-1',
		),

	),

);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Queue Driver
	|--------------------------------------------------------------------------
	|
	| The Laravel queue API supports a variety of back-ends via an unified
	| API, giving you convenient access to each back-end using the same
	| syntax for each one. Here you may set the default queue driver.
	|
	| Supported: "sync", "beanstalkd", "sqs"
	|
	*/

	'default' => 'sync',

	/*
	|--------------------------------------------------------------------------
	| Queue Connections
	|--------------------------------------------------------------------------
	|
	| Here you may configure the connection information for each server that
	| is used by your application. A default configuration has been added
	| for each back-end shipped with Laravel. You are free to add more.
	|
	*/

	'connections' => array(

		'sync' => array(
			'driver' => 'sync',
		),

		'beanstalkd' => array(
			'driver' => 'beanstalkd',
			'host'   => 'localhost',
			'queue'  => 'default',
		),

		'sqs' => array(
			'driver' => 'sqs',
			'key'    => 'your-public-key',
			'secret' => 'your-secret-key',
			'queue'  => 'your-queue-url',
			'region' => 'us-east-1',
		),

	),

);

Add sqs to list of supported drivers

Add sqs to list of supported drivers

Just forgotten I presume.


<?php
/*
 * Media class
 * Provides functions to get other media types
 */

class Media {
    protected $db;
    function __construct() {
        global $db;
        $this->db = $db;
    }

    /*
     * Public: Get photo albums
     *
     * Returns array of MediaPhoto objects
     */
    public function getAlbums($limit = NULL) {
        $sql = "SELECT
                    `id`
                FROM `media_photo_album`
                WHERE visible = 1
                ";
        if($limit) {
            $sql .= "LIMIT 0, ".$limit;
        }
        $albums = $this->db->get_results($sql);
        foreach($albums as $key => $object) {
            $output[] = new MediaPhoto($object->id);
        }
        return $output;
    }
}
?>

<?php
/*
 * Media class
 * Provides functions to get other media types
 */

class Media {
    protected $db;
    function __construct() {
        global $db;
        $this->db = $db;
    }

    /*
     * Public: Get photo albums
     *
     * Returns array of MediaPhoto objects
     */
    public function getAlbums($limit = NULL) {
        $sql = "SELECT
                    `id`
                FROM `media_photo_album`
                WHERE visible = 1
                ORDER BY date DESC
                ";
        if($limit) {
            $sql .= "LIMIT 0, ".$limit;
        }
        $albums = $this->db->get_results($sql);
        foreach($albums as $key => $object) {
            $output[] = new MediaPhoto($object->id);
        }
        return $output;
    }
}
?>

Order photo albums by date

Order photo albums by date


<?php namespace Orchestra\Support\Traits;

use Orchestra\Support\Str;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

trait UploadableTrait {

    /**
     * Save uploaded file into directory
     *
     * @param  use Symfony\Component\HttpFoundation\File\UploadedFile
     * @param  string $path
     * @return string
     */
    protected function save(UploadedFile $file, $path)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = Str::random(10).".{$extension}";

        $file->move($path, $filename);

        return $filename;
    }

    /**
     * Delete uploaded from directory
     *
     * @param  string $file
     * @return bool
     */
    protected function delete($file)
    {
        return File::delete($file);
    }

}

<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Orchestra\Support\Str;

trait UploadableTrait
{
    /**
     * Save uploaded file into directory.
     *
     * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $file
     * @param  string                                               $path
     * @return string
     */
    protected function saveUploadedFile(UploadedFile $file, $path)
    {
        $file->move($path, $filename = $this->getUploadedFilename($file));

        return $filename;
    }

    /**
     * Delete uploaded from directory
     *
     * @param  string $file
     * @return bool
     */
    protected function deleteUploadedFile($file)
    {
        return File::delete($file);
    }

    /**
     * Get uploaded filename.
     *
     * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $file
     * @return string
     */
    protected function getUploadedFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();

        return Str::random(10).".{$extension}";
    }
}

Use verbose method name to avoid conflict with implementing class.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

use Illuminate\Database\Migrations\Migration;

class AddExternalContestType extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE contests CHANGE type type ENUM(
            'art',
            'beatmap',
            'music',
            'external'
        )");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE contests CHANGE type type ENUM(
            'art',
            'beatmap',
            'music'
        )");
    }
}

<?php

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

use Illuminate\Database\Migrations\Migration;

class AddExternalContestType extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE contests CHANGE type type ENUM(
            'art',
            'beatmap',
            'music',
            'external'
        )");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE contests CHANGE type type ENUM(
            'art',
            'beatmap',
            'music'
        )");
    }
}

Add license header to migration

Add license header to migration


<?php

class auth_model extends Model {

    function is_admin($user) {
        global $admins;

        if (in_array($user, $admins)) {
            return true;
        }
        return false;
    }
}

<?php

class auth_model extends Model {

    function is_admin($user) {
        global $admins;

        if (!isset($admins) || !is_array($admins)) {
            return false;
        }

        if (in_array($user, $admins)) {
            return true;
        }
        return false;
    }
}

Make $admins in config optional

Make $admins in config optional


<?php

namespace CQRSFactory;

use CQRS\Serializer\SerializerInterface;
use CQRS\Serializer\SymfonySerializer;
use CQRSFactory\Exception\DomainException;
use Psr\Container\ContainerInterface;
use Symfony\Component\Serializer\SerializerInterface as SymfonySerializerInterface;

/**
 * @phpstan-type SerializerConfig array{
 *     class: class-string<SerializerInterface>,
 *     instance?: class-string|object,
 *     format?: string,
 *     context?: array
 * }
 * @phpstan-extends AbstractFactory<SerializerInterface>
 */
class SerializerFactory extends AbstractFactory
{
    protected function createWithConfig(ContainerInterface $container, string $configKey): SerializerInterface
    {
        /** @var SerializerConfig $config */
        $config = $this->retrieveConfig($container, $configKey, 'serializer');

        if ($config['class'] === SymfonySerializer::class) {
            $instance = $this->retrieveService(
                $container,
                $config,
                'instance',
                SymfonySerializerInterface::class
            );

            $format = $config['format'] ?? 'json';
            $context = $config['context'] ?? [];

            return new SymfonySerializer($instance, $format, $context);
        }

        return new $config['class'];
    }

    /**
     * @phpstan-return SerializerConfig
     */
    protected function getDefaultConfig(): array
    {
        return [
            'class' => SymfonySerializer::class,
            'instance' => SymfonySerializerInterface::class,
        ];
    }
}

<?php

namespace CQRSFactory;

use CQRS\Serializer\SerializerInterface;
use CQRS\Serializer\SymfonySerializer;
use CQRSFactory\Exception\DomainException;
use Psr\Container\ContainerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface as SymfonySerializerInterface;

/**
 * @phpstan-type SerializerConfig array{
 *     class: class-string<SerializerInterface>,
 *     instance?: class-string|object,
 *     format?: string,
 *     context?: array
 * }
 * @phpstan-extends AbstractFactory<SerializerInterface>
 */
class SerializerFactory extends AbstractFactory
{
    protected function createWithConfig(ContainerInterface $container, string $configKey): SerializerInterface
    {
        /** @var SerializerConfig $config */
        $config = $this->retrieveConfig($container, $configKey, 'serializer');

        if ($config['class'] === SymfonySerializer::class) {
            $instance = $this->retrieveService(
                $container,
                $config,
                'instance',
                SymfonySerializerInterface::class
            );

            $format = $config['format'] ?? 'json';
            $context = $config['context'] ?? [];

            return new SymfonySerializer($instance, $format, $context);
        }

        return new $config['class'];
    }

    /**
     * @phpstan-return SerializerConfig
     */
    protected function getDefaultConfig(): array
    {
        return [
            'class' => SymfonySerializer::class,
            'instance' => SymfonySerializerInterface::class,
            'context' => [
                AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
            ],
        ];
    }
}

feat: Configure symfony serializer to preserve empty objects


<?php

if ( !defined( 'WP_CLI' ) ) return;

global $argv;

$env = $argv[1];

$config = array();

$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';

if ( is_readable( $config_path ) ){

    $configurator = \WP_CLI::get_configurator();

    $configurator->merge_yml( $config_path );
    list( $config, $extra_config ) = $configurator->to_array();
}

if ( 'auto' === $config['color'] ) {
  $colorize = !\cli\Shell::isPiped();
} else {
  $colorize = $config['color'];
}

if ( isset($config['quiet']) && $config['quiet'] )
    $logger = new \WP_CLI\Loggers\Quiet;
else
    $logger = new \WP_CLI\Loggers\Regular( $colorize );

\WP_CLI::set_logger( $logger );

try {
    $environment = new \ViewOne\Environment();
    $environment->run($env);
} catch (Exception $e) {
    \WP_CLI::error( $e->getMessage() );
}

<?php

if ( !defined( 'WP_CLI' ) ) return;

global $argv;

$env = $argv[1];

$config = array();

$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';

if ( is_readable( $config_path ) ){

    $configurator = \WP_CLI::get_configurator();

    $configurator->merge_yml( $config_path );
    list( $config, $extra_config ) = $configurator->to_array();
}

if ( isset($config['color']) && 'auto' === $config['color'] ) {
    $colorize = !\cli\Shell::isPiped();
} elseif(isset($config['color'])) {
    $colorize = $config['color'];
}else {
    $colorize = true;
}

if ( isset($config['quiet']) && $config['quiet'] )
    $logger = new \WP_CLI\Loggers\Quiet;
else
    $logger = new \WP_CLI\Loggers\Regular( $colorize );

\WP_CLI::set_logger( $logger );

try {
    $environment = new \ViewOne\Environment();
    $environment->run($env);
} catch (Exception $e) {
    \WP_CLI::error( $e->getMessage() );
}

Fix colorize otput if there is no config settings in global config file


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

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

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        ValidationException::class,
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

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

Add new exceptions to `$dontReport` property


<?php

declare(strict_types=1);

namespace App\Nova;

use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Text;

class ClassStanding extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = \App\Models\ClassStanding::class;

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'name';

    /**
     * The logical group associated with the resource.
     *
     * @var string
     */
    public static $group = 'Demographics';

    /**
     * The columns that should be searched.
     *
     * @var array<string>
     */
    public static $search = [
        'name',
    ];

    /**
     * Get the fields displayed by the resource.
     */
    public function fields(Request $request): array
    {
        return [
            Text::make('Name')->sortable(),

            BelongsToMany::make('Members', 'members', User::class),

            self::metadataPanel(),
        ];
    }
}

<?php

declare(strict_types=1);

namespace App\Nova;

use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Text;

class ClassStanding extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = \App\Models\ClassStanding::class;

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'name';

    /**
     * The logical group associated with the resource.
     *
     * @var string
     */
    public static $group = 'Demographics';

    /**
     * The columns that should be searched.
     *
     * @var array<string>
     */
    public static $search = [
        'name',
    ];

    /**
     * Get the fields displayed by the resource.
     */
    public function fields(Request $request): array
    {
        return [
            Text::make('Name')->sortable(),

            Number::make('Rank Order')->sortable(),

            BelongsToMany::make('Members', 'members', User::class),

            self::metadataPanel(),
        ];
    }
}

Add Nova UI for class standing rank order


Add sqs to list of supported drivers


<?php

class ShippingEasy_SignedUrl
{
  public function __construct($http_method=null, $path=null, $params=null, $json_body=null, $api_timestamp=null)
  {
    $secret = ShippingEasy::$apiSecret;
    $params["api_key"] = ShippingEasy::$apiKey;
    $params["api_timestamp"] = isset($api_timestamp) ? $api_timestamp : time();
    $signature_object = new ShippingEasy_Signature($secret, $http_method, $path, $params, $json_body);
    $params["api_signature"] = $signature_object->encrypted();
    $this->params = $params;
    $this->path = $path;
  }

  public function getParams()
  {
    return $this->params;
  }

  public function getPath()
  {
    return $this->path;
  }

  public function toString()
  {
    $url = ShippingEasy::$apiBase;
    $url .= $this->getPath();
    $url .= "?" . http_build_query($this->getParams());
    return $url;
  }

}

<?php

class ShippingEasy_SignedUrl
{
  public function __construct($http_method=null, $path=null, $params=null, $json_body=null, $api_timestamp=null, $api_secret = null, $api_key = null)
  {
    $api_secret = isset($api_secret) ? $api_secret : ShippingEasy::$apiSecret;
    $params["api_key"] = isset($api_key) ? $api_key : ShippingEasy::$apiKey;
    $params["api_timestamp"] = isset($api_timestamp) ? $api_timestamp : time();
    $signature_object = new ShippingEasy_Signature($api_secret, $http_method, $path, $params, $json_body);
    $params["api_signature"] = $signature_object->encrypted();

    $this->params = $params;
    $this->path = $path;
  }

  public function getParams()
  {
    return $this->params;
  }

  public function getPath()
  {
    return $this->path;
  }

  public function toString()
  {
    $url = ShippingEasy::$apiBase;
    $url .= $this->getPath();
    $url .= "?" . http_build_query($this->getParams());
    return $url;
  }

}

Allow local override of api key and secret.


<?php
define( 'DB_NAME', 'root_tongue_wp' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', 'root' );
define( 'DB_HOST', '127.0.0.1' );

define( 'SAVEQUERIES', true );
define( 'WP_DEBUG', true );

<?php
define( 'DB_NAME', 'root_tongue_wp' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', 'root' );
define( 'DB_HOST', '127.0.0.1' );

define( 'SAVEQUERIES', true );
define( 'WP_DEBUG', false );

Migrate DB import PRO disable Wp Debug

Migrate DB import PRO disable Wp Debug


<?php

namespace Lmc\Steward\Test;

/**
 * This is a workaround for the order in which PHPUnit executes addFailure on listeners and tearDown
 * If taking screenshot using addFailure, tearDown was already called and the browser closed
 */
class WebdriverListener extends \PHPUnit_Framework_BaseTestListener
{
    public function startTest(\PHPUnit_Framework_Test $test)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }

        $test->log(
            sprintf('Initializing "%s" webdriver for "%s::%s"', BROWSER_NAME, get_class($test), $test->getName())
        );

        $capabilities = [
            \WebDriverCapabilityType::BROWSER_NAME => BROWSER_NAME
        ];

        $test->wd = \RemoteWebDriver::create('http://localhost:4444/wd/hub', $capabilities);

    }

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }

        $test->log(sprintf('Destroying "%s" webdriver for "%s::%s"', BROWSER_NAME, get_class($test), $test->getName()));

        if ($test->wd instanceof \RemoteWebDriver) {
            $test->wd->close();
            $test->wd->quit();
        }
    }
}

<?php

namespace Lmc\Steward\Test;

/**
 * This is a workaround for the order in which PHPUnit executes addFailure on listeners and tearDown
 * If taking screenshot using addFailure, tearDown was already called and the browser closed
 */
class WebdriverListener extends \PHPUnit_Framework_BaseTestListener
{
    public function startTest(\PHPUnit_Framework_Test $test)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }

        $test->log(
            sprintf('Initializing "%s" webdriver for "%s::%s"', BROWSER_NAME, get_class($test), $test->getName())
        );

        $capabilities = [
            \WebDriverCapabilityType::BROWSER_NAME => BROWSER_NAME,
        ];
        $test->wd = \RemoteWebDriver::create('http://localhost:4444/wd/hub', $capabilities);
    }

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }

        if ($test->wd instanceof \RemoteWebDriver) {
            $test->log(sprintf('Destroying "%s" webdriver for "%s::%s" (session %s)', BROWSER_NAME, get_class($test), $test->getName(), $test->wd->getSessionID()));

            // Necessary for phantomjs - see https://github.com/detro/ghostdriver/issues/343
            $test->wd->getCommandExecutor()->execute('deleteAllCookies');

            $test->wd->close();
            $test->wd->quit();
        }
    }
}

Fix phantomJS keeps user logged in even in new session; make login wait for login form


<?php
if (version_compare(PHP_VERSION, '5.3', '>=')) {
    $loader = require_once __DIR__ . '/vendor/autoload.php';
} else {
    require_once dirname(__FILE__) . '/vendor/splclassloader/SplClassLoader.php';

    $loader = new SplClassLoader('Snidel', dirname(__FILE__) . '/src');
    $loader->setNamespaceSeparator('_');
    $loader->register();
}

<?php
if (version_compare(PHP_VERSION, '5.3', '>=')) {
    $loader = require_once __DIR__ . '/vendor/autoload.php';
} else {
    require_once dirname(__FILE__) . '/vendor/splclassloader/SplClassLoader.php';
    require_once dirname(__FILE__) . '/src/Snidel.php';

    $loader = new SplClassLoader('Snidel', dirname(__FILE__) . '/src');
    $loader->setNamespaceSeparator('_');
    $loader->register();
}

Fix Fatal error in php5.2

Fix Fatal error in php5.2


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;

// use vendor generated autoloader
$loader = require __DIR__ . '/vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

// Spoon is not autoloaded via Composer but uses its own old skool autoloader
set_include_path(__DIR__ . '/vendor/spoon/library' . PATH_SEPARATOR . get_include_path());
require_once 'spoon/spoon.php';

return $loader;

<?php

// @TODO rename this file to bootstrap.php to better reflect its function

use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\Dotenv\Dotenv;

// use vendor generated autoloader
$loader = require __DIR__ . '/vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

// Spoon is not autoloaded via Composer but uses its own old skool autoloader
set_include_path(__DIR__ . '/vendor/spoon/library' . PATH_SEPARATOR . get_include_path());
require_once 'spoon/spoon.php';

// load server variables
if (!array_key_exists('FORK_ENV', $_SERVER)) {
    $_SERVER['FORK_ENV'] = $_ENV['FORK_ENV'] ?? null;
}

if ('prod' !== $_SERVER['FORK_ENV']) {
    if (!class_exists(Dotenv::class)) {
        throw new RuntimeException('The "FORK_ENV" environment variable is not set to "prod". Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
    }
    $dotenv = new Dotenv();

    $dotenv->load(__DIR__ . '/.env');

    // @TODO when updating to Fork 6, using Symfony 4, check if we still need to check the file's existence
    if (file_exists(__DIR__ . '/.env.local')) {
        $dotenv->load(__DIR__ . '/.env.local');
    }
}

$_SERVER['FORK_ENV'] = $_ENV['FORK_ENV'] = $_SERVER['FORK_ENV'] ?: $_ENV['FORK_ENV'] ?: 'dev';
$_SERVER['FORK_DEBUG'] = $_SERVER['FORK_DEBUG'] ?? $_ENV['FORK_DEBUG'] ?? 'prod' !== $_SERVER['FORK_ENV'];
$_SERVER['FORK_DEBUG'] = $_ENV['FORK_DEBUG'] = (int) $_SERVER['FORK_DEBUG'] || filter_var($_SERVER['FORK_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';

return $loader;

Load the .env(.local) file using Symfony's Dotenv


<?php namespace Todaymade\Daux\Format\HTML;

use Todaymade\Daux\GeneratorHelper;

trait HTMLUtils
{
    public function ensureEmptyDestination($destination)
    {
        if (is_dir($destination)) {
            GeneratorHelper::rmdir($destination);
        } else {
            mkdir($destination);
        }
    }

    /**
     * Copy all files from $local to $destination.
     *
     * @param string $destination
     * @param string $local_base
     */
    public function copyThemes($destination, $local_base)
    {
        mkdir($destination . DIRECTORY_SEPARATOR . 'themes');
        GeneratorHelper::copyRecursive(
            $local_base,
            $destination . DIRECTORY_SEPARATOR . 'themes'
        );
    }
}

<?php namespace Todaymade\Daux\Format\HTML;

use Todaymade\Daux\GeneratorHelper;

trait HTMLUtils
{
    public function ensureEmptyDestination($destination)
    {
        if (is_dir($destination)) {
            GeneratorHelper::rmdir($destination);
        } else {
            mkdir($destination, 0777, true);
        }
    }

    /**
     * Copy all files from $local to $destination.
     *
     * @param string $destination
     * @param string $local_base
     */
    public function copyThemes($destination, $local_base)
    {
        mkdir($destination . DIRECTORY_SEPARATOR . 'themes');
        GeneratorHelper::copyRecursive(
            $local_base,
            $destination . DIRECTORY_SEPARATOR . 'themes'
        );
    }
}

Make sure the destination directory can be created recursively


<?php

use WP_CLI_Login\WP_CLI_Login_Server;

if (! class_exists('PHPUnit_Framework_TestCase')) {
    class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase');
}

class WP_CLI_Login_ServerTest extends PHPUnit_Framework_TestCase
{
    /** @test */
    function parses_endpoint_and_key_from_uri()
    {
        list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key');

        $this->assertSame('end', $endpoint);
        $this->assertSame('key', $public);
    }

    /** @test */
    function parses_endpoint_and_key_from_uri_for_subdirectory_site()
    {
        list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key');

        $this->assertSame('end', $endpoint);
        $this->assertSame('key', $public);
    }

}

<?php

use PHPUnit\Framework\TestCase;
use WP_CLI_Login\WP_CLI_Login_Server;

class WP_CLI_Login_ServerTest extends TestCase
{
    /** @test */
    function parses_endpoint_and_key_from_uri()
    {
        list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key');

        $this->assertSame('end', $endpoint);
        $this->assertSame('key', $public);
    }

    /** @test */
    function parses_endpoint_and_key_from_uri_for_subdirectory_site()
    {
        list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key');

        $this->assertSame('end', $endpoint);
        $this->assertSame('key', $public);
    }

}

Use namespaced PHPUnit test case

Use namespaced PHPUnit test case

Polyfilled by yoast package now


#!/usr/bin/php
<?php
require dirname(__FILE__) . '/../src/Curl/Curl.php';

$current_version = Curl\Curl::VERSION;
list($major, $_, $_) = explode('.', $current_version);
$new_version = implode('.', array((string)((int)$major += 1), '0', '0'));

foreach (array(
        array(
            dirname(__FILE__) . '/../src/Curl/Curl.php',
            '/const VERSION = \'(?:\d+.\d+.\d+)\';/',
            'const VERSION = \'' . $new_version . '\';',
        ),
    ) as $info) {
    list($filepath, $find, $replace) = $info;
    $data = preg_replace($find, $replace, file_get_contents($filepath));
    file_put_contents($filepath, $data);
}

$rightwards_arrow = json_decode('"\u2192"');
echo 'Bump version: ' . $current_version . ' ' . $rightwards_arrow . ' ' . $new_version . "\n";

#!/usr/bin/php
<?php
require dirname(__FILE__) . '/../src/Curl/Curl.php';

$current_version = Curl\Curl::VERSION;
list($major, $_, $__) = explode('.', $current_version);
$new_version = implode('.', array((string)((int)$major += 1), '0', '0'));

foreach (array(
        array(
            dirname(__FILE__) . '/../src/Curl/Curl.php',
            '/const VERSION = \'(?:\d+.\d+.\d+)\';/',
            'const VERSION = \'' . $new_version . '\';',
        ),
    ) as $info) {
    list($filepath, $find, $replace) = $info;
    $data = preg_replace($find, $replace, file_get_contents($filepath));
    file_put_contents($filepath, $data);
}

$rightwards_arrow = json_decode('"\u2192"');
echo 'Bump version: ' . $current_version . ' ' . $rightwards_arrow . ' ' . $new_version . "\n";

Use unique variables with list() to prevent unexpected results.

PHP Compatibility check for PHP_CodeSniffer error message:
    FILE: php-curl-class/scripts/bump_major_version.php
    ---------------------------------------------------------------------------------------------------------------------------------------------
    FOUND 1 ERROR AFFECTING 1 LINE
    ---------------------------------------------------------------------------------------------------------------------------------------------
     6 | ERROR | list() will assign variable from left-to-right since PHP 7.0. Ensure all variables in list() are unique to prevent unexpected
       |       | results. (PHPCompatibility.Lists.AssignmentOrder.Affected)
    ---------------------------------------------------------------------------------------------------------------------------------------------


<?php

namespace OwsProxy3\CoreBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Christian Wygoda
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('fom_user');

        $rootNode
                ->children()
                ->scalarNode('logging')
                ->defaultTrue()
                ->end()
                ->scalarNode('obfuscate_client_ip')
                ->defaultTrue()
                ->end()
                ->arrayNode("proxy")
                ->canBeUnset()
                ->addDefaultsIfNotSet()
                ->children()
                ->scalarNode('host')->defaultNull()->end()
                ->scalarNode('port')->defaultNull()->end()
                ->scalarNode('connecttimeout')->defaultNull()->end()
                ->scalarNode('timeout')->defaultNull()->end()
                ->scalarNode('user')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->scalarNode('checkssl')->defaultNull()->end()
                ->arrayNode("noproxy")
                ->prototype('scalar')->end()
                ->end()
                ->end()
                ->end()
                ->end();

        return $treeBuilder;
    }

}

<?php

namespace OwsProxy3\CoreBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Christian Wygoda
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ows_proxy3_core');

        $rootNode
                ->children()
                ->scalarNode('logging')
                ->defaultTrue()
                ->end()
                ->scalarNode('obfuscate_client_ip')
                ->defaultTrue()
                ->end()
                ->arrayNode("proxy")
                ->canBeUnset()
                ->addDefaultsIfNotSet()
                ->children()
                ->scalarNode('host')->defaultNull()->end()
                ->scalarNode('port')->defaultNull()->end()
                ->scalarNode('connecttimeout')->defaultNull()->end()
                ->scalarNode('timeout')->defaultNull()->end()
                ->scalarNode('user')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->scalarNode('checkssl')->defaultNull()->end()
                ->arrayNode("noproxy")
                ->prototype('scalar')->end()
                ->end()
                ->end()
                ->end()
                ->end();

        return $treeBuilder;
    }

}

Fix copy&pasted extension config root node name


<?php
namespace Tests\Shopello\API;

use \Shopello\API\ApiClient;
use \Curl\Curl;

class ApiClientTest extends \PHPUnit_Framework_TestCase
{
    /** @var ApiClient */
    private $target;

    /** @var Curl */
    private $curlMock;

    public function setUp()
    {
        $this->curlMock = $this->getMock('Curl\Curl');

        $this->target = new ApiClient($this->curlMock);
    }

    /**
     * @test
     */
    public function shouldSetApiKey()
    {
        // Fixture
        // Test
        $actual = $this->target->setApiKey('Hello');

        // Assert
        $this->assertSame(null, $actual);
    }

    /**
     * @test
     */
    public function shouldSetApiEndpoint()
    {
        // Fixture
        // Test
        $actual = $this->target->setApiEndpoint('Hello');

        // Assert
        $this->assertSame(null, $actual);
    }

    /**
     * @test
     */
    public function shouldGetProduct()
    {
        // Fixture
        // Test
        $actual = $this->target->getProduct(123);

        // Assert
        print_r($actual);
    }
}

<?php
namespace Tests\Shopello\API;

use \Shopello\API\ApiClient;
use \Curl\Curl;

class ApiClientTest extends \PHPUnit_Framework_TestCase
{
    /** @var ApiClient */
    private $target;

    /** @var Curl */
    private $curlMock;

    public function setUp()
    {
        $this->curlMock = $this->getMock('\Curl\Curl');

        $this->target = new ApiClient($this->curlMock);
    }

    /**
     * @test
     */
    public function shouldSetApiKey()
    {
        // Fixture
        // Test
        $actual = $this->target->setApiKey('Hello');

        // Assert
        $this->assertSame(null, $actual);
    }

    /**
     * @test
     */
    public function shouldSetApiEndpoint()
    {
        // Fixture
        // Test
        $actual = $this->target->setApiEndpoint('Hello');

        // Assert
        $this->assertSame(null, $actual);
    }

    /**
     * @test
     * @expectedException \Exception
     */
    public function shouldFailRequest()
    {
        // Fixate
        $this->curlMock->response = json_encode(
            (object) array(
                'error' => 'Not allowed'
            )
        );

        $this->curlMock->error = 1;

        // Test
        $actual = $this->target->getProduct(1);
    }
}

Make sure to test failures

Make sure to test failures


<?php

require_once '../lib/Qless/Worker.php';
require_once '../lib/Qless/Queue.php';
require_once '../lib/Qless/Client.php';
require_once 'TestWorkerImpl.php';

$queues = ['testQueue1','testQueue2'];
$client = new Qless\Client('localhost',6380);
$worker = new Qless\Worker("TestWorker_1", $queues, $client, 5);

$worker->run();

<?php

require_once '../lib/Qless/Worker.php';
require_once '../lib/Qless/Queue.php';
require_once '../lib/Qless/Client.php';
require_once 'TestWorkerImpl.php';

$queues = ['testQueue1','testQueue2'];
$REDIS_HOST = getenv('REDIS_HOST') ?: 'localhost';
$REDIS_PORT = getenv('REDIS_PORT') ?: 6380;

$client = new Qless\Client($REDIS_HOST, $REDIS_PORT);
$worker = new Qless\Worker("TestWorker_1", $queues, $client, 5);

$worker->run();

Support REDIS_HOST and REDIS_PORT environment variables


<?php

namespace Purekid\Mongodm\Test\TestCase;

use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;

/**
 * Test Case Base Class for using Phactory *
 */
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
  protected static $db;
  protected static $phactory;

  public static function setUpBeforeClass()
  {
    MongoDB::setConfigBlock('testing', array(
      'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'test_db'
      )
    ));
    MongoDB::instance('testing')->connect();

    if(!self::$db) {
      self::$db = MongoDB::instance('testing');
    }

    if(!self::$phactory) {
      self::$phactory = new Phactory(self::$db->getDB());
      self::$phactory->reset();
    }

    //set up Phactory db connection
    self::$phactory->reset();
  }

  public static function tearDownAfterClass()
  {
    foreach(self::$db->getDB()->getCollectionNames() as $collection) {
      self::$db->getDB()->$collection->drop();
    }
  }

  protected function setUp()
  {
  }

  protected function tearDown()
  {
    self::$phactory->recall();
  }
}

<?php

namespace Purekid\Mongodm\Test\TestCase;

use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;

/**
 * Test Case Base Class for using Phactory *
 */
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
  protected static $db;
  protected static $phactory;

  public static function setUpBeforeClass()
  {
    MongoDB::setConfigBlock('testing', array(
      'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'test_db'
      )
    ));

    MongoDB::instance('testing')->connect();

//    if(!self::$db) {
      self::$db = MongoDB::instance('testing');
//    }

    if(!self::$phactory) {
      self::$phactory = new Phactory(self::$db->getDB());
      self::$phactory->reset();
    }

    //set up Phactory db connection
    self::$phactory->reset();
  }

  public static function tearDownAfterClass()
  {
    foreach(self::$db->getDB()->getCollectionNames() as $collection) {
      self::$db->getDB()->$collection->drop();
    }
  }

  protected function setUp()
  {
  }

  protected function tearDown()
  {
    self::$phactory->recall();
  }
}

Fix for travis php5.4 falling

Fix for travis php5.4 falling


<?php

namespace Pharam\Console\Commands;

use Pharam\Application;
use Pharam\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class InitCommand extends Command
{

    protected $name = 'init';

    protected $description = 'Initializes & generates an config file';

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var FileSystem $fileSystem */
        $fileSystem = $this->getContainer()->make('filesystem');

        $sourceFile = __DIR__ . '/../../../' . Application::DIST_CONFIG_FILE;
        $destinationFile = getcwd() . '/' . Application::APP_CONFIG_FILE;

        $fileSystem->copy($sourceFile, $destinationFile);

        $output->writeln('<comment>Creating pharam.yml file...</comment> <info>✔</info>');
        $output->writeln('<comment>pharam.yml file created at:</comment> ' . getcwd());
    }
}

<?php

namespace Pharam\Console\Commands;

use Pharam\Application;
use Pharam\Console\Command;
use InvalidArgumentException;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class InitCommand extends Command
{

    protected $name = 'init';

    protected $description = 'Initializes & generates an config file';

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var FileSystem $fileSystem */
        $fileSystem = $this->getContainer()->make('filesystem');

        $sourceFile = __DIR__ . '/../../../' . Application::DIST_CONFIG_FILE;
        $destinationFile = getcwd() . '/' . Application::APP_CONFIG_FILE;

        if ($fileSystem->exists($destinationFile)) {
            throw new InvalidArgumentException('Config file has already been initialized.');
        }

        $fileSystem->copy($sourceFile, $destinationFile);

        $output->writeln('<comment>Creating pharam.yml file...</comment> <info>✔</info>');
        $output->writeln('<comment>pharam.yml file created at:</comment> ' . getcwd());
    }
}

Check for config file if it already exists.


<?php

namespace Omnipay\Alipay\Message;

use Omnipay\Common\Message\AbstractResponse;

class RefundNotifyResponse extends AbstractResponse
{

    /**
     * @var ExpressCompletePurchaseRequest
     */
    protected $request;

    public function getResponseText()
    {
        if ($this->isSuccessful()) {
            return 'success';
        } else {
            return 'fail';
        }
    }

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isVerifySuccess()
    {
        return $this->data['verify_success'];
    }
}

<?php

namespace Omnipay\Alipay\Message;

use Omnipay\Common\Message\AbstractResponse;

class RefundNotifyResponse extends AbstractResponse
{

    /**
     * @var ExpressCompletePurchaseRequest
     */
    protected $request;

    public function getResponseText()
    {
        if ($this->isSuccessful()) {
            return 'success';
        } else {
            return 'fail';
        }
    }

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isVerifySuccess()
    {
        return $this->data['verify_success'];
    }

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        return $this->isVerifySuccess();
    }
}

Fix isSuccessful method not exists

Fix isSuccessful method not exists


<?php
/**
 * Initialize the router and set routes

 * ==================

 * New routes are added like this:

 * $router->add('/uri', 'Class/function');

 * To accept parameters in the URI you can use two options:

 * :s = string

 * :i = integer

 * Parameter options are used like so:

 * $router->add('/uri/:s/:i', 'Class/function');

 * Integers will still be accepted if you use :s and you can just convert them
 * to a true integer later if you wish.
 *
 * @author David Summerton
 * @link http://saskphp.com/ Sask website
 * @license http://opensource.org/licenses/MIT MIT
 *
 *
 */

$router = new Router();

$router->add('/', 'Hello/world');

<?php

/*
 * 	Initialize the router and set routes
 * 	==================
 * 	New routes are added like this:
 * 	$router->add('/uri', 'Class/function');
 *
 * 	To accept parameters in the URI you can use two options:
 * 	:s = string
 * 	:i = integer
 *
 * 	Parameter options are used like so:
 * 	$router->add('/uri/:s/:i', 'Class/function');
 *
 * 	Integers will still be accepted if you use :s and you can
 * 	just convert them to a true integer later if you wish.
 */

$router = new Router();

$router->add('/', 'Hello/world');

Revert "Added some PHPDoc tags and changed some formats."

This reverts commit e07e8e5c97683a88c2c551d5190cb2d1ebf09845.


<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Model;

/**
 * Trait for doctrine models that use a sortable handler
 */
trait SortableModelTrait
{
    /**
     * Applies the sort order mapping as provided in the parameters.
     *
     * The model should wrap this method and use type hints on the $where parameter entries.
     *
     * @param array $sortMapping
     * @param array $where
     *
     * @return bool
     */
    protected function flushSortOrderMapping (array $sortMapping, array $where) : bool
    {
        if ($this->sortableHandler->applySorting($sortMapping, $where))
        {
            $this->flush();
            return true;
        }

        return false;
    }
}

<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Model;

/**
 * Trait for doctrine models that use a sortable handler
 */
trait SortableModelTrait
{
    /**
     * Applies the sort order mapping as provided in the parameters.
     *
     * The model should wrap this method and use type hints on the $where parameter entries.
     *
     * @param array|mixed $sortMapping
     * @param array $where
     *
     * @return bool
     */
    protected function flushSortOrderMapping ($sortMapping, array $where) : bool
    {
        if ($this->sortableHandler->applySorting($sortMapping, $where))
        {
            $this->flush();
            return true;
        }

        return false;
    }
}

Allow more types, as the helper allows more


<?php namespace Barryvdh\StackMiddleware;

use Closure;
use Illuminate\Contracts\Container\Container;

class Wrapper
{
    /** @var Container $container */
    protected $container;

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

    /**
     * Wrap and register the middleware in the Container
     *
     * @param  string         $abstract
     * @param  Closure|string $callable
     */
    public function bind($abstract, $callable)
    {
        $this->container->bind($abstract, function() use($callable) {
            return $this->wrap($callable);
        });
    }

    /**
     * Wrap the StackPHP Middleware in a Laravel Middleware
     *
     * @param  Closure|string  $callable
     * @return ClosureMiddleware
     */
    public function wrap($callable)
    {
        $kernel = new ClosureHttpKernel();

        if (is_callable($callable)) {
            $middleware = $callable($kernel);
        } else {
            $middleware = new $callable($kernel)
        }

        return new ClosureMiddleware($kernel, $middleware);
    }
}

<?php namespace Barryvdh\StackMiddleware;

use Closure;
use Illuminate\Contracts\Container\Container;

class Wrapper
{
    /** @var Container $container */
    protected $container;

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

    /**
     * Wrap and register the middleware in the Container
     *
     * @param  string         $abstract
     * @param  array          $params
     * @param  Closure|string $callable
     */
    public function bind($abstract, $callable, $params = [])
    {
        $this->container->bind($abstract, function() use($callable, $params) {
            return $this->wrap($callable, $params);
        });
    }

    /**
     * Wrap the StackPHP Middleware in a Laravel Middleware
     *
     * @param  Closure|string  $callable
     * @param  array           $params
     * @return ClosureMiddleware
     */
    public function wrap($callable, $params = [])
    {
        $kernel = new ClosureHttpKernel();

        if (is_callable($callable)) {
            $middleware = $callable($kernel);
        } else {
            // Add kernel as first parameter
            array_unshift($params, $kernel);
            $middleware = $this->container->make($callable, $params);
        }

        return new ClosureMiddleware($kernel, $middleware);
    }
}

Allow string + params as builder

Allow string + params as builder

Fixes #2


<?php

/**
* ownCloud - bookmarks plugin
*
* @author Arthur Schiwon
* @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// Check if we are a user
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('bookmarks');

$query = OCP\DB::prepare('
	UPDATE `*PREFIX*bookmarks`
	SET `clickcount` = `clickcount` + 1
	WHERE `user_id` = ?
		AND `url` LIKE ?
	');

$params=array(OCP\USER::getUser(), htmlspecialchars_decode($_POST["url"]));
$bookmarks = $query->execute($params);

header( "HTTP/1.1 204 No Content" );

Remove empty lines at end of file

Remove empty lines at end of file


<?php
namespace Phragile;

use GuzzleHttp\Client;

class PhabricatorOAuth {
	public function requestAccessToken($authCode)
	{
		return with(new Client)->get($this->accessTokenURL($authCode))->json();
	}

	private function accessTokenURL($authCode)
	{
		return $_ENV['PHABRICATOR_URL'] . 'oauthserver/token/?' . http_build_query([
			'client_id' => $_ENV['OAUTH_CLIENT_ID'],
			'client_secret' => $_ENV['OAUTH_CLIENT_SECRET'],
			'code' => $authCode,
			'grant_type' => 'authorization_code',
			'redirect_uri' => route('login_path')
		]);
	}
}

<?php
namespace Phragile;

use GuzzleHttp\Client;

class PhabricatorOAuth {

	// TODO: This might fail in the future as Phabricator's OAuth implementation is supposed to redirect back to the
	//       client application and not just respond with a JSON object.
	public function requestAccessToken($authCode)
	{
		return with(new Client)->get($this->accessTokenURL($authCode))->json();
	}

	private function accessTokenURL($authCode)
	{
		return $_ENV['PHABRICATOR_URL'] . 'oauthserver/token/?' . http_build_query([
			'client_id' => $_ENV['OAUTH_CLIENT_ID'],
			'client_secret' => $_ENV['OAUTH_CLIENT_SECRET'],
			'code' => $authCode,
			'grant_type' => 'authorization_code',
			'redirect_uri' => route('login_path')
		]);
	}
}

Add TODO for OAuth workaround.

Add TODO for OAuth workaround.


<?php

class Auth {
	public $session;

	public function __construct() {
		$this->session = new \SlimSession\Helper;
	}

	public function login( $user ) {
		$this->session->set('authenticated', [
			'name' => $user->title,
			'email' => $user->email,
			'id' => $user->id
		]);
	}

	public function logout() {
		$this->session->delete('authenticated');
	}

	/**
	 * Check if logged in user has right properties
	 *
	 * @var string[] $allowed String with single id or array with allowed user id's
	 *
	 * @return boolean Returns true if logged in user id is in $allowed, false otherwise
	 */
	public function check( $allowed ) {
		if ( isset( $this->session->authenticated ) ) {
			if (
				( is_array( $allowed ) && !in_array( $app->session->authenticated['id'], $allowed ) )
				||
				$this->session->authenticated['id'] != $allowed

			) {
				throw new \Exception('You are not allowed to perform this action.');
			}
		} else {
			throw new \Exception('You need to log in to perform this action.');
		}
	}

}

?>

<?php

class Auth {
	public $session;

	public function __construct() {
		$this->session = new \SlimSession\Helper;
	}

	public function login( $user ) {
		$this->session->set('authenticated', [
			'name' => $user->title,
			'email' => $user->email,
			'id' => $user->id
		]);
	}

	public function logout() {
		$this->session->delete('authenticated');
	}

	/**
	 * Check if logged in user has right properties. Throws an exception if not.
	 *
	 * @var string[] $allowed String with single id or array with allowed user id's
	 *
	 * @return string[] Array with logged in user name, email and id.
	 */
	public function check( $allowed ) {
		if ( isset( $this->session->authenticated ) ) {
			if (
				( is_array( $allowed ) && in_array( $app->session->authenticated['id'], $allowed ) )
				||
				$this->session->authenticated['id'] == $allowed

			) {
				return $this->session->authenticated;
			} else {
				throw new \Exception('You are not allowed to perform this action.');
			}
		} else {
			throw new \Exception('You need to log in to perform this action.');
		}
	}

}

?>

Check returns logged in user array.

Check returns logged in user array.


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This file contains the Search controller
 */

/**
 * The controller for the search pages
 */
class Search extends CI_Controller {

	/**
	 * The search page call
	 */
	function index()
	{
		$this->load->helper('form');
		$this->load->library('form_validation');

		$submit = $this->input->post('submit');
		$search_results = array();

		$search_term = $this->input->post('term');

		if($submit)
		{
			if($this->form_validation->run('search'))
			{
				$this->load->model('spark');

				$search_results = Spark::search($search_term);
			}
			else
			{
				UserHelper::setNotice('Whoops. There were some errors. Check below and re-submit!');
			}
		}

		$data['search_term'] = $search_term;
		$data['sparks']   = $search_results;

		echo json_encode($data);
	}

}

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This file contains the Search controller
 */

/**
 * The controller for the search pages
 */
class Search extends CI_Controller {

	/**
	 * The search page call
	 */
	function index()
	{
		$this->load->helper('form');
		$this->load->library('form_validation');

		$submit = $this->input->post('submit');
		$search_results = array();

		$search_term = $this->input->get_post('term', TRUE);

		if($submit)
		{
			if($this->form_validation->run('search'))
			{
				$this->load->model('spark');

				$search_results = Spark::search($search_term);
			}
			else
			{
				UserHelper::setNotice('Whoops. There were some errors. Check below and re-submit!');
			}
		}

		$data['search_term'] = $search_term;
		$data['sparks']   = $search_results;

		echo json_encode($data);
	}

}

Allow term to be specified via get parameter


<?php

/**
 * @copyright  Frederic G. Østby
 * @license    http://www.makoframework.com/license
 */

namespace mako\application\commands\migrations;

use mako\application\commands\migrations\Command;
use mako\application\commands\migrations\RollbackTrait;

/**
 * Command that rolls back the last batch of migrations.
 *
 * @author  Frederic G. Østby
 */

class Down extends Command
{
	use RollbackTrait;

	/**
	 * Command information.
	 *
	 * @var array
	 */

	protected $commandInformation =
	[
		'description' => 'Rolls back the last batch of migrations.',
		'arguments'   =>
		[
			'batches' =>
			[
				'optional'    => true,
				'description' => 'Number of batches to roll back'
			],
		],
		'options'     => [],
	];

	/**
	 * Executes the command.
	 *
	 * @access  public
	 * @param   string  $arg2  Number of batches to roll back
	 */

	public function execute($arg2 = 1)
	{
		$this->rollback($arg2);
	}
}

<?php

/**
 * @copyright  Frederic G. Østby
 * @license    http://www.makoframework.com/license
 */

namespace mako\application\commands\migrations;

use mako\application\commands\migrations\Command;
use mako\application\commands\migrations\RollbackTrait;

/**
 * Command that rolls back the last batch of migrations.
 *
 * @author  Frederic G. Østby
 */

class Down extends Command
{
	use RollbackTrait;

	/**
	 * Command information.
	 *
	 * @var array
	 */

	protected $commandInformation =
	[
		'description' => 'Rolls back the last batch of migrations.',
		'arguments'   => [],
		'options'     =>
		[
			'batches' =>
			[
				'optional'    => true,
				'description' => 'Number of batches to roll back'
			],
		],
	];

	/**
	 * Executes the command.
	 *
	 * @access  public
	 * @param   string  $batches  Number of batches to roll back
	 */

	public function execute($batches = 1)
	{
		$this->rollback($batches);
	}
}

Use option instead of argument

Use option instead of argument


<?php

namespace Benrowe\Laravel\Widgets\Traits;

/**
 * Provides the begin & end functionality for the Widget factory
 *
 * @package Benrowe\Laravel\Widgets
 */
trait BeginEndFactory
{
    private $stack = [];

    /**
     * [begin description]
     * @return [type] [description]
     */
    public function begin()
    {

    }

    /**
     * [end description]
     * @return [type] [description]
     */
    public function end()
    {

    }
}

<?php

namespace Benrowe\Laravel\Widgets\Traits;

/**
 * Provides the begin & end functionality for the Widget factory
 *
 * @package Benrowe\Laravel\Widgets
 */
trait BeginEndFactory
{
    private $stack = [];

    /**
     * [begin description]
     * @return [type] [description]
     */
    public function begin()
    {
        $args = func_get_args();
        $this->stack[] = $args;
        $this->instantiateWidget($args);

        return $this->asExpression($this->widget->begin());
    }

    /**
     * [end description]
     * @return [type] [description]
     */
    public function end()
    {
        $args = array_pop($this->stack);
        $args[1] = $args[1] ? array_merge($args[1], $config) : [];
        $this->instantiateWidget($args);

        return $this->asExpression($this->widget->end());
    }
}

Implement begin & end functionality for Trait


<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\Util;

/**
 * The file size formatter
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class FileSizeFormatter
{
    /**
     * @param int $size
     * @param int $precision
     *
     * @return string
     */
    public static function formatBytes(int $size, int $precision = 2) : string
    {
        $base     = log($size, 1024);
        $suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];

        return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[(int)floor($base)];
    }
}

<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\Util;

/**
 * The file size formatter
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class FileSizeFormatter
{
    /**
     * @param int $size
     * @param int $precision
     *
     * @return string
     */
    public static function formatBytes(int $size, int $precision = 2) : string
    {
        if ($size === 0) {
            return '0B';
        }

        $base     = log($size, 1024);
        $suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];

        return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[(int)floor($base)];
    }
}

Fix issue with formatting 0 bytes file size


<?php

namespace AmpProject\Exception;

use InvalidArgumentException;

/**
 * Exception thrown when an invalid option value was provided.
 *
 * @package ampproject/amp-toolbox
 */
final class InvalidOptionValue extends InvalidArgumentException implements AmpException
{
    /**
     * Instantiate an InvalidOptionValue exception for an invalid option value.
     *
     * @param string        $option   Name of the option.
     * @param array<string> $accepted Array of acceptable values.
     * @param string        $actual   Value that was actually provided.
     * @return self
     */
    public static function forValue($option, $accepted, $actual)
    {
        $acceptedString = implode(', ', $accepted);
        $message = "The value for the option '{$option}' expected the value to be one of "
                   . "[{$acceptedString}], got '{$actual}' instead.";

        return new self($message);
    }
}

<?php

namespace AmpProject\Exception;

use DomainException;

/**
 * Exception thrown when an invalid option value was provided.
 *
 * @package ampproject/amp-toolbox
 */
final class InvalidOptionValue extends DomainException implements AmpException
{
    /**
     * Instantiate an InvalidOptionValue exception for an invalid option value.
     *
     * @param string        $option   Name of the option.
     * @param array<string> $accepted Array of acceptable values.
     * @param string        $actual   Value that was actually provided.
     * @return self
     */
    public static function forValue($option, $accepted, $actual)
    {
        $acceptedString = implode(', ', $accepted);
        $message = "The value for the option '{$option}' expected the value to be one of "
                   . "[{$acceptedString}], got '{$actual}' instead.";

        return new self($message);
    }
}

Extend DomainException instead of InvalidArgumentException


<?php
namespace Fyuze\Kernel\Application;

use Fyuze\Http\Kernel;
use Fyuze\Http\Request;
use Fyuze\Http\Response;
use Fyuze\Kernel\Fyuze;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;

class Web extends Fyuze
{
    /**
     * @return Response
     */
    public function boot($request = null)
    {
        $request = $this->getRegistry()->make('Fyuze\Http\Request');
        $routes = include $this->path . '/routes.php';

        $context = new RequestContext();
        $matcher = new UrlMatcher($routes, $context);
        $resolver = new ControllerResolver();

        $kernel = new Kernel($matcher, $resolver);
        return $kernel->handle($request);
    }
}

<?php
namespace Fyuze\Kernel\Application;

use Fyuze\Http\Kernel;
use Fyuze\Http\Request;
use Fyuze\Http\Response;
use Fyuze\Kernel\Fyuze;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;

class Web extends Fyuze
{
    /**
     * @return Response
     */
    public function boot($request = null)
    {
        $request = $this->getRegistry()->make('Fyuze\Http\Request');
        $routes = include $this->path . '/routes.php';

        $context = new RequestContext();
        $matcher = new UrlMatcher($routes, $context);
        $resolver = new ControllerResolver();

        $kernel = new Kernel($matcher, $resolver);
        $kernel = new HttpCache($kernel, new Store($this->path.'/app/cache'));
        return $kernel->handle($request);
    }
}

Add HttpCache to web application

Add HttpCache to web application


<?php
/**
 * CSP
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2014 Kenji Suzuki
 * @link       https://github.com/kenjis/php-csp-nonce-source
 */

class Csp
{
    private static $nonce;

    private static function generateNonce()
    {
        $length = 16;

        $bytes = '';
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes($length, $usable);
            if ($usable === false) {
                // weak
            }
        } else {
            throw new Exception('Can\'t use openssl_random_pseudo_bytes');
        }

        static::$nonce = base64_encode($bytes);
    }

    public static function setHeader()
    {
        if (static::$nonce === null) {
            static::generateNonce();
        }

        header("Content-Security-Policy: unsafe-inline; script-src 'nonce-" . static::$nonce . "'");
    }

    public static function getNonce()
    {
        if (static::$nonce === null) {
            static::generateNonce();
        }

        return static::$nonce;
    }
}

<?php
/**
 * CSP
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2014 Kenji Suzuki
 * @link       https://github.com/kenjis/php-csp-nonce-source
 */

class Csp
{
    private static $nonce;

    private static function generateNonce()
    {
        $length = 16;

        $bytes = '';
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes($length, $usable);
            if ($usable === false) {
                // weak
            }
        } else {
            throw new Exception('Can\'t use openssl_random_pseudo_bytes');
        }

        static::$nonce = base64_encode($bytes);
    }

    public static function setHeader()
    {
        if (static::$nonce === null) {
            static::generateNonce();
        }

        header("Content-Security-Policy: script-src 'unsafe-inline' 'nonce-" . static::$nonce . "'");
    }

    public static function getNonce()
    {
        if (static::$nonce === null) {
            static::generateNonce();
        }

        return static::$nonce;
    }
}

Fix CSP header, but Firefox doen't work

Fix CSP header, but Firefox doen't work


<?php
namespace Concrete\Core\Routing;
use Response;
use Request;
class ClosureRouteCallback extends RouteCallback {

	public function execute(Request $request, \Concrete\Core\Routing\Route $route, $parameters) {
		$r = new Response();
		$r->setContent($this->callback->__invoke());
		return $r;
	}

	public function __sleep() {
		unset($this->callback);
	}

	public static function getRouteAttributes($callback) {
		$callback = new static($callback);
		return array('callback' => $callback);
	}

}

<?php
namespace Concrete\Core\Routing;
use Symfony\Component\HttpKernel;
use Response;
use Request;

class ClosureRouteCallback extends RouteCallback {

	public function execute(Request $request, \Concrete\Core\Routing\Route $route, $parameters) {
		$resolver = new HttpKernel\Controller\ControllerResolver();
		$arguments = $resolver->getArguments($request, $this->callback);
		$r = new Response();
		$r->setContent(call_user_func_array($this->callback, $arguments));
		return $r;
	}

	public function __sleep() {
		unset($this->callback);
	}

	public static function getRouteAttributes($callback) {
		$callback = new static($callback);
		return array('callback' => $callback);
	}

}

Add Parameters to Route Closures

Add Parameters to Route Closures

Use 'HttpKernel\Controller\ControllerResolver::getArguments' to get the
parameter arguments mapped properly to the closure function arguments

Function arguments must have the same name as the route parameters but
can be in any order.


<?php

namespace Dota2Api\Models;

class LiveSlot extends Slot
{
    /**
     * @var int
     */
    protected $_ultimate_state;
    /**
     * @var int
     */
    protected $_ultimate_cooldown;
    /**
     * @var int
     */
    protected $_respawn_timer;
    /**
     * @var float
     */
    protected $_position_x;
    /**
     * @var float
     */
    protected $_position_y;
    /**
     * @var int
     */
    protected $_net_worth;
}

<?php

namespace Dota2Api\Models;

class LiveSlot extends Slot
{
    /**
     * @var int
     */
    protected $_ultimate_state;
    /**
     * @var int
     */
    protected $_ultimate_cooldown;
    /**
     * @var int
     */
    protected $_respawn_timer;
    /**
     * @var float
     */
    protected $_position_x;
    /**
     * @var float
     */
    protected $_position_y;
    /**
     * @var int
     */
    protected $_net_worth;

    public function getDataArray()
    {
        $data = get_object_vars($this);
        $ret = array();
        foreach ($data as $key => $value) {
            if (!is_array($value) && !is_null($value)) {
                $ret[ltrim($key, '_')] = $value;
            }
        }
        return $ret;
    }
}

Normalize all fields for live slot

Normalize all fields for live slot


<?php
require('maze_utility.php');

assert(coordinate_to_column('a1n') == 0);
assert(coordinate_to_column('b3s') == 1);
assert(coordinate_to_column('c5e') == 2);
assert(coordinate_to_column('d1s') == 3);
assert(coordinate_to_column('e4w') == 4);

assert(coordinate_to_row('a1n') == 0);
assert(coordinate_to_row('b3s') == 2);
assert(coordinate_to_row('c5e') == 4);
assert(coordinate_to_row('d1s') == 0);
assert(coordinate_to_row('e4w') == 3);

echo 'All OK.' . PHP_EOL;

<?php
require_once('maze_utility.php');

error_reporting(E_ALL);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);
assert(coordinate_to_column('a1n') == 0);
assert(coordinate_to_column('b3s') == 1);
assert(coordinate_to_column('c5e') == 2);
assert(coordinate_to_column('d1s') == 3);
assert(coordinate_to_column('e4w') == 4);

assert(coordinate_to_row('a1n') == 0);
assert(coordinate_to_row('b3s') == 2);
assert(coordinate_to_row('c5e') == 4);
assert(coordinate_to_row('d1s') == 0);
assert(coordinate_to_row('e4w') == 3);

echo 'All OK.' . PHP_EOL;

Fix maze utility test script

Fix maze utility test script


<?php
/**
 * @author Patsura Dmitry @ovr <talk@dmtry.me>
 */

/**
 * Class IndexController
 * @Path("/api/")
 */
class IndexController extends \Owl\Rest\Controller
{
    /**
     * @Get
     * @Url("/user/{id:int}/")
     */
    public function indexAction($id)
    {
        return array(
            'user' => array(
                'id' => $id
            )
        );
    }

    /**x
     * @Post
     * @Url("/user")
     */
    public function createAction()
    {
        //Create new user in db

        return true;
    }

    /**
     * @Delete
     * @Url("/user/{id:int}/")
     */
    public function deleteAction()
    {
        //Remove user from db

        return true;
    }
}

<?php
/**
 * @author Patsura Dmitry @ovr <talk@dmtry.me>
 */

/**
 * Class IndexController
 * @Path("/api/")
 */
class IndexController extends \Owl\Rest\Controller
{
    /**
     * @Get
     * @Url("/user/{id:int}/")
     */
    public function indexAction($id)
    {
        return array(
            'user' => array(
                'id' => $id
            )
        );
    }

    /**
     * @Get
     * @Url("/users")
     */
    public function listAction()
    {
        //Get users from db

        return true;
    }

    /**x
     * @Post
     * @Url("/user")
     */
    public function createAction()
    {
        //Create new user in db

        return true;
    }

    /**
     * @Delete
     * @Url("/user/{id:int}/")
     */
    public function deleteAction()
    {
        //Remove user from db

        return true;
    }
}

Write idea for rest app

Write idea for rest app


<?php
namespace Respect\Foundation\InfoProviders;

use DirectoryIterator;

class PackageName extends AbstractProvider
{
    public function providerPackageIni()
    {
        $iniPath = realpath($this->projectFolder.'/package.ini');

        if (!file_exists($iniPath))
            return '';

        $ini = parse_ini_file($iniPath, true);
        return $ini['package']['name'];
    }

    public function providerFolderStructure()
    {
        $vendorFolder  = new LibraryFolder($this->projectFolder);
        if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder)))
            foreach (new DirectoryIterator((string) $vendorFolder) as $vendor)
                if (!$vendor->isDot() && $vendor->isDir())
                    return $vendor->getFileName();
    }
}

<?php
namespace Respect\Foundation\InfoProviders;

use DirectoryIterator;

class PackageName extends AbstractProvider
{
    public function providerPackageIni()
    {
        $iniPath = realpath($this->projectFolder.'/package.ini');

        if (!file_exists($iniPath))
            return '';

        $ini = parse_ini_file($iniPath, true);
        return $ini['package']['name'];
    }

    public function providerFolderStructure()
    {
        $vendorFolder  = new LibraryFolder($this->projectFolder);
        if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder)))
            foreach (new DirectoryIterator((string) $vendorFolder) as $vendor)
                if (!$vendor->isDot() && $vendor->isDir())
                    return $vendor->getFileName();
    }

    public function providerDefault()
    {
        return ucfirst(preg_replace('#^.*'.DIRECTORY_SEPARATOR.'(?=\w$)#U', '', $this->projectFolder));
    }
}

Add default value for package name.

Add default value for package name.

If all else fails assume the name of the current folder is the packoge name.


<?php

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

class ImportAllCategoriesAgain extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Artisan::call('import:collections-full', ['endpoint' => 'categories']);
    }

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

<?php

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

class ImportAllCategoriesAgain extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Remove experimental migration
        //Artisan::call('import:collections-full', ['endpoint' => 'categories']);
    }

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

Remove experimental migration that called Artisan command


<?php

HuradWidget::registerSidebar(array('name' => __('Right Sidebar')));
HuradWidget::registerSidebar(array('name' => __('Left Sidebar')));

HuradWidget::registerWidget(array(
    'title' => __('Authors'),
    'element' => 'authors',
        )
);
HuradWidget::registerWidget(array(
    'title' => __('Categories'),
    'element' => 'categories',
        )
);
HuradWidget::registerWidget(array(
    'title' => __('Recent Posts'),
    'element' => 'recent_posts',
        )
);
HuradWidget::registerWidget(array(
    'title' => __('Pages'),
    'element' => 'pages',
        )
);

Move register default widget to app/Config/Hurad/default_widgets.php


<?php

namespace App\Policies;

use App\Models\Reply;
use App\User;

class ReplyPolicy
{
    const CREATE = 'create';
    const UPDATE = 'update';
    const DELETE = 'delete';

    /**
     * Determine if replies can be created by the user.
     */
    public function create(User $user): bool
    {
        // We only need to be logged in.
        return true;
    }

    /**
     * Determine if the given reply can be updated by the user.
     */
    public function update(User $user, Reply $reply): bool
    {
        return $reply->isAuthoredBy($user);
    }

    /**
     * Determine if the given reply can be deleted by the user.
     */
    public function delete(User $user, Reply $reply): bool
    {
        return $reply->isAuthoredBy($user);
    }
}

<?php

namespace App\Policies;

use App\Models\Reply;
use App\User;

class ReplyPolicy
{
    const CREATE = 'create';
    const UPDATE = 'update';
    const DELETE = 'delete';

    /**
     * Determine if replies can be created by the user.
     */
    public function create(User $user): bool
    {
        // We only need to be logged in.
        return true;
    }

    /**
     * Determine if the given reply can be updated by the user.
     */
    public function update(User $user, Reply $reply): bool
    {
        return $reply->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin();
    }

    /**
     * Determine if the given reply can be deleted by the user.
     */
    public function delete(User $user, Reply $reply): bool
    {
        return $reply->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin();
    }
}

Allow moderators and admins to modify replies


<?php
namespace verbb\navigation\migrations;

use verbb\navigation\elements\Node;

use Craft;
use craft\db\Migration;

class m181113_000000_add_paginationNode extends Migration
{
    public function safeUp()
    {
        $this->addColumn('{{%feedme_feeds}}', 'paginationNode', $this->text()->after('duplicateHandle'));

        return true;
    }

    public function safeDown()
    {
        echo "m181113_000000_add_paginationNode cannot be reverted.\n";

        return false;
    }
}

<?php
namespace verbb\feedme\migrations;

use Craft;
use craft\db\Migration;

class m181113_000000_add_paginationNode extends Migration
{
    public function safeUp()
    {
        if (!$this->db->columnExists('{{%feedme_feeds}}', 'paginationNode')) {
            $this->addColumn('{{%feedme_feeds}}', 'paginationNode', $this->text()->after('duplicateHandle'));
        }

        return true;
    }

    public function safeDown()
    {
        echo "m181113_000000_add_paginationNode cannot be reverted.\n";

        return false;
    }
}

Fix conflict with Navigation plugin migration


<?php
/*
 * This file is part of Sesshin library.
 *
 * (c) Przemek Sobstel <http://sobstel.org>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sesshin\EntropyGenerator;
use Sesshin\Exception;

class File implements EntropyGeneratorInterface {

  private $file;
  private $length;

  public function __construct($file = '/dev/urandom', $length = 512) {
    $this->file = $file;
    $this->length = $length;
  }

  public function generate() {
    $entropy = file_get_contents($this->file, false, null, 0, $this->length);
		if ($entropy === false) {
			throw new Exception('Entropy file is empty.');
		}
		return $entropy;
  }

}

<?php
/*
 * This file is part of Sesshin library.
 *
 * (c) Przemek Sobstel <http://sobstel.org>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sesshin\EntropyGenerator;
use Sesshin\Exception;

class File implements EntropyGeneratorInterface {

  private $file;
  private $length;

  public function __construct($file = '/dev/urandom', $length = 512) {
    $this->file = $file;
    $this->length = $length;
  }

  public function generate() {
    $entropy = file_get_contents($this->file, false, null, 0, $this->length);
		if (empty($entropy)) {
			throw new Exception('Entropy file is empty.');
		}
		return $entropy;
  }

}

Fix file entropy generator: throw exception if file contents empty.


<?php namespace Limoncello\Application\Authorization;

/**
 * Copyright 2015-2018 info@neomerx.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @package Limoncello\Application
 */
class ContextProperties extends RequestProperties
{
    /** Context key */
    const CTX_CONTAINER = self::REQ_LAST + 1;

    /** Context key */
    const CTX_LAST = self::CTX_CONTAINER + 1;
}

<?php namespace Limoncello\Application\Authorization;

/**
 * Copyright 2015-2018 info@neomerx.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @package Limoncello\Application
 */
class ContextProperties extends RequestProperties
{
    /** Context key */
    const CTX_CONTAINER = self::REQ_LAST + 1;

    /** Context key */
    const CTX_LAST = self::CTX_CONTAINER;
}

Remove unnecessary increment for the last key.


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

use PHPUnit\Framework\TestCase;

final class MigrationTest extends TestCase
{
    /**
     * @testdox Migrates PHPUnit 9.2 configuration to PHPUnit 9.3
     */
    public function testMigratesPhpUnit92ConfigurationToPhpUnit93(): void
    {
        $this->assertStringEqualsFile(
            __DIR__ . '/../../_files/XmlConfigurationMigration/output-9.3.xml',
            (new Migrator)->migrate(
                __DIR__ . '/../../_files/XmlConfigurationMigration/input-9.2.xml'
            )
        );
    }
}

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

use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Xml;

final class MigrationTest extends TestCase
{
    /**
     * @testdox Migrates PHPUnit 9.2 configuration to PHPUnit 9.3
     */
    public function testMigratesPhpUnit92ConfigurationToPhpUnit93(): void
    {
        $this->assertEquals(
            Xml::loadFile(__DIR__ . '/../../_files/XmlConfigurationMigration/output-9.3.xml'),
            Xml::load(
                (new Migrator)->migrate(
                    __DIR__ . '/../../_files/XmlConfigurationMigration/input-9.2.xml'
                )
            )
        );
    }
}

Use assertEquals() instead of assertStringEqualsFile() in order to compare XML documents with C14N


<?php
namespace ADesigns\CalendarBundle\Tests\Fixtures\EventListener;

use ADesigns\CalendarBundle\Entity\EventEntity;
use ADesigns\CalendarBundle\Event\CalendarEvent;

/**
 * Loads a fake event for testing purposes.
 *
 * @package ADesigns\CalendarBundle\Tests\Fixtures\EventListener
 */
class CalendarEventListener
{
    const TEST_START_TIME = "2016-01-15 13:00";
    const TEST_END_TIME = "2016-01-15 14:00";
    public function loadEvents(CalendarEvent $calendarEvent)
    {
        // these
        $startTime = new \DateTime(self::TEST_START_TIME);
        $endTime = new \DateTime(self::TEST_END_TIME);

        if ($calendarEvent->getStartDatetime()->getTimestamp() === $startTime->getTimestamp()
            && $calendarEvent->getEndDatetime()->getTimestamp() === $endTime->getTimestamp()) {
            $event = new EventEntity("Fake Event Title", new \DateTime(), null, true);
            $calendarEvent->addEvent($event);
        }

    }
}

<?php
namespace ADesigns\CalendarBundle\Tests\Fixtures\EventListener;

use ADesigns\CalendarBundle\Entity\EventEntity;
use ADesigns\CalendarBundle\Event\CalendarEvent;

/**
 * Loads a fake event for testing purposes.
 *
 * @package ADesigns\CalendarBundle\Tests\Fixtures\EventListener
 */
class CalendarEventListener
{
    const TEST_START_TIME = "2016-01-15 13:00";
    const TEST_END_TIME = "2016-01-15 14:00";

    public function loadEvents(CalendarEvent $calendarEvent)
    {

        $startTime = new \DateTime(self::TEST_START_TIME);
        $endTime = new \DateTime(self::TEST_END_TIME);

        if ($calendarEvent->getStartDatetime()->getTimestamp() === $startTime->getTimestamp()
            && $calendarEvent->getEndDatetime()->getTimestamp() === $endTime->getTimestamp()) {
            $event = new EventEntity("Fake Event Title", new \DateTime(), null, true);
            $calendarEvent->addEvent($event);
        }

    }
}

Remove comment line / add whitespace.

Remove comment line / add whitespace.


<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// Check if we are a user
OCP\User::checkLoggedIn();
\OC::$server->getSession()->close();

$files = $_GET["files"];
$dir = $_GET["dir"];

$files_list = json_decode($files);
// in case we get only a single file
if (!is_array($files_list)) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD');

<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// Check if we are a user
OCP\User::checkLoggedIn();
\OC::$server->getSession()->close();

$files = isset($_GET['files']) ? $_GET['files'] : '';
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';

$files_list = json_decode($files);
// in case we get only a single file
if (!is_array($files_list)) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD');

Check for existence of $_GET keys

Check for existence of $_GET keys

`$dir` may for example very well not get passed at well.


<?php

namespace Concrete\Core\Sharing\ShareThisPage;

class ServiceList
{
    protected static function getServices()
    {
        return array(
            array('facebook', 'Facebook', 'facebook'),
            array('twitter', 'Twitter', 'twitter'),
            array('linkedin', 'LinkedIn', 'linkedin-in'),
            array('reddit', 'Reddit', 'reddit'),
            array('pinterest', 'Pinterest', 'pinterest'),
            array('google_plus', 'Google Plus', 'google-plus'),
            array('print', t('Print'), 'print', ''),
            array('email', 'Email', 'envelope', ''),
        );
    }

    public static function get()
    {
        $services = [];

        foreach (static::getServices() as $serviceArray) {
            $ssHandle = isset($serviceArray[0]) ? $serviceArray[0] : null;
            $ssName = isset($serviceArray[1]) ? $serviceArray[1] : null;
            $ssIcon = isset($serviceArray[2]) ? $serviceArray[2] : null;
            $customHTML = isset($serviceArray[3]) ? $serviceArray[3] : null;

            $service = new Service($ssHandle, $ssName, $ssIcon, $customHTML);

            $services[] = $service;
        }

        return $services;
    }
}

<?php

namespace Concrete\Core\Sharing\ShareThisPage;

class ServiceList
{
    protected static function getServices()
    {
        return array(
            array('facebook', 'Facebook', 'fab fa-facebook'),
            array('twitter', 'Twitter', 'fab fa-twitter'),
            array('linkedin', 'LinkedIn', 'fab fa-linkedin'),
            array('reddit', 'Reddit', 'fab fa-reddit'),
            array('pinterest', 'Pinterest', 'fab fa-pinterest'),
            array('google_plus', 'Google Plus', 'fab fa-google-plus-square'),
            array('print', t('Print'), 'print', ''),
            array('email', 'Email', 'envelope', ''),
        );
    }

    public static function get()
    {
        $services = [];

        foreach (static::getServices() as $serviceArray) {
            $ssHandle = isset($serviceArray[0]) ? $serviceArray[0] : null;
            $ssName = isset($serviceArray[1]) ? $serviceArray[1] : null;
            $ssIcon = isset($serviceArray[2]) ? $serviceArray[2] : null;
            $customHTML = isset($serviceArray[3]) ? $serviceArray[3] : null;

            $service = new Service($ssHandle, $ssName, $ssIcon, $customHTML);

            $services[] = $service;
        }

        return $services;
    }
}

Fix icon class of share this page services

Use same icon class with social network icon classes


<?php
use Maghead\Utils\ArrayUtils;

/**
 * @group utils
 */
class ArrayUtilsTest extends PHPUnit\Framework\TestCase
{
    public function testAssocArrayCheck()
    {
        $a = array(
            'a' => 'b',
            '0' => '1',
        );
        ok(ArrayUtils::is_assoc_array($a));

        $a = array(
            'foo' => 'b',
            'bar' => '1',
        );
        ok(ArrayUtils::is_assoc_array($a));
    }

    public function testIndexedArrayCheck()
    {
        $a = array(
            0 => 'foo',
            1 => 'bar',
        );
        ok(ArrayUtils::is_indexed_array($a));

        $a = array(
            'a' => 'foo',
            1 => 'bar',
        );
        not_ok(ArrayUtils::is_indexed_array($a));

        $a = array(
            'a' => 'foo',
            1 => 'bar',
        );
        not_ok(ArrayUtils::is_indexed_array($a));
    }
}

<?php
use Maghead\Utils\ArrayUtils;

/**
 * @group utils
 */
class ArrayUtilsTest extends PHPUnit\Framework\TestCase
{
    public function testAssocArrayCheck()
    {
        $a = array(
            'a' => 'b',
            '0' => '1',
        );
        $this->assertTrue(ArrayUtils::is_assoc_array($a));

        $a = array(
            'foo' => 'b',
            'bar' => '1',
        );
        $this->assertTrue(ArrayUtils::is_assoc_array($a));
    }

    public function testIndexedArrayCheck()
    {
        $a = array(
            0 => 'foo',
            1 => 'bar',
        );
        $this->assertTrue(ArrayUtils::is_indexed_array($a));

        $a = array(
            'a' => 'foo',
            1 => 'bar',
        );
        $this->assertFalse(ArrayUtils::is_indexed_array($a));

        $a = array(
            'a' => 'foo',
            1 => 'bar',
        );
        $this->assertFalse(ArrayUtils::is_indexed_array($a));
    }
}

Fix the final assertion API upgrade for PHPUnit