<?php

namespace ContainerTools\Configuration;

use ContainerTools\Configuration;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class Loader
{
    /**
     * @var array
     */
    private $serviceConfigs;

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

    /**
     * @param Configuration $configuration
     *
     * @return $this
     */
    public function load(Configuration $configuration)
    {
        $this->serviceConfigs = $configuration->getServicesFolders();
        $this->servicesFormat = $configuration->getServicesFormat();

        return $this;
    }

    /**
     * @param ContainerBuilder $containerBuilder
     */
    public function into(ContainerBuilder $containerBuilder)
    {
        $loader = new XmlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs));

        $loader->load('services.' . $this->servicesFormat);
    }
}

<?php

namespace ContainerTools\Configuration;

use ContainerTools\Configuration;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class Loader
{
    /**
     * @var array
     */
    private $serviceConfigs;

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

    /**
     * @param Configuration $configuration
     *
     * @return $this
     */
    public function load(Configuration $configuration)
    {
        $this->serviceConfigs = $configuration->getServicesFolders();
        $this->servicesFormat = $configuration->getServicesFormat();

        return $this;
    }

    /**
     * @param ContainerBuilder $containerBuilder
     */
    public function into(ContainerBuilder $containerBuilder)
    {
        $loader = new DelegatingLoader(new LoaderResolver(array(
            new XmlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs)),
            new YamlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs)),
        )));

        $loader->load('services.' . $this->servicesFormat);
    }
}

Allow for multiple service file formats

Allow for multiple service file formats


<?php namespace Spatie\Activitylog\Models;

use Eloquent;
use DateTime;

class Activity extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'activity_log';

    /**
     * Get the user that the activity belongs to.
     *
     * @return object
     */
    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }

    protected $guarded = array('id');

    public $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::saving(function($activity) {
            $activity->created_at = new DateTime();
        });
    }
}

<?php namespace Spatie\Activitylog\Models;

use Eloquent;
use DateTime;
use Config;

class Activity extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'activity_log';

    /**
     * Get the user that the activity belongs to.
     *
     * @return object
     */
    public function user()
    {
        return $this->belongsTo(Config::get('auth.model'), 'user_id');
    }

    protected $guarded = array('id');

    public $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::saving(function($activity) {
            $activity->created_at = new DateTime();
        });
    }
}

Add support for namespaced user model

Add support for namespaced user model


<?php

function theme_enqueue_styles() {

    $parent_style = 'parent-style';

    wp_enqueue_script( 'jquery' );
    wp_enqueue_style( 'bootstrap-css', get_stylesheet_directory_uri().'/bootstrap/css/bootstrap.css' );
    wp_enqueue_script( 'bootstrap-js', get_stylesheet_directory_uri().'/bootstrap/js/bootstrap.js' );
    wp_enqueue_script( 'backbone' );
    wp_enqueue_script( 'app-js', get_stylesheet_directory_uri().'/scripts/app.js' );

    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css'
    );

    wp_enqueue_style('theme-extra',
    	get_stylesheet_directory_uri().'/styles/custom.less',
    	array( $parent_style )
    );

}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', 'theme_enqueue_scripts' );

/* Removes jQuery Migrate dependency console log */
add_action( 'wp_default_scripts', function( $scripts ) {
    if ( ! empty( $scripts->registered['jquery'] ) ) {
        $jquery_dependencies = $scripts->registered['jquery']->deps;
        $scripts->registered['jquery']->deps = array_diff( $jquery_dependencies, array( 'jquery-migrate' ) );
    }
} );

?>

<?php

function theme_enqueue_styles() {

    $parent_style = 'parent-style';

    wp_enqueue_script( 'jquery' );
    wp_enqueue_style( 'bootstrap-css', get_stylesheet_directory_uri().'/bootstrap/css/bootstrap.css' );
    wp_enqueue_script( 'bootstrap-js', get_stylesheet_directory_uri().'/bootstrap/js/bootstrap.js' );
    wp_enqueue_script( 'backbone' );

    if ( is_page( 'Participants', 'series' ) ) {
        wp_enqueue_script( 'app-js', get_stylesheet_directory_uri().'/scripts/app.js' );
    };

    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css'
    );

    wp_enqueue_style('theme-extra',
    	get_stylesheet_directory_uri().'/styles/custom.less',
    	array( $parent_style )
    );

}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', 'theme_enqueue_scripts' );

/* Removes jQuery Migrate dependency console log */
add_action( 'wp_default_scripts', function( $scripts ) {
    if ( ! empty( $scripts->registered['jquery'] ) ) {
        $jquery_dependencies = $scripts->registered['jquery']->deps;
        $scripts->registered['jquery']->deps = array_diff( $jquery_dependencies, array( 'jquery-migrate' ) );
    }
} );

?>

Load Backbone app on selective pages

Load Backbone app on selective pages


<?php

namespace Enzyme\LaravelBinder;

use Illuminate\Contracts\Container\Container;

class Binder
{
    protected $container;
    protected $bindings;
    protected $requesters;
    protected $dependencies;

    public function __construct(Container $container)
    {
        $this->container = $container;
        $this->bindings = [];
    }

    public function setRequesters(array $requesters)
    {
        //
    }

    public function setBindings(array $bindings)
    {
        //
    }

    public function setDependencies(array $dependencies)
    {
        //
    }

    public function register()
    {
        foreach ($this->dependencies as $base => $dependencies) {
            $base_fqn = $this->requesters[$base];

            foreach ($dependencies as $dependency) {
                $dependency_fqn = $this->bindings[$dependency]['fqn'];
                $binding = $this->bindings[$dependency]['binding'];

                $this
                    ->container
                    ->when($base_fqn)
                    ->needs($dependency_fqn)
                    ->give($binding);
            }
        }
    }
}

<?php

namespace Enzyme\LaravelBinder;

use Illuminate\Contracts\Container\Container;

class Binder
{
    protected $container;
    protected $bindings;
    protected $aliases;
    protected $needs;

    public function __construct(Container $container)
    {
        $this->container = $container;
        $this->bindings = [];
    }

    public function setAlias($alias, $fqn)
    {
        $this->aliases[$alias] = $fqn;
    }

    public function setBinding($alias, $interface, $concrete)
    {
        $this->bindings[$alias] = [
            'interface' => $interface,
            'concrete'  => $concrete,
        ];
    }

    public function setNeeds($alias, array $needs)
    {
        $this->needs[$alias] = $needs;
    }

    public function register()
    {
        foreach ($needs as $parent => $dependencies) {
            $this->registerDependencies($this->aliases[$parent], $dependencies);
        }
    }

    protected function registerDependencies($parent_fqn, $dependencies)
    {
        foreach ($dependencies as $dependency) {
            $dependency_fqns = $this->bindings[$dependency];

            $this
                ->container
                ->when($parent_fqn)
                ->needs($dependency_fqns['interface'])
                ->give($dependency_fqns['concrete']);
        }
    }
}

Implement missing methods and functionality.


<?php
namespace Lawstands\Hermes;

class Channel
{
    /**
     * Channel command.
     *
     * @var $command
     */
    private $command;

    /**
     * Channel constructor.
     * @param array $config
     * @param $data
     * @param bool $async
     */
    public function __construct(array $config, $data, $async = true)
    {
        $data = self::formatData($data, $config['formatter']);
        $this->buildCommand($config, $data, $async);
    }

    /**
     * Execute channel command.
     *
     * @return string
     */
    public function execute()
    {
        return shell_exec($this->command);
    }

    /**
     * Build channel command.
     *
     * @param $config
     * @param $data
     * @param $async
     * @return string
     */
    private function buildCommand($config, $data, $async)
    {
        $redirect = $async ? '&>/dev/null' : '';
        $this->command = "{$config['type']} {$config['path']} {$data} {$redirect}";
    }

    /**
     * Format channel data.
     *
     * @param $data
     * @param $formatter
     * @return mixed
     */
    private static function formatData($data, $formatter)
    {
        $formatter = new $formatter;
        return $formatter->format($data);
    }
}

<?php
namespace Lawstands\Hermes;

class Channel
{
    /**
     * Channel command.
     *
     * @var $command
     */
    private $command;

    /**
     * Channel constructor.
     * @param array $config
     * @param $data
     * @param bool $async
     */
    public function __construct(array $config, $data, $async = true)
    {
        $data = self::formatData($data, $config['formatter']);
        $this->buildCommand($config['type'], $config['path'], $data, $async);
    }

    /**
     * Execute channel command.
     *
     * @return string
     */
    public function execute()
    {
        return shell_exec($this->command);
    }

    /**
     * Build channel command.
     *
     * @param $type
     * @param $path
     * @param $data
     * @param $async
     * @return string
     */
    private function buildCommand($type, $path, $data, $async)
    {
        $redirect = $async ? '&>/dev/null' : '';
        $this->command = "{$type} {$path} {$data} {$redirect}";
    }

    /**
     * Format channel data.
     *
     * @param $data
     * @param $formatter
     * @return mixed
     */
    private static function formatData($data, $formatter)
    {
        $formatter = new $formatter;
        return $formatter->format($data);
    }
}

Remove config access from buildCommand

Remove config access from buildCommand


<?php
	namespace Bolt;

	use Bolt\Api\Response;

	class Handler
	{
		public static function error($level, $message, $file, $line, $context)
		{
			throw new Exceptions\Error($message, 0, $level, $file, $line);
		}

		public static function exception($exception)
		{
			$className = get_class($exception);

			$type = $className;

			if ($exception instanceof Exception)
			{
				$type .= "::" . $exception->getCodeKey();
			}

			if (DEPLOYMENT === Deployment::PRODUCTION)
			{
				$data = $type;
			}
			else
			{
				$data = array(
					"type" => $type,
					"message" => $exception->getMessage(),
					"code" => $exception->getCode(),
					"line" => $exception->getLine(),
					"file" => $exception->getFile(),
					"trace" => $exception->getTrace()
				);
			}

			if (php_sapi_name() == "cli")
			{
				if (!is_string($data))
				{
					$data = json_encode($data, JSON_PRETTY_PRINT);
				}

				echo($data . "\n");
			}
			else
			{
				$response = new Response();
				$response->status(500, $data);
			}

			return true;
		}
	}
?>

<?php
	namespace Bolt;

	use Bolt\Api\Response;
	use Bolt\Exceptions\Output;

	class Handler
	{
		public static function error($level, $message, $file, $line, $context)
		{
			throw new Exceptions\Error($message, 0, $level, $file, $line);
		}

		public static function exception($exception)
		{
			$className = get_class($exception);

			$type = $className;

			if ($exception instanceof Exception)
			{
				$type .= "::" . $exception->getCodeKey();
			}

			if ($exception instanceof Output)
			{
				$data = $exception->getMessage();
			}
			elseif (DEPLOYMENT === Deployment::PRODUCTION)
			{
				$data = $type;
			}
			else
			{
				$data = array(
					"type" => $type,
					"message" => $exception->getMessage(),
					"code" => $exception->getCode(),
					"line" => $exception->getLine(),
					"file" => $exception->getFile(),
					"trace" => $exception->getTrace()
				);
			}

			if (php_sapi_name() == "cli")
			{
				if (!is_string($data))
				{
					$data = json_encode($data, JSON_PRETTY_PRINT);
				}

				echo($data . "\n");
			}
			else
			{
				$response = new Response();
				$response->status(500, $data);
			}

			return true;
		}
	}
?>

Update handler to output api response with Output exceptions


<?php

namespace Encore\Error;

use Symfony\Component\Debug\ErrorHandler;
use Encore\Container\Container;

class Handler
{
	protected $container = null;

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

	public function setContainer(Container $container)
	{
		$this->container = $container;
	}

	public function register()
	{
		$this->registerErrorHandler();
		$this->registerExceptionHandler();
	}

	protected function registerErrorHandler()
	{
		ErrorHandler::register(E_ALL);
	}

	protected function registerExceptionHandler()
	{
		ExceptionHandler::register(true, $this->container)
			->setDisplayer($this->displayer);
	}
}

<?php

namespace Encore\Error;

use Symfony\Component\Debug\ErrorHandler;
use Encore\Container\ContainerAwareInterface;
use Encore\Container\ContainerAwareTrait;

class Handler implements ContainerAwareInterface
{
	use ContainerAwareTrait;

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

	public function register()
	{
		$this->registerErrorHandler();
		$this->registerExceptionHandler();
	}

	protected function registerErrorHandler()
	{
		ErrorHandler::register(E_ALL);
	}

	protected function registerExceptionHandler()
	{
		ExceptionHandler::register(true, $this->container)
			->setDisplayer($this->displayer);
	}
}

Implement ContainerAwareInterface and use ContainerAwareTrait


<?php

use Illuminate\Database\Seeder;

class VehiclesFuelsTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('vehicles_fuels')->delete();

        $fuels = [
            ['name' => 'Gasolina', 'regex' => '/\bgasolina\b/i'],
            ['name' => 'Diesel', 'regex' => '/\bgas[oó]leo\b/iu'],
            ['name' => 'GPL', 'regex' => '/\bgpl|g[aá]s\b/iu'],
            ['name' => 'Híbrido', 'regex' => '/\bh[íi]brido\b/iu'],
            ['name' => 'Eléctrico', 'regex' => '/\bel[ée]c?trico\b/iu'],
        ];

        DB::table('vehicles_fuels')->insert($fuels);
    }
}

<?php

use Illuminate\Database\Seeder;

class VehiclesFuelsTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('vehicles_fuels')->delete();

        $fuels = [
            ['name' => 'Gasolina', 'regex' => '/\bgasolina\b/i'],
            ['name' => 'Diesel', 'regex' => '/\bdiesel|gas[oó]leo\b/iu'],
            ['name' => 'GPL', 'regex' => '/\bgpl|g[aá]s\b/iu'],
            ['name' => 'Híbrido', 'regex' => '/\bh[íi]brido\b/iu'],
            ['name' => 'Eléctrico', 'regex' => '/\bel[ée]c?trico\b/iu'],
        ];

        DB::table('vehicles_fuels')->insert($fuels);
    }
}

Update regex for diesel fuel

Update regex for diesel fuel


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

namespace Drupal\AppConsole\Generator;

class PluginBlockGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  $module
   * @param  $class_name
   * @param  $plugin_label
   * @param  $plugin_id
   * @param  $services
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
  {

    $parameters = [
      'module'   => $module,
      'class'     => [
        'name'      => $class_name,
        'underscore' => $this->camelCaseToUnderscore($class_name)
      ],
      'plugin_label' => $plugin_label,
      'plugin_id' => $plugin_id,
      'services'    => $services,
    ];

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

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

namespace Drupal\AppConsole\Generator;

class PluginBlockGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  $module
   * @param  $class_name
   * @param  $plugin_label
   * @param  $plugin_id
   * @param  $services
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
  {

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

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

Rename argument, remove unusued one

Rename argument, remove unusued one


<?php
/**
 * Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC_JSON::checkAdminUser();

$count=(isset($_GET['count']))?$_GET['count']:50;
$offset=(isset($_GET['offset']))?$_GET['offset']:0;

$entries=OC_Log_Owncloud::getEntries($count, $offset);
$data = array();

OC_JSON::success(
	array(
		"data" => $entries,
		"remain" => count(OC_Log_Owncloud::getEntries(1, $offset + $count)) !== 0
	)
);

<?php
/**
 * Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC_JSON::checkAdminUser();

$count=(isset($_GET['count']))?$_GET['count']:50;
$offset=(isset($_GET['offset']))?$_GET['offset']:0;

$entries=OC_Log_Owncloud::getEntries($count, $offset);
$data = array();

OC_JSON::success(
	array(
		"data" => $entries,
		"remain" => count(OC_Log_Owncloud::getEntries(1, $offset + $count)) !== 0,
	)
);

Add trailing comma for all touched array lines.


<?php

namespace Asvae\ApiTester\Providers;

use Illuminate\Routing\Router;

class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
    /**
     * Define the routes for the application.
     *
     * Module
     * ├ Http
     * │ └ routes.php
     * │
     * └ Providers
     *    └ [static]
     *
     * @param  Router $router
     *
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->getNamespace()], function () {
            $this->requireRoutes();
        });
    }

    public function boot(Router $router)
    {
        parent::boot($router);

        $this->loadViewsFrom(__DIR__.'/../resources/assets/views', 'api-tester');
        $this->publishes([
            __DIR__.'/../resources/assets/build' => public_path('vendor/api-tester'),
        ], 'public');
    }

    /**
     * Get module namespace
     *
     * @return string
     */
    protected function getNamespace()
    {
        return 'Asvae\ApiTester\Http\Controllers';
    }

    /**
     * @return string
     */
    protected function requireRoutes()
    {
        require __DIR__.'/../Http/routes.php';
    }
}

<?php

namespace Asvae\ApiTester\Providers;

use Illuminate\Routing\Router;

class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
    /**
     * Define the routes for the application.
     *
     * Module
     * ├ Http
     * │ └ routes.php
     * │
     * └ Providers
     *    └ [static]
     *
     * @param  Router $router
     *
     * @return void
     */
    public function map(Router $router)
    {
        $router->group([
            'namespace' => $this->getNamespace(),
            'middleware' => ['web'],
        ], function () {
            $this->requireRoutes();
        });
    }

    public function boot(Router $router)
    {
        parent::boot($router);

        $this->loadViewsFrom(__DIR__.'/../resources/assets/views', 'api-tester');
        $this->publishes([
            __DIR__.'/../resources/assets/build' => public_path('vendor/api-tester'),
        ], 'public');
    }

    /**
     * Get module namespace
     *
     * @return string
     */
    protected function getNamespace()
    {
        return 'Asvae\ApiTester\Http\Controllers';
    }

    /**
     * @return string
     */
    protected function requireRoutes()
    {
        require __DIR__.'/../Http/routes.php';
    }
}

Set web middleware to get token

Set web middleware to get token


<?php

namespace Drubo\Robo\Task\Filesystem;

use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Files;

trait loadTasks {

  /**
   * Clean filesystem directories.
   *
   * @return \Drubo\Robo\Task\Filesystem\Clean\Directories
   */
  protected function taskFilesystemCleanDirectories() {
    return $this->task(CleanDicrectories::class);
  }

  /**
   * Prepare filesystem directories.
   *
   * @return \Drubo\Robo\Task\Filesystem\Prepare\Directories
   */
  protected function taskFilesystemPrepareDirectories() {
    return $this->task(PrepareDicrectories::class);
  }

  /**
   * Prepare filesystem files.
   *
   * @return \Drubo\Robo\Task\Filesystem\Prepare\Files
   */
  protected function taskFilesystemPrepareFiles() {
    return $this->task(Files::class);
  }

}

<?php

namespace Drubo\Robo\Task\Filesystem;

use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDirectories;
use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Files;

trait loadTasks {

  /**
   * Clean filesystem directories.
   *
   * @return \Drubo\Robo\Task\Filesystem\Clean\Directories
   */
  protected function taskFilesystemCleanDirectories() {
    return $this->task(CleanDirectories::class);
  }

  /**
   * Prepare filesystem directories.
   *
   * @return \Drubo\Robo\Task\Filesystem\Prepare\Directories
   */
  protected function taskFilesystemPrepareDirectories() {
    return $this->task(PrepareDicrectories::class);
  }

  /**
   * Prepare filesystem files.
   *
   * @return \Drubo\Robo\Task\Filesystem\Prepare\Files
   */
  protected function taskFilesystemPrepareFiles() {
    return $this->task(Files::class);
  }

}

Fix typo in use statement

Fix typo in use statement


<?php

/*
 * This file is part of flagrow/upload.
 *
 * Copyright (c) Flagrow.
 *
 * http://flagrow.github.io
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

namespace Flagrow\Upload\Adapters;

use Flagrow\Upload\Contracts\UploadAdapter;
use Flagrow\Upload\File;
use Illuminate\Support\Arr;

class AwsS3 extends Flysystem implements UploadAdapter
{
    /**
     * @param File $file
     */
    protected function generateUrl(File $file)
    {
        $region = $this->adapter->getClient()->getRegion();
        $bucket = $this->adapter->getBucket();

        $baseUrl = in_array($region, [null, 'us-east-1']) ?
            sprintf('http://%s.s3-website-us-east-1.amazonaws.com/', $bucket) :
            sprintf('http://%s.s3-website-%s.amazonaws.com/', $bucket, $region);

        $file->url = sprintf(
            $baseUrl . '%s',
            Arr::get($this->meta, 'path', $file->path)
        );
    }
}

<?php

/*
 * This file is part of flagrow/upload.
 *
 * Copyright (c) Flagrow.
 *
 * http://flagrow.github.io
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

namespace Flagrow\Upload\Adapters;

use Flagrow\Upload\Contracts\UploadAdapter;
use Flagrow\Upload\File;
use Illuminate\Support\Arr;

class AwsS3 extends Flysystem implements UploadAdapter
{
    /**
     * @param File $file
     */
    protected function generateUrl(File $file)
    {
        $region = $this->adapter->getClient()->getRegion();
        $bucket = $this->adapter->getBucket();

        $baseUrl = in_array($region, [null, 'us-east-1']) ?
            sprintf('https://%s.s3-website-us-east-1.amazonaws.com/', $bucket) :
            sprintf('https://%s.s3-website-%s.amazonaws.com/', $bucket, $region);

        $file->url = sprintf(
            $baseUrl . '%s',
            Arr::get($this->meta, 'path', $file->path)
        );
    }
}

Use https for s3 links

Use https for s3 links


<?php
/**
 * @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
 *    Confidential and Proprietary. Any dissemination outside of Quicken Loans
 *    is strictly prohibited.
 */

namespace MCP\Cache;

/**
 * @api
 */
interface CacheInterface
{
    /**
     * @param string $key
     *
     * @return mixed|null
     */
    public function get($key);

    /**
     * Returns true if the data was stored.
     *
     * @param string $key
     * @param mixed $value Anything not a resource
     * @param int $ttl How long the data should live, in seconds
     *
     * @return boolean
     */
    public function set($key, $value, $ttl = 0);
}

<?php
/**
 * @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
 *    Confidential and Proprietary. Any dissemination outside of Quicken Loans
 *    is strictly prohibited.
 */

namespace MCP\Cache;

/**
 * @api
 */
interface CacheInterface
{
    const VERSION = '3.0.0';

    /**
     * @param string $key
     *
     * @return mixed|null
     */
    public function get($key);

    /**
     * Returns true if the data was stored.
     *
     * @param string $key
     * @param mixed $value Anything not a resource
     * @param int $ttl How long the data should live, in seconds
     *
     * @return boolean
     */
    public function set($key, $value, $ttl = 0);
}

Add version const to cache interface

Add version const to cache interface


<?php namespace SublimeArts\SublimeStripe\Tests\Http\Controllers;

use PluginTestCase;
use SublimeArts\SublimeStripe\Http\Controllers\WebhooksController;

class WebhooksControllerTest extends PluginTestCase
{

    protected $baseUrl = 'http://nasmei.org.dev';

    /** @test */
    public function it_converts_a_stripe_event_name_to_a_method_name()
    {
        $name = (new WebhooksController)->eventToMethod('customer.subscription.deleted');

        $this->assertEquals('whenCustomerSubscriptionDeleted', $name);
    }

}

<?php namespace SublimeArts\SublimeStripe\Tests\Http\Controllers;

use PluginTestCase;
use SublimeArts\SublimeStripe\Http\Controllers\WebhooksController;

class WebhooksControllerTest extends PluginTestCase
{

    protected $baseUrl = 'http://sublimestripe.dev';

    /** @test */
    public function it_converts_a_stripe_event_name_to_a_method_name()
    {
        $name = (new WebhooksController)->eventToMethod('customer.subscription.deleted');

        $this->assertEquals('whenCustomerSubscriptionDeleted', $name);
    }

}

Add the correct baseUrl for the WebhookController test.


<?php

namespace Bdt\Eway\Log;

use Guzzle\Log\MessageFormatter as GuzzleMessageFormatter;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Curl\CurlHandle;

/**
 * Eway MessageFormatter that hides the credit card number from logs.
 */
class MessageFormatter extends GuzzleMessageFormatter
{
    /**
     * {@inheritdoc}
     * Also replaces the ewayCardNumber field in the body with Xs.
     */
    public function format(
        RequestInterface $request,
        Response $response = null,
        CurlHandle $handle = null,
        array $customData = array()
    ) {
        if ($request instanceof EntityEnclosingRequestInterface) {
            $request = clone($request);
            $body = preg_replace_callback('/<ewayCardNumber>(.*?)<\/ewayCardNumber>/', function($matches) {
                $privateNumber = str_repeat('X', strlen($matches[1])-4).substr($matches[1], -4);
                return '<ewayCardNumber modified>'.$privateNumber.'</ewayCardNumber>';
            }, $request->getBody()->__toString());
            $request->setBody($body);
        }
        return parent::format($request, $response, $handle, $customData);
    }
}

<?php

namespace Bdt\Eway\Log;

use Guzzle\Log\MessageFormatter as GuzzleMessageFormatter;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Curl\CurlHandle;

/**
 * Eway MessageFormatter that hides the credit card number from logs.
 */
class MessageFormatter extends GuzzleMessageFormatter
{
    /**
     * {@inheritdoc}
     * Also replaces the ewayCardNumber field in the body with Xs.
     */
    public function format(
        RequestInterface $request,
        Response $response = null,
        CurlHandle $handle = null,
        array $customData = array()
    ) {
        if ($request instanceof EntityEnclosingRequestInterface) {
            $body = $request->getBody()->__toString();
            $newBody = preg_replace_callback('/<ewayCardNumber>(.*?)<\/ewayCardNumber>/', function($matches) {
                $privateNumber = str_repeat('X', strlen($matches[1])-4).substr($matches[1], -4);
                return '<ewayCardNumber modified>'.$privateNumber.'</ewayCardNumber>';
            }, $body);
            $newRequest = clone $request;
            $newRequest->setBody($newBody);

            $request->setBody($body);
        } else {
            $newRequest = $request;
        }
        return parent::format($newRequest, $response, $handle, $customData);
    }
}

Set the body of the new request to handle issues with cloning request bodies


<?php

/**
 * Part of the Stripe package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Stripe
 * @version    2.1.0
 * @author     Cartalyst LLC
 * @license    BSD License (3-clause)
 * @copyright  (c) 2011-2018, Cartalyst LLC
 * @link       http://cartalyst.com
 */

namespace Cartalyst\Stripe\Api;

class EphemeralKey extends Api
{
    /**
     * Creates a new Ephemeral Key.
     *
     * @param  string  $customer
     * @return array
     */
    public function create(string $customer)
    {
        return $this->_post('ephemeral_keys', compact('customer'));
    }

    /**
     * Deletes the given Ephemeral Key.
     *
     * @param  string  $ephemeralKey
     * @return array
     */
    public function delete(string $ephemeralKey)
    {
        return $this->_delete("ephemeral_keys/{$ephemeralKey}");
    }
}

<?php

/**
 * Part of the Stripe package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Stripe
 * @version    2.1.0
 * @author     Cartalyst LLC
 * @license    BSD License (3-clause)
 * @copyright  (c) 2011-2018, Cartalyst LLC
 * @link       http://cartalyst.com
 */

namespace Cartalyst\Stripe\Api;

class EphemeralKey extends Api
{
    /**
     * Creates a new Ephemeral Key.
     *
     * @param  string  $customer
     * @return array
     */
    public function create($customer)
    {
        return $this->_post('ephemeral_keys', compact('customer'));
    }

    /**
     * Deletes the given Ephemeral Key.
     *
     * @param  string  $ephemeralKey
     * @return array
     */
    public function delete($ephemeralKey)
    {
        return $this->_delete("ephemeral_keys/{$ephemeralKey}");
    }
}

Remove typehint for PHP 5.5.

fix: Remove typehint for PHP 5.5.

Signed-off-by: Bruno Gaspar <367518169777ee9ae71cfcee56304a59ac5423c1@gmail.com>


<?php

namespace Michaeljennings\Carpenter;

class Laravel4ServiceProvider extends CarpenterServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('michaeljennings/carpenter', 'carpenter');
    }
}

<?php

namespace Michaeljennings\Carpenter;

class Laravel4ServiceProvider extends CarpenterServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     * @codeCoverageIgnore
     */
    public function boot()
    {
        $this->package('michaeljennings/carpenter', 'carpenter');
    }
}

Remove boot method in laravel 4 service provider from code coverage


<?php
namespace Criterion\Helper;

class Github
{
    public static function toSSHUrl($url)
    {
        $url = str_replace(array('https://','.com/'), array('git@','.com:'), $url);
        return $url;
    }

    public static function toHTTPSUrl($url)
    {
        $url = str_replace(array('git@','.com:'), array('https://','.com/'), $url);
        return $url;
    }

    public static function commitUrl($commit, $repo)
    {
    	$repo = self::toHTTPSUrl($repo);
    	return $repo . '/commit/' . $commit['hash']['long'];
    }

    public static function branchUrl($branch, $repo)
    {
    	$repo = self::toHTTPSUrl($repo);
    	return $repo . '/tree/' . $branch;
    }
}

<?php
namespace Criterion\Helper;

class Github
{
    public static function toSSHUrl($url)
    {
        $url = str_replace(array('https://','.com/'), array('git@','.com:'), $url);
        return $url;
    }

    public static function toHTTPSUrl($url)
    {
        $url = str_replace(array('git@','.com:'), array('https://','.com/'), $url);
        return $url;
    }

    public static function commitUrl($commit, $repo)
    {
        $repo = self::toHTTPSUrl($repo);
        return $repo . '/commit/' . $commit['hash']['long'];
    }

    public static function branchUrl($branch, $repo)
    {
        $repo = self::toHTTPSUrl($repo);
        return $repo . '/tree/' . $branch;
    }

    public static function shortRepo($url)
    {
        $https_url = self::toHTTPSUrl($url);
        return str_replace('https://github.com/', null, $https_url);
    }
}

Return a short version of a github repo

Return a short version of a github repo


<?php
/*
 * Copyright 2016 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Filter\Rule;

use Coast\Filter\Rule;

class Custom extends Rule
{
    protected $_func = [];

	public function __construct(callable $func, $name = null)
	{
        $this->func($func);
	}

    public function func($func = null)
    {
        if (func_num_args() > 0) {
            $this->_func = $func;
            return $this;
        }
        return $this->_func;
    }

    protected function _filter($value)
    {
        $func = $this->_func;
        return $func($value, $this);
    }
}

<?php
/*
 * Copyright 2016 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Filter\Rule;

use Coast\Filter\Rule;

class Custom extends Rule
{
    protected $_func = [];

	public function __construct(callable $func, $name = null)
	{
        $this->func($func);
        $this->name($name);
	}

    public function func($func = null)
    {
        if (func_num_args() > 0) {
            $this->_func = $func;
            return $this;
        }
        return $this->_func;
    }

    protected function _filter($value)
    {
        $func = $this->_func;
        return $func($value, $this);
    }
}

Add name to custom filter

Add name to custom filter


<?php

namespace Debril\RssAtomBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class StreamControllerTest extends WebTestCase
{

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

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

        $response = $client->getResponse();
        $this->assertEquals('200', $response->getStatusCode());
        $lastModified = $response->getLastModified();

        $lastModified->setTimezone(
                new \DateTimeZone(date_default_timezone_get())
        );

        $this->assertInstanceOf('\DateTime', $lastModified);
        $this->assertGreaterThan(0, $response->getMaxAge());
        $this->assertGreaterThan(0, strlen($response->getContent()));
        $this->assertTrue($response->isCacheable());

        $client->request('GET', '/mock/rss', array(), array(), array('HTTP_If-Modified-Since' => $lastModified->format(\DateTime::RSS)));
        $response2 = $client->getResponse();

        $this->assertEquals('304', $response2->getStatusCode());
        $this->assertEquals(0, strlen($response2->getContent()));
    }

    /**
     * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function testNotFound()
    {
        $client = static::createClient();

        $client->request('GET', '/mock/rss/not-found');
    }

    /**
     * @expectedException \Exception
     */
    public function testBadProvider()
    {
        $client = static::createClient();

        $client->request('GET', '/bad/provider');
    }

}

<?php

namespace Debril\RssAtomBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class StreamControllerTest extends WebTestCase
{

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

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

        $response = $client->getResponse();
        $this->assertEquals('200', $response->getStatusCode());
        $lastModified = $response->getLastModified();

        $lastModified->setTimezone(
                new \DateTimeZone(date_default_timezone_get())
        );

        $lastModified->add(new \DateInterval('PT1S'));
        $this->assertInstanceOf('\DateTime', $lastModified);
        $this->assertGreaterThan(0, $response->getMaxAge());
        $this->assertGreaterThan(0, strlen($response->getContent()));
        $this->assertTrue($response->isCacheable());

        $client->request('GET', '/mock/rss', array(), array(), array('HTTP_If-Modified-Since' => $lastModified->format(\DateTime::RSS)));
        $response2 = $client->getResponse();

        $this->assertEquals('304', $response2->getStatusCode());
        $this->assertEquals(0, strlen($response2->getContent()));
    }

    /**
     * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function testNotFound()
    {
        $client = static::createClient();

        $client->request('GET', '/mock/rss/not-found');
    }

    /**
     * @expectedException \Exception
     */
    public function testBadProvider()
    {
        $client = static::createClient();

        $client->request('GET', '/bad/provider');
    }

}

Fix 200 / 304 issue

Fix 200 / 304 issue


<?php

namespace Slate\Progress;

class SectionInterimReportsRequestHandler extends \RecordsRequestHandler
{
    public static $recordClass = SectionInterimReport::class;
}

<?php

namespace Slate\Progress;

use Slate\Term;
use Slate\Courses\Section;
use Slate\People\Student;

class SectionInterimReportsRequestHandler extends \RecordsRequestHandler
{
    public static $recordClass = SectionInterimReport::class;

    public static function handleBrowseRequest($options = [], $conditions = [], $responseID = null, $responseData = [])
    {
        if (!empty($_REQUEST['term'])) {
            if ($_REQUEST['term'] == 'current') {
                if (!$Term = Term::getClosest()) {
                    return static::throwInvalidRequestError('No current term could be found');
                }
            } elseif (!$Term = Term::getByHandle($_REQUEST['term'])) {
                return static::throwNotFoundError('term not found');
            }

            $conditions[] = sprintf('TermID IN (%s)', join(',', $Term->getRelatedTermIDs()));
            $responseData['term'] = $Term;
        }

        if (!empty($_REQUEST['course_section'])) {
            if (!$Section = Section::getByHandle($_REQUEST['course_section'])) {
                return static::throwNotFoundError('course_section not found');
            }

            $conditions['SectionID'] = $Section->ID;
            $responseData['course_section'] = $Section;
        }

        if (!empty($_REQUEST['students'])) {
            $studentIds = [];

            foreach (Student::getAllByListIdentifier($_REQUEST['students']) AS $Student) {
                $studentIds[] = $Student->ID;
            }

            $conditions[] = sprintf('StudentID IN (%s)', count($studentIds) ? join(',', $studentIds) : '0');
        }

        if (!empty($_REQUEST['status'])) {
            if (!in_array($_REQUEST['status'], Report::getFieldOptions('Status', 'values'))) {
                return static::throwInvalidRequestError('Invalid status');
            }

            $conditions['Status'] = $_REQUEST['status'];
        }

        return parent::handleBrowseRequest($options, $conditions, $responseID, $responseData);
    }
}

Add filters for interim reports

Add filters for interim reports


<?php

namespace Picqer\Financials\Moneybird\Entities\Generic;

use Picqer\Financials\Moneybird\Model;

/**
 * Class InvoiceDetail.
 */
abstract class InvoiceDetail extends Model
{
    /**
     * @var array
     */
    protected $fillable = [
        'id',
        'tax_rate_id',
        'ledger_account_id',
        'amount',
        'description',
        'period',
        'price',
        'row_order',
        'total_price_excl_tax_with_discount',
        'total_price_excl_tax_with_discount_base',
        'tax_report_reference',
        'created_at',
        'updated_at',
        'product_id',
        '_destroy',
    ];
}

<?php

namespace Picqer\Financials\Moneybird\Entities\Generic;

use Picqer\Financials\Moneybird\Model;

/**
 * Class InvoiceDetail.
 */
abstract class InvoiceDetail extends Model
{
    /**
     * @var array
     */
    protected $fillable = [
        'id',
        'tax_rate_id',
        'ledger_account_id',
        'amount',
        'description',
        'period',
        'price',
        'row_order',
        'total_price_excl_tax_with_discount',
        'total_price_excl_tax_with_discount_base',
        'tax_report_reference',
        'created_at',
        'updated_at',
        'product_id',
        '_destroy',
        'project_id',
    ];
}

Add project_id to invoice detail

Add project_id to invoice detail


<?php
/**
 * The default template for displaying content. Used for both single and index/archive/search.
 *
 * @subpackage cerulean
 * @since cerulean 4.0
 */
global $responsive_svg;
?>

<?php if (!empty(get_field_img($responsive_svg['img_field']))){ ?>
        <?php
        $path = get_attached_file(get_field($responsive_svg['img_field']) );
        $file = file_get_contents($path);
        preg_match('/viewBox="[0-9\s]+"/i', $file, $viewbox);
        $viewbox = explode(' ', $viewbox[0]) ;
        $ratio = floor($viewbox[3] / $viewbox[2] *10000) /100;
        //var_dump($ratio);
        $file = preg_replace('/<svg.+(viewBox="[0-9\s]+").+>/i', '<svg version="1.1" preserveAspectRatio="xMinYMin meet" class="u-svg__content" $1>', $file);

        ?>
        <div class="u-svg <?php echo $responsive_svg['class_svg-container'];?>" <?php echo $responsive_svg['attr_svg-container'];?> style="padding-bottom:<?php echo $ratio; ?>%">
        <?php
        echo $file;
        ?>
        </div>
<?php } ?>

<?php
/**
 * The default template for displaying content. Used for both single and index/archive/search.
 *
 * @subpackage cerulean
 * @since cerulean 4.0
 */
global $responsive_svg;
?>

<?php if (!empty(get_field($responsive_svg['img_field'],$responsive_svg['post_id']))){ ?>
        <?php

        $path = get_attached_file(get_field($responsive_svg['img_field'],$responsive_svg['post_id']) );
        $file = file_get_contents($path);
        preg_match('/viewBox="[0-9\s]+"/i', $file, $viewbox);
        $viewbox = explode(' ', $viewbox[0]) ;
        $ratio = floor($viewbox[3] / $viewbox[2] *10000) /100;
        //var_dump($ratio);
        $file = preg_replace('/<svg.+(viewBox="[0-9\s]+").+>/i', '<svg version="1.1" preserveAspectRatio="xMinYMin meet" class="u-svg__content" $1>', $file);

        ?>
        <div class="u-svg <?php echo $responsive_svg['class_svg-container'];?>" <?php echo $responsive_svg['attr_svg-container'];?> style="padding-bottom:<?php echo $ratio; ?>%">
        <?php
        echo $file;
        ?>
        </div>
<?php } ?>

Support for post id/opions page in responsive svg


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

// Displays the number of total users or the number of users in a group
// Use:
// {USERCOUNT()}groupname{USERCOUNT}
//
// If no groupname is given returns all users

function wikiplugin_usercount_help() {
        return tra("Displays the number of registered users").":<br />~np~{USERCOUNT()}groupname{USERCOUNT}~/np~";
}

function wikiplugin_usercount_info() {
	return array(
		'name' => tra('User Count'),
		'documentation' => 'PluginUserCount',
		'description' => tra('Displays the number of registered users'),
		'prefs' => array( 'wikiplugin_usercount' ),
		'body' => tra('Group name'),
		'icon' => 'pics/icons/group_gear.png',
		'params' => array(
		),
	);
}

function wikiplugin_usercount($data, $params) {
        global $tikilib;

        global $userlib;

        extract ($params,EXTR_SKIP);

        $numusers = $userlib->count_users($data);

        return $numusers;
}

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

// Displays the number of total users or the number of users in a group
// Use:
// {USERCOUNT()}groupname{USERCOUNT}
//
// If no groupname is given returns all users

function wikiplugin_usercount_help() {
        return tra("Displays the number of registered users").":<br />~np~{USERCOUNT()}groupname{USERCOUNT}~/np~";
}

function wikiplugin_usercount_info() {
	return array(
		'name' => tra('User Count'),
		'documentation' => tra('PluginUserCount'),
		'description' => tra('Displays the number of users that are registered or within a group'),
		'prefs' => array( 'wikiplugin_usercount' ),
		'body' => tra('Group name'),
		'icon' => 'pics/icons/group_gear.png',
		'params' => array(
		),
	);
}

function wikiplugin_usercount($data, $params) {
        global $tikilib;

        global $userlib;

        extract ($params,EXTR_SKIP);

        $numusers = $userlib->count_users($data);

        return $numusers;
}

Add tra and some rewording for plugin info used in plugin edit window

git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@30966 b456876b-0849-0410-b77d-98878d47e9d5


<?php

require __DIR__.'/../../vendor/autoload.php';
require 'path.php';

$dotenv = new Dotenv\Dotenv(dirname(__DIR__));
$dotenv->load();

date_default_timezone_set(getenv('DATE_TIMEZONE') ?: 'Asia/Jakarta');

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection(array(
   'driver'    => getenv('DRIVER_ELOQUENT') ?: 'mysql',
   'host'      => getenv('DB_HOST') ?: 'localhost',
   'database'  => getenv('DB_DATABASE') ?: 'homestead',
   'username'  => getenv('DB_USERNAME') ?: 'homestead',
   'password'  => getenv('DB_PASSWORD') ?: 'secret',
   'charset'   => 'utf8',
   'collation' => 'utf8_unicode_ci',
   'prefix'    => getenv('DB_PREFIX') ?: '',
));

foreach (glob(__DIR__ . '/db_*.php') as $filedb) {
	include $filedb;
}

$capsule->setAsGlobal();
$capsule->bootEloquent();

<?php

require __DIR__.'/../../vendor/autoload.php';
require 'path.php';

$dotenv = new Dotenv\Dotenv(dirname(dirname(__DIR__)));
$dotenv->load();

date_default_timezone_set(getenv('DATE_TIMEZONE') ?: 'Asia/Jakarta');

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection(array(
   'driver'    => getenv('DRIVER_ELOQUENT') ?: 'mysql',
   'host'      => getenv('DB_HOST') ?: 'localhost',
   'database'  => getenv('DB_DATABASE') ?: 'homestead',
   'username'  => getenv('DB_USERNAME') ?: 'homestead',
   'password'  => getenv('DB_PASSWORD') ?: 'secret',
   'charset'   => 'utf8',
   'collation' => 'utf8_unicode_ci',
   'prefix'    => getenv('DB_PREFIX') ?: '',
));

foreach (glob(__DIR__ . '/db_*.php') as $filedb) {
	include $filedb;
}

$capsule->setAsGlobal();
$capsule->bootEloquent();

Change Dotenv contruction to app root directory


{{-- Block Type: Call To Action --}}

{{ $block->block_title }}

    {{ $block->block_body_html }}

    @if (Auth::guest())

        {{ link_to_route('registration.create', 'Start Application', null, ['class' => 'button -default']) }}
        {{ link_to_route('status', 'or continue an application') }}

    @else

        {{ link_to_route('status', 'Continue Application', null, ['class' => 'button -default']) }}

    @endif

Update to make code cleaner.

Update to make code cleaner.


<?php namespace xp\runtime;

use util\cmd\Console;

/**
 * Displays XP version and runtime information
 */
class Version {

  /**
   * Main
   *
   * @param   string[] args
   * @return  int
   */
  public static function main(array $args) {
    Console::writeLinef(
      'XP %s { PHP %s & ZE %s } @ %s',
      \xp::version(),
      phpversion(),
      zend_version(),
      php_uname()
    );
    Console::writeLine('Copyright (c) 2001-2016 the XP group');
    foreach (\lang\ClassLoader::getLoaders() as $delegate) {
      Console::writeLine($delegate->toString());
    }
    return 1;
  }
}

<?php namespace xp\runtime;

use util\cmd\Console;

/**
 * Displays XP version and runtime information
 */
class Version {

  /** @return string */
  private function xpVersion() { return 'XP/'.\xp::version(); }

  /** @return string */
  private function phpVersion() { return 'PHP/'.phpversion(); }

  /** @return string */
  private function engineVersion() { return defined('HHVM_VERSION') ? 'HHVM/'.HHVM_VERSION : 'Zend/'.zend_version(); }

  /** @return string */
  private function osVersion() {
    if ('Linux' == PHP_OS && is_executable('/usr/bin/lsb_release')) {
      return 'Linux/'.strtr(`/usr/bin/lsb_release -scd`, "\n", ' ');
    } else {
      return PHP_OS.'/'.php_uname('v');
    }
  }

  /**
   * Main
   *
   * @param   string[] $args
   * @return  int
   */
  public static function main(array $args) {
    if (isset($args[0])) {
      $method= $args[0].'Version';
      Console::writeLine(self::$method());
    } else {
      Console::writeLinef(
        'XP %s { PHP %s & ZE %s } @ %s',
        \xp::version(),
        phpversion(),
        zend_version(),
        php_uname()
      );
      Console::writeLine('Copyright (c) 2001-2016 the XP group');
      foreach (\lang\ClassLoader::getLoaders() as $delegate) {
        Console::writeLine($delegate->toString());
      }
      return 1;
    }
  }
}

Implement version details xp, php, engine and os

. xp: XP Version
. php: PHP Version
. engine: Engine version - HHVM_VERSION || zend_version()
. os: OS Version (and distribution if available)


<?php
$fields = json_decode(json_encode(get_fields($module->ID)));

$classes = '';
if (isset($fields->mod_table_classes) && is_array($fields->mod_table_classes)) {
    $classes = implode(' ', $fields->mod_table_classes);
}
?>

<?php echo $module->post_title; ?>

    <?php
    echo str_replace(
        'mod_table_pagination_count,
            $fields->mod_table_search
        ),
        $fields->mod_table
    );
?>

<?php
$fields = json_decode(json_encode(get_fields($module->ID)));

$classes = '';
if (isset($fields->mod_table_classes) && is_array($fields->mod_table_classes)) {
    $classes = implode(' ', $fields->mod_table_classes);
}
?>

<?php echo $module->post_title; ?>

    <?php
    echo str_replace(
        'mod_table_pagination_count,
            $fields->mod_table_search,
            $fields->mod_table_pagination || $fields->mod_table_search
        ),
        $fields->mod_table
    );
?>

Disable info if both pagination and filter is disabled


<?php
/**
 * Audio Player
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the LICENSE.md file.
 *
 * @author Marcel Scherello <audioplayer@scherello.de>
 * @author Olivier Paroz <galleryapps@oparoz.com>
 * @copyright 2016-2019 Marcel Scherello
 */

namespace OCA\audioplayer\Http;

use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http;

/**
 * A renderer for cover arts
 */
class ImageResponse extends Response
{

    private $preview;

    /**
     * @param array $image image meta data
     * @param int $statusCode the Http status code, defaults to 200
     */
    public function __construct(array $image, $statusCode = Http::STATUS_OK)
    {
        $this->preview = $image['content'];
        $this->setStatus($statusCode);
        $this->addHeader('Content-type', $image['mimetype'] . '; charset=utf-8');
        $this->cacheFor(365 * 24 * 60 * 60);
        $etag = md5($image['content']);
        $this->setETag($etag);
    }

    /**
     * Returns the rendered image
     *
     * @return string the file
     */
    public function render()
    {
        if ($this->preview instanceof \OC_Image) {
            return $this->preview->data();
        } else {
            return $this->preview;
        }
    }
}

<?php
/**
 * Audio Player
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the LICENSE.md file.
 *
 * @author Marcel Scherello <audioplayer@scherello.de>
 * @author Olivier Paroz <galleryapps@oparoz.com>
 * @copyright 2016-2019 Marcel Scherello
 */

namespace OCA\audioplayer\Http;

use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http;

/**
 * A renderer for cover arts
 */
class ImageResponse extends Response
{

    private $preview;

    /**
     * @param array $image image meta data
     * @param int $statusCode the Http status code, defaults to 200
     */
    public function __construct(array $image, $statusCode = Http::STATUS_OK)
    {
        parent::__construct();
        $this->preview = $image['content'];
        $this->setStatus($statusCode);
        $this->addHeader('Content-type', $image['mimetype'] . '; charset=utf-8');
        $this->cacheFor(365 * 24 * 60 * 60);
        $etag = md5($image['content']);
        $this->setETag($etag);
    }

    /**
     * Returns the rendered image
     *
     * @return string the file
     */
    public function render()
    {
        if ($this->preview instanceof \OC_Image) {
            return $this->preview->data();
        } else {
            return $this->preview;
        }
    }
}

Call parent constructor on response object

Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>


<?php
namespace Test;

// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;

/**
 * Unit test for the UriFactory object.
 *
 * @package Test
 * @author  Bohuslav Simek <bohuslav@simek.si>
 * @license MIT
 */
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test creating url from string.
     *
     * @return void
     */
    public function testCreate()
    {
        $uri = UriFactory::create(
            'http://user:password@test.com:1111/path/123?q=abc#test'
        );

        $this->assertInstanceOf('Kambo\HttpMessage\Uri', $uri);
        $this->assertEquals('http', $uri->getScheme());
        $this->assertEquals('user:password', $uri->getUserInfo());
        $this->assertEquals('test.com', $uri->getHost());
        $this->assertEquals(1111, $uri->getPort());
        $this->assertEquals('/path/123', $uri->getPath());
        $this->assertEquals('q=abc', $uri->getQuery());
        $this->assertEquals('test', $uri->getFragment());
    }
}

<?php
namespace Test;

// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;

/**
 * Unit test for the UriFactory object.
 *
 * @package Test
 * @author  Bohuslav Simek <bohuslav@simek.si>
 * @license MIT
 */
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test creating url from string.
     *
     * @return void
     */
    public function testCreate()
    {
        $uri = UriFactory::create(
            'http://user:password@test.com:1111/path/123?q=abc#test'
        );

        $this->assertInstanceOf(Uri::class, $uri);
        $this->assertEquals('http', $uri->getScheme());
        $this->assertEquals('user:password', $uri->getUserInfo());
        $this->assertEquals('test.com', $uri->getHost());
        $this->assertEquals(1111, $uri->getPort());
        $this->assertEquals('/path/123', $uri->getPath());
        $this->assertEquals('q=abc', $uri->getQuery());
        $this->assertEquals('test', $uri->getFragment());
    }
}

Revert "Fix broken test in PHP 5.4"

Revert "Fix broken test in PHP 5.4"

This reverts commit 60a6a6943c76a783f0251245b8a3919d86640f6b.


<?php

use pendalf89\filemanager\assets\FilemanagerAsset;
use pendalf89\filemanager\Module;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model pendalf89\filemanager\models\Mediafile */
/* @var $dataProvider yii\data\ActiveDataProvider */
$bundle = FilemanagerAsset::register($this);
?>
<?= Html::img($model->getDefaultThumbUrl($bundle->baseUrl)) ?>

<?= $model->type ?>

<?= Yii::$app->formatter->asDatetime($model->getLastChanges()) ?>

<?= Yii::$app->formatter->asShortSize($model->size, 0) ?>

<?= Html::a(Module::t('main', 'Delete'), ['/filemanager/file/delete/', 'id' => $model->id],
            [
                'class' => 'text-danger',
                'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                'data-id' => $model->id,
                'role' => 'delete',
            ]
        ) ?>

    <?= $model->filename ?>

<?php

use pendalf89\filemanager\assets\FilemanagerAsset;
use pendalf89\filemanager\Module;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model pendalf89\filemanager\models\Mediafile */
/* @var $dataProvider yii\data\ActiveDataProvider */
$bundle = FilemanagerAsset::register($this);
?>
<?= Html::img($model->getDefaultThumbUrl($bundle->baseUrl)) ?>

<?= $model->type ?>

<?= Yii::$app->formatter->asDatetime($model->getLastChanges()) ?>

    <?php Yii::$app->formatter->sizeFormatBase = 1000; ?>

<?= Yii::$app->formatter->asShortSize($model->size, 0) ?>

<?= Html::a(Module::t('main', 'Delete'), ['/filemanager/file/delete/', 'id' => $model->id],
            [
                'class' => 'text-danger',
                'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                'data-id' => $model->id,
                'role' => 'delete',
            ]
        ) ?>

    <?= $model->filename ?>

Change kibi to kilo format

Change kibi to kilo format


<?php declare(strict_types=1);

namespace Symplify\BetterPhpDocParser\Attributes\Ast\PhpDoc\Type;

use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use Symplify\BetterPhpDocParser\Attributes\Attribute\AttributeTrait;
use Symplify\BetterPhpDocParser\Attributes\Contract\Ast\AttributeAwareNodeInterface;

final class AttributeAwareNullableTypeNode extends NullableTypeNode implements AttributeAwareNodeInterface
{
    use AttributeTrait;
}

<?php declare(strict_types=1);

namespace Symplify\BetterPhpDocParser\Attributes\Ast\PhpDoc\Type;

use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use Symplify\BetterPhpDocParser\Attributes\Attribute\AttributeTrait;
use Symplify\BetterPhpDocParser\Attributes\Contract\Ast\AttributeAwareNodeInterface;

final class AttributeAwareNullableTypeNode extends NullableTypeNode implements AttributeAwareNodeInterface
{
    use AttributeTrait;

    public function __toString(): string
    {
        return $this->type . '|null';
    }
}

Fix nullable type print to doc |null

[BetterPhpDocParser] Fix nullable type print to doc |null


<?php namespace Anomaly\UsersModule\Role\Command;

use Anomaly\Streams\Platform\Support\Authorizer;
use Anomaly\UsersModule\Role\Contract\RoleRepositoryInterface;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class SetGuestRole
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\UsersModule\Role\Command
 */
class SetGuestRole implements SelfHandling
{

    /**
     * Handle the command.
     *
     * @param RoleRepositoryInterface $roles
     * @param Authorizer              $authorizer
     */
    public function handle(RoleRepositoryInterface $roles, Authorizer $authorizer)
    {
        $authorizer->setGuest($roles->findBySlug('guest'));
    }
}

<?php namespace Anomaly\UsersModule\Role\Command;

use Anomaly\Streams\Platform\Support\Authorizer;
use Anomaly\UsersModule\Role\Contract\RoleRepositoryInterface;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class SetGuestRole
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\UsersModule\Role\Command
 */
class SetGuestRole implements SelfHandling
{

    /**
     * Handle the command.
     *
     * @param RoleRepositoryInterface $roles
     * @param Authorizer              $authorizer
     */
    public function handle(RoleRepositoryInterface $roles, Authorizer $authorizer)
    {
        if ($guest = $roles->findBySlug('guest')) {
            $authorizer->setGuest($guest);
        }
    }
}

Fix issue where guest does not exist

Fix issue where guest does not exist


<?php

namespace ContentTranslator;

class Meta Extends Entity\Translate
{

    protected $lang;

    public function __construct()
    {
        if (\ContentTranslator\Switcher::isLanguageSet()) {
            $this->lang = \ContentTranslator\Switcher::$currentLanguage['code'];
            add_filter('get_post_metadata', array($this,'get'), 4, 1);
        }
    }

    public function save(null, $object_id, $meta_key, $single ) {

        return null;
    }

    public function get(null, $object_id, $meta_key, $single ) {
        if(!$this->isLangualMeta($meta_key)) {
            return get_metadata('post', $object_id, $this->createLangualMetaKey($meta_key), $single);
        }

        return null;
    }

    private function isLangualMeta($meta_key) {
        return substr($meta_key, -strlen("_".$this->lang)) == TRANSLATE_DELIMITER.$this->lang ? true : false;
    }

    private function createLangualMetaKey ($meta_key) {
        return $meta_key.TRANSLATE_DELIMITER.$this->lang;
    }
}

<?php

namespace ContentTranslator;

class Meta Extends Entity\Translate
{

    protected $lang;

    public function __construct()
    {
        if (\ContentTranslator\Switcher::isLanguageSet()) {
            $this->lang = \ContentTranslator\Switcher::$currentLanguage['code'];
            add_filter('get_post_metadata', array($this,'get'), 4, 1);
        }
    }

    public function save(null, $object_id, $meta_key, $single ) {

        return null;
    }

    public function get(null, $object_id, $meta_key, $single ) {

        if(!$this->isLangualMeta($meta_key)) {

            $translation =  get_metadata('post', $object_id, $this->createLangualMetaKey($meta_key), $single);

            if (!TRANSLATE_FALLBACK && $translation == "") {
                return "";      // Abort and return empty
            } elseif (TRANSLATE_FALLBACK && $translation == "") {
                return null;    // Continiue normal procedure
            } {
                return $translation; // Not empty, return value
            }

        }

        return null;
    }

    private function isLangualMeta($meta_key) {
        return substr($meta_key, -strlen(TRANSLATE_DELIMITER.$this->lang)) == TRANSLATE_DELIMITER.$this->lang ? true : false;
    }

    private function createLangualMetaKey ($meta_key) {
        return $meta_key.TRANSLATE_DELIMITER.$this->lang;
    }
}

Support for fallback & no fallback.

Support for fallback & no fallback.


<?php

namespace FluxBB\Models;

class Ban extends Base
{
    protected $table = 'bans';

    public function creator()
    {
        return $this->belongsTo('FluxBB\\Models\\User', 'ban_creator');
    }
}

Remove whitespace at beginning of file.

Remove whitespace at beginning of file.


<?php

namespace Plummer\Calendarful;

interface RegistryInterface
{
	public function get(Array $filters = []);
}

<?php

namespace Plummer\Calendarful;

interface RegistryInterface
{
	public function get();
}

Remove filters parameter from method signature.


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

            <?php

            get_template_part(SNIPPETS_DIR . '/header/entry-header');

            if (is_archive() || is_home() || is_search()) :
                get_template_part(SNIPPETS_DIR . '/entry-excerpt');
            else :
                if ('' !== get_the_post_thumbnail()) :
                    get_template_part(SNIPPETS_DIR . '/post-thumbnail');
                endif;
                get_template_part(SNIPPETS_DIR . '/entry-content');
            endif;

            comments_template();

            ?>

            <?php

            if (!is_search()):
                keitaro_child_pages_list(get_the_ID());

                foreach (get_children(get_ancestors(get_the_ID())) as $page) :
                    get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks');
                endforeach;
            endif;

            get_template_part(SNIPPETS_DIR . '/entry-footer');

            ?>

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

        <?php if (!is_author() && !is_single()): ?>

                <?php keitaro_author_avatar(get_the_author_meta('ID')); ?>

        <?php endif; ?>

            <?php

            get_template_part(SNIPPETS_DIR . '/header/entry-header');

            if (is_archive() || is_home() || is_search()) :
                get_template_part(SNIPPETS_DIR . '/entry-excerpt');
            else :
                get_template_part(SNIPPETS_DIR . '/entry-content');
            endif;

            comments_template();

            ?>

        <?php if (is_single()): ?>

                <?php

                if (!is_search()):
                    keitaro_child_pages_list(get_the_ID());

                    foreach (get_children(get_ancestors(get_the_ID())) as $page) :
                        get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks');
                    endforeach;
                endif;

                get_template_part(SNIPPETS_DIR . '/entry-footer');

                ?>

        <?php endif; ?>

Add conditional blocks for avatars and post sidebar


<?php

namespace PragmaRX\Tracker\Support;

use PragmaRX\Support\Migration as PragmaRxMigration;

abstract class Migration extends PragmaRxMigration
{
    protected function checkConnection()
    {
        $this->manager = app()->make('db');

        $this->connection = $this->manager->connection('tracker');

        parent::checkConnection();
    }
}

<?php

namespace PragmaRX\Tracker\Support;

use PragmaRX\Support\Migration as PragmaRxMigration;

abstract class Migration extends PragmaRxMigration
{
    protected function checkConnection()
    {
        $this->manager = app()->make('db');

        $this->connection = $this->manager->connection(config('tracker.connection'));

        parent::checkConnection();
    }
}

Fix migrations with default MySQL connection.


<?php

namespace BrainMaestro\GitHooks;

class Hook
{
    private static $hooks;

    /**
     * Add valid git hooks.
     */
    public static function add($hook, $script)
    {
        if (array_key_exists($hook, self::getHooks())) {
            $filename = ".git/hooks/{$hook}";
            file_put_contents($filename, $script);
            chmod($filename, 0755);
            echo "Added '{$hook}' hook" . PHP_EOL;
        }
    }

    /**
     * Remove valid git hooks.
     */
    public static function remove($hook)
    {
        if (array_key_exists($hook, self::getHooks())) {
            unlink(".git/hooks/{$hook}");
            echo "Removed '{$hook}' hook" . PHP_EOL;
        }
    }

    /**
     * Get all valid git hooks
     */
    private static function getHooks()
    {
        if (! isset(self::$hooks)) {
            self::$hooks = array_flip([
               'applypatch-msg',
               'commit-msg',
               'post-applypatch',
               'post-checkout',
               'post-commit',
               'post-merge',
               'post-receive',
               'post-rewrite',
               'post-update',
               'pre-applypatch',
               'pre-auto-gc',
               'pre-commit',
               'pre-push',
               'pre-rebase',
               'pre-receive',
               'prepare-commit-msg',
               'push-to-checkout',
               'update',
           ]);
        }

        return self::$hooks;
    }
}

<?php

namespace BrainMaestro\GitHooks;

class Hook
{
    private static $hooks;

    /**
     * Add valid git hooks.
     */
    public static function add($hook, $script)
    {
        $filename = ".git/hooks/{$hook}";

        if (array_key_exists($hook, self::getHooks())) {
            file_put_contents($filename, $script);
            chmod($filename, 0755);
            echo "Added '{$hook}' hook" . PHP_EOL;
        }
    }

    /**
     * Remove valid git hooks.
     */
    public static function remove($hook)
    {
        $filename = ".git/hooks/{$hook}";

        if (array_key_exists($hook, self::getHooks()) && is_file($filename)) {
            unlink(".git/hooks/{$hook}");
            echo "Removed '{$hook}' hook" . PHP_EOL;
        }
    }

    /**
     * Get all valid git hooks
     */
    private static function getHooks()
    {
        if (! isset(self::$hooks)) {
            self::$hooks = array_flip([
               'applypatch-msg',
               'commit-msg',
               'post-applypatch',
               'post-checkout',
               'post-commit',
               'post-merge',
               'post-receive',
               'post-rewrite',
               'post-update',
               'pre-applypatch',
               'pre-auto-gc',
               'pre-commit',
               'pre-push',
               'pre-rebase',
               'pre-receive',
               'prepare-commit-msg',
               'push-to-checkout',
               'update',
           ]);
        }

        return self::$hooks;
    }
}

Add check to ensure hook exists before deleting it


<?php

namespace Hochstrasser\Wirecard\Model;

abstract class Model
{
    private $parameters;

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

    static function fromParameters(array $parameters)
    {
        return new static($parameters);
    }

    function getParam($param)
    {
        if (array_key_exists($param, $this->parameters)) {
            return $this->parameters[$param];
        }
    }

    function addParam($param, $value)
    {
        $this->parameters[$param] = $value;
        return $this;
    }
}

<?php

namespace Hochstrasser\Wirecard\Model;

abstract class Model
{
    private $parameters;

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

    static function fromParameters(array $parameters)
    {
        return new static($parameters);
    }

    function toArray()
    {
        return $this->parameters;
    }

    function getParam($param)
    {
        if (array_key_exists($param, $this->parameters)) {
            return $this->parameters[$param];
        }
    }

    function addParam($param, $value)
    {
        $this->parameters[$param] = $value;
        return $this;
    }
}

Add toArray() to every model

Add toArray() to every model


<?php

namespace Mcfedr\QueueManagerBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('mcfedr_queue_manager')
            ->children()
                ->booleanNode('debug')->defaultFalse()->end()
                ->integerNode('retry_limit')->defaultValue(3)->end()
                ->integerNode('sleep_seconds')->defaultValue(5)->end()
                ->arrayNode('drivers')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('class')->isRequired()->cannotBeEmpty()->end()
                            ->scalarNode('command_class')->end()
                            ->variableNode('options')->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('managers')
                    ->requiresAtLeastOneElement()
                    ->prototype('array')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->scalarNode('driver')->cannotBeEmpty()->end()
                            ->variableNode('options')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Mcfedr\QueueManagerBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('mcfedr_queue_manager')
            ->children()
                ->booleanNode('debug')->defaultFalse()->end()
                ->integerNode('retry_limit')->defaultValue(3)->end()
                ->integerNode('sleep_seconds')->defaultValue(5)->end()
                ->arrayNode('drivers')
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('class')->isRequired()->cannotBeEmpty()->end()
                            ->scalarNode('command_class')->end()
                            ->variableNode('options')->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('managers')
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->scalarNode('driver')->cannotBeEmpty()->end()
                            ->variableNode('options')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Fix the config to have names of managers


<?php

if (file_exists(APP . 'Config' . DS . 'croogo.php')) {
	require APP . 'Config' . DS . 'croogo.php';
} else {
	if (!defined('LOG_ERROR')) {
		define('LOG_ERROR', LOG_ERR);
	}

	Configure::write('Error', array(
		'handler' => 'ErrorHandler::handleError',
		'level' => E_ALL & ~E_DEPRECATED,
		'trace' => true
	));

	Configure::write('Exception', array(
		'handler' => 'ErrorHandler::handleException',
		'renderer' => 'ExceptionRenderer',
		'log' => true
	));
}

<?php

if (file_exists(APP . 'Config' . DS . 'croogo.php')) {
	require APP . 'Config' . DS . 'croogo.php';
} else {
	if (!defined('LOG_ERROR')) {
		define('LOG_ERROR', LOG_ERR);
	}

	Configure::write('Error', array(
		'handler' => 'ErrorHandler::handleError',
		'level' => E_ALL & ~E_DEPRECATED,
		'trace' => true
	));

	Configure::write('Exception', array(
		'handler' => 'ErrorHandler::handleException',
		'renderer' => 'ExceptionRenderer',
		'log' => true
	));

	Configure::write('Session', array(
		'defaults' => 'php',
		'ini' => array(
			'session.cookie_httponly' => 1
		)
	));
}

Fix missing default session settings prior to the installation process

Closes #440
Cherry-picked from: croogo/croogo@f51f0852abbf


<?php

class Admin_Form_Link extends CM_Form_Abstract {

	public function setup () {
		$this->registerField('label', new CM_FormField_Text());
		$this->registerField('url', new CM_FormField_Url());
		$this->registerField('automatic', new CM_FormField_Boolean());

		$this->registerAction(new Admin_FormAction_Link_Add($this));
	}
}

<?php

class Admin_Form_Link extends CM_Form_Abstract {

	public function setup () {
		$this->registerField('label', new CM_FormField_Text());
		$this->registerField('url', new CM_FormField_Url());
		$this->registerField('automatic', new CM_FormField_Boolean());

		$this->registerAction(new Admin_FormAction_Link_Add($this));
	}

	protected function _renderStart(CM_Params $params) {
		$this->getField('automatic')->setValue(true);
	}
}

Set link's "automatic" field to TRUE by default


<?php
class Kwc_Directories_TopChoose_Component extends Kwc_Directories_Top_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['showDirectoryClass'] = 'Kwc_Directories_Item_Directory_Component'; // nur für form
        $ret['ownModel'] = 'Kwc_Directories_TopChoose_Model';
        $ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form';
        return $ret;
    }

    public static function getItemDirectoryClasses($directoryClass)
    {
        $ret = array();
        $class = self::getSetting($directoryClass, 'showDirectoryClass');
        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($class) as $component) {
            $ret[] = $component->componentClass;
        }
        return $ret;
    }

    protected function _getItemDirectory()
    {
        $row = $this->_getRow();
        if ($row && $row->directory_component_id) {
            $component = Kwf_Component_Data_Root::getInstance()
                ->getComponentByDbId($row->directory_component_id);
            if (is_instance_of($component, 'Kwc_Directories_Item_DirectoryNoAdmin_Component')) {
                return $component;
            }
        }
        return null;
    }
}

<?php
class Kwc_Directories_TopChoose_Component extends Kwc_Directories_Top_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['showDirectoryClass'] = 'Kwc_Directories_Item_Directory_Component'; // nur für form
        $ret['ownModel'] = 'Kwc_Directories_TopChoose_Model';
        $ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form';
        return $ret;
    }

    public static function getItemDirectoryClasses($directoryClass)
    {
        $ret = array();
        $class = self::getSetting($directoryClass, 'showDirectoryClass');
        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($class) as $component) {
            $ret[] = $component->componentClass;
        }
        return $ret;
    }

    protected function _getItemDirectory()
    {
        $row = $this->_getRow();
        if ($row && $row->directory_component_id) {
            $component = Kwf_Component_Data_Root::getInstance()
                ->getComponentByDbId($row->directory_component_id);
            if (is_instance_of($component->componentClass, 'Kwc_Directories_Item_DirectoryNoAdmin_Component')) {
                return $component;
            }
        }
        return null;
    }
}

Fix checking correct component class

Fix checking correct component class


<?php

namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;

/**
 * Basic replicator implementation using file operations to replicate.
 */
class FileReplicator implements Replicator
{
    /**
     * Base URL.
     * @var string
     */
    protected $baseUrl;

    /**
     * Target directory.
     * @var string
     */
    protected $directory;

    /**
     * Constructs a file replicator.
     */
    public function __construct($baseUrl, $directory)
    {
        $this->baseUrl = rtrim($baseUrl, '/').'/';
        $this->directory = rtrim($directory, '\\/').'/';
    }

    /**
     * {@inheritdoc}
     */
    public function replicate($resource)
    {
        $url = $this->baseUrl.$resource->getPath();
        if (!$source = @fopen($url, 'r')) {
            throw new ReplicatorException('Cannot open URL for reading.');
        }
        $file = $this->directory.$resource->getPath();
        @mkdir(dirname($file), 0777, true);
        if (!$target = @fopen($file, 'w')) {
            fclose($source);
            throw new ReplicatorException('Cannot open local file for writing.');
        }
        stream_copy_to_stream($source, $target);
        fclose($source);
        fclose($target);
    }
}

<?php

namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;

/**
 * Basic replicator implementation using file operations to replicate.
 */
class FileReplicator implements Replicator
{
    /**
     * Base URL.
     * @var string
     */
    protected $baseUrl;

    /**
     * Target directory.
     * @var string
     */
    protected $directory;

    /**
     * Constructs a file replicator.
     */
    public function __construct($baseUrl, $directory)
    {
        $this->baseUrl = rtrim($baseUrl, '/').'/';
        $this->directory = rtrim($directory, '\\/').'/';
    }

    /**
     * {@inheritdoc}
     */
    public function replicate($resource)
    {
        $url = $this->baseUrl.$resource->getPath();
        if (!$source = @fopen($url, 'rb')) {
            throw new ReplicatorException('Cannot open URL for reading.');
        }
        $file = $this->directory.$resource->getPath();
        @mkdir(dirname($file), 0777, true);
        if (!$target = @fopen($file, 'wb')) {
            fclose($source);
            throw new ReplicatorException('Cannot open local file for writing.');
        }
        stream_copy_to_stream($source, $target);
        fclose($source);
        fclose($target);
    }
}

Read and write as binary.

Read and write as binary.


<?php

namespace Soda\Cms\Models;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Soda\Cms\Models\Traits\DraftableTrait;
use Soda\Cms\Models\Traits\DynamicCreatorTrait;
use Soda\Cms\Models\Traits\OptionallyInApplicationTrait;

class PageType extends AbstractDynamicType {
    use OptionallyInApplicationTrait, DraftableTrait;

    protected $table = 'page_types';
    public $fillable = [
        'name',
        'identifier',
        'description',
        'application_id',
        'status',
        'position',
        'package',
        'action',
        'action_type',
        'edit_action',
        'edit_action_type',
    ];

    public function fields() {
        return $this->morphToMany(Field::class, 'fieldable');
    }

    public function block() {
        return $this->hasMany(Block::class, 'block_type_id');
    }

    public function setIdentifierAttribute($value) {
        $this->attributes['identifier'] = str_slug($value);
    }
}

<?php

namespace Soda\Cms\Models;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Soda\Cms\Models\Traits\DraftableTrait;
use Soda\Cms\Models\Traits\DynamicCreatorTrait;
use Soda\Cms\Models\Traits\OptionallyInApplicationTrait;

class PageType extends AbstractDynamicType {
    use OptionallyInApplicationTrait, DraftableTrait;

    protected $table = 'page_types';
    public $fillable = [
        'name',
        'identifier',
        'description',
        'application_id',
        'status',
        'position',
        'package',
        'action',
        'action_type',
        'edit_action',
        'edit_action_type',
    ];

    public function fields() {
        return $this->morphToMany(Field::class, 'fieldable');
    }

    public function block() {
        return $this->hasMany(Block::class, 'block_type_id');
    }

    public function setIdentifierAttribute($value) {
        $this->attributes['identifier'] = str_slug($value, '_');
    }
}

Fix page type identifier generator

Fix page type identifier generator


<?php
/**
 * Secondary sidebar template.
 *
 * @package BLR_Base_Theme\Templates
 */

?>

<?php dynamic_sidebar( 'sidebar-secondary' ); ?>

<?php
/**
 * Secondary sidebar template.
 *
 * @package BLR_Base_Theme\Templates
 */

?>

FREE White Papers

White Paper Placeholder Text

White Paper Placeholder Text

White Paper Placeholder Text

White Paper Placeholder Text

<?php dynamic_sidebar( 'sidebar-secondary' ); ?>

Add placeholder White Papers widget

Add placeholder White Papers widget


<?php

namespace LAG\AdminBundle\Utils;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class FormUtils
{
    /**
     * Convert a shortcut type into its class type.
     *
     * @param string $type
     *
     * @return string
     */
    public static function convertShortFormType(string $type)
    {
        $mapping = [
            'choice' => ChoiceType::class,
            'string' => TextType::class,
            'entity' => EntityType::class,
            'date' => DateType::class,
            'datetime' => DateType::class,
            'text' => TextType::class,
            'number' => NumberType::class,
            'integer' => NumberType::class,
            'smallint' => NumberType::class,
            'boolean' => CheckboxType::class,
        ];

        if (key_exists($type, $mapping)) {
            $type = $mapping[$type];
        }

        return $type;
    }
}

<?php

namespace LAG\AdminBundle\Utils;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class FormUtils
{
    /**
     * Convert a shortcut type into its class type.
     *
     * @param string $type
     *
     * @return string
     */
    public static function convertShortFormType(string $type)
    {
        $mapping = [
            'choice' => ChoiceType::class,
            'array' => ChoiceType::class,
            'string' => TextType::class,
            'entity' => EntityType::class,
            'date' => DateType::class,
            'datetime' => DateType::class,
            'text' => TextType::class,
            'number' => NumberType::class,
            'integer' => NumberType::class,
            'smallint' => NumberType::class,
            'boolean' => CheckboxType::class,
        ];

        if (key_exists($type, $mapping)) {
            $type = $mapping[$type];
        }

        return $type;
    }
}

Add missing form type mapping in the form utils


@section('js')

@endsection

@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}

@include('core::admin._image-fieldset', ['field' => 'image'])

{!! BootForm::hidden('homepage')->value(0) !!}
{!! BootForm::checkbox(__('Homepage'), 'homepage') !!}

has('position'))has-error @endif">
        {!! BootForm::text(__('Position'), 'position') !!}

@include('core::form._title-and-slug')
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::text(__('Website'), 'website') !!}
{!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

@section('js')

@endsection

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}

@include('core::admin._image-fieldset', ['field' => 'image'])

{!! BootForm::hidden('homepage')->value(0) !!}
{!! BootForm::checkbox(__('Homepage'), 'homepage') !!}

has('position'))has-error @endif">
        {!! BootForm::text(__('Position'), 'position') !!}

@include('core::form._title-and-slug')
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::text(__('Website'), 'website') !!}
{!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

Use of @component for buttons in form

Use of @component for buttons in form


Use CC template for oneclick payments

Use CC template for oneclick payments


<?php
namespace SepomexPhpTests\Cases;

use SepomexPhp\PdoGateway\Gateway;
use SepomexPhp\SepomexPhp;
use SepomexPhpTests\TestCase;

class ZipCodeDataTest extends TestCase
{
    public function testZipCodeCheck()
    {
        $expectedZipCode = 88305;

        $sepomex = new SepomexPhp(new Gateway($this->pdo()));
        $zipcode = $sepomex->getZipCodeData($expectedZipCode);
        if (null === $zipcode) {
            $this->fail("Expected information of zip code $expectedZipCode was not found");
            return;
        }

        $data = $zipcode->asArray();

        $this->assertArraySubset(['zipcode' => $expectedZipCode], $data);
        $this->assertArraySubset(['state' => ['name' => 'Tamaulipas']], $data);
        $this->assertArraySubset(['district' => ['name' => 'Miguel Alemán']], $data);
        $this->assertArraySubset(['cities' => [['name' => 'Ciudad Miguel Alemán']]], $data);
        $this->assertArraySubset(['locations' => [['name' => 'Adolfo López Mateos']]], $data);
        $this->assertCount(5, $data['locations']);
    }
}

<?php
namespace SepomexPhpTests\Cases;

use SepomexPhp\PdoGateway\Gateway;
use SepomexPhp\SepomexPhp;
use SepomexPhpTests\TestCase;

class ZipCodeDataTest extends TestCase
{
    public function testGetZipCodeDataOnNotFound()
    {
        $sepomex = new SepomexPhp(new Gateway($this->pdo()));
        $this->assertNull($sepomex->getZipCodeData('00001'));
    }

    public function testZipCodeCheck()
    {
        $expectedZipCode = 88305;

        $sepomex = new SepomexPhp(new Gateway($this->pdo()));
        $zipcode = $sepomex->getZipCodeData($expectedZipCode);
        if (null === $zipcode) {
            $this->fail("Expected information of zip code $expectedZipCode was not found");
            return;
        }

        $data = $zipcode->asArray();

        $this->assertArraySubset(['zipcode' => $expectedZipCode], $data);
        $this->assertArraySubset(['state' => ['name' => 'Tamaulipas']], $data);
        $this->assertArraySubset(['district' => ['name' => 'Miguel Alemán']], $data);
        $this->assertArraySubset(['cities' => [['name' => 'Ciudad Miguel Alemán']]], $data);
        $this->assertArraySubset(['locations' => [['name' => 'Adolfo López Mateos']]], $data);
        $this->assertCount(5, $data['locations']);
    }
}

Test that getZipCodeData return null when not found


<?php

class Admin_Page_Abstract extends CM_Page_Abstract {

    /** @var  Denkmal_Params */
    protected $_params;

    /** @var Denkmal_Model_Region|null */
    protected $_region;

    public function prepareResponse(CM_Frontend_Environment $environment, CM_Http_Response_Page $response) {
        $session = $response->getRequest()->getSession();
        if ($session->has('region')) {
            $this->_region = new Denkmal_Model_Region($session->get('region'));
        }
    }

    public function checkAccessible(CM_Frontend_Environment $environment) {
        if (!$environment->getViewer(true)->getRoles()->contains(Denkmal_Role::ADMIN, Denkmal_Role::PUBLISHER)) {
            throw new CM_Exception_AuthRequired();
        }
    }

    /**
     * @return Denkmal_Model_Region
     * @throws CM_Exception
     */
    protected function _getRegion() {
        if (!$this->_hasRegion()) {
            throw new CM_Exception('No region available in session');
        }
        return $this->_region;
    }

    /**
     * @return bool
     */
    protected function _hasRegion() {
        return null !== $this->_region;
    }
}

<?php

class Admin_Page_Abstract extends CM_Page_Abstract {

    /** @var  Denkmal_Params */
    protected $_params;

    /** @var Denkmal_Model_Region|null */
    protected $_region;

    public function prepareResponse(CM_Frontend_Environment $environment, CM_Http_Response_Page $response) {
        $site = $response->getSite();
        if ($site instanceof Denkmal_Site_Default && $site->hasRegion()) {
            $this->_region = $site->getRegion();
        }
    }

    public function checkAccessible(CM_Frontend_Environment $environment) {
        if (!$environment->getViewer(true)->getRoles()->contains(Denkmal_Role::ADMIN, Denkmal_Role::PUBLISHER)) {
            throw new CM_Exception_AuthRequired();
        }
    }

    /**
     * @return Denkmal_Model_Region
     * @throws CM_Exception
     */
    protected function _getRegion() {
        if (!$this->_hasRegion()) {
            throw new CM_Exception('No region available in session');
        }
        return $this->_region;
    }

    /**
     * @return bool
     */
    protected function _hasRegion() {
        return null !== $this->_region;
    }
}

Use site's region in admin page

Use site's region in admin page


<?php
declare(strict_types=1);

namespace Neos\Flow\Persistence;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A container for the list of allowed objects to be persisted during this request.
 *
 * @Flow\Scope("singleton")
 */
final class AllowedObjectsContainer extends \SplObjectStorage
{
    /**
     * @var bool
     */
    protected $checkNext = false;

    /**
     * Set the internal flag to return true for `shouldCheck()` on the next invocation.
     *
     * @param bool $checkNext
     */
    public function checkNext($checkNext = true)
    {
        $this->checkNext = $checkNext;
    }

    /**
     * Returns true if allowed objects should be checked this time and resets the internal flag to false,
     * so the next call will return false unless `checkNext(true)` is called again.
     *
     * @return bool
     */
    public function shouldCheck(): bool
    {
        $shouldCheck = $this->checkNext;
        $this->checkNext = false;
        return $shouldCheck;
    }
}

<?php
declare(strict_types=1);

namespace Neos\Flow\Persistence;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A container for the list of allowed objects to be persisted during this request.
 *
 * @Flow\Scope("singleton")
 */
final class AllowedObjectsContainer extends \SplObjectStorage
{
    /**
     * @var bool
     */
    protected $checkNext = false;

    /**
     * Set the internal flag to return true for `shouldCheck()` on the next invocation.
     *
     * @param bool $checkNext
     */
    public function checkNext(bool $checkNext = true): void
    {
        $this->checkNext = $checkNext;
    }

    /**
     * Returns true if allowed objects should be checked this time and resets the internal flag to false,
     * so the next call will return false unless `checkNext(true)` is called again.
     *
     * @return bool
     */
    public function shouldCheck(): bool
    {
        $shouldCheck = $this->checkNext;
        $this->checkNext = false;
        return $shouldCheck;
    }
}

!!!TASK: Add method argument and return type hints