<?php

/*
 * This file is part of the Indigo Guardian package.
 *
 * (c) Indigo Development Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Indigo\Guardian\Authenticator;

use BeatSwitch\Lock\Callers\Caller;
use Indigo\Guardian\Caller\User;
use Assert\Assertion;

/**
 * Authenticate using a username-password pair
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class UserPassword extends HasherAware
{
    /**
     * {@inheritdoc}
     */
    public function authenticate(array $subject, Caller $caller)
    {
        Assertion::choicesNotEmpty($subject, ['password']);
        Assertion::isInstanceOf(
            $caller,
            User::CLASS,
            sprintf('The caller was expected to be an instance of "%s"', User::CLASS)
        );

        return $this->hasher->verify($subject['password'], $caller->getPassword());
    }
}

<?php

/*
 * This file is part of the Indigo Guardian package.
 *
 * (c) Indigo Development Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Indigo\Guardian\Authenticator;

use BeatSwitch\Lock\Callers\Caller;
use Assert\Assertion;

/**
 * Authenticate using a username-password pair
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class UserPassword extends HasherAware
{
    /**
     * {@inheritdoc}
     */
    public function authenticate(array $subject, Caller $caller)
    {
        Assertion::choicesNotEmpty($subject, ['password']);
        Assertion::isInstanceOf(
            $caller,
            'Indigo\Guardian\Caller\User',
            sprintf('The caller was expected to be an instance of "%s"', 'Indigo\Guardian\Caller\User')
        );

        return $this->hasher->verify($subject['password'], $caller->getPassword());
    }
}

Revert to string based class name because of PHP 5.4 support


<?php

declare(strict_types=1);

namespace App\Sync\Task;

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

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

    public function run(bool $force = false): void
    {
        $threshold = time() - 60 * 60; // An hour ago

        $certs = CertificateLocator::findCertificate();

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

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

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

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

<?php

declare(strict_types=1);

namespace App\Sync\Task;

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

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

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

        $certs = CertificateLocator::findCertificate();

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

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

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

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

Use more reliable time threshold for SSL reload.


<?php

namespace UltraPress\Controllers;

class PageController extends BaseController
{

    /**
    * View the home page.
    */
    public static function getHome()
    {
        View::get('pages.home');
    }

}

<?php

namespace UltraPress\Controllers;

use UltraPress\View;

class PageController extends BaseController
{

    /**
    * View the home page.
    */
    public static function getHome()
    {
        View::get('pages.home');
    }

}

Add use statement to routes files

Add use statement to routes files


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

require_once('vendor/autoload.php');

use Vimeo;

$config = json_decode(file_get_contents('./config.json'), true);

$lib = new Vimeo($config['client_id'], $config['client_secret']);
$user = $lib->request('/users/dashron');
print_r($user);

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

require_once('vendor/autoload.php');

$config = json_decode(file_get_contents('./config.json'), true);

$lib = new Vimeo\Vimeo($config['client_id'], $config['client_secret']);
$user = $lib->request('/users/dashron');
print_r($user);

Remove use Vimeo and add Vimeo\Vimeo.

Remove use Vimeo and add Vimeo\Vimeo.


<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\HasAbilities;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, HasAbilities;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

Define HasAbilities trait on default user.


<?php

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

namespace Symfony\Bundle\DoctrineMigrationsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Bundle.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 */
class DoctrineMigrationsBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    /**
     * {@inheritdoc}
     */
    public function getPath()
    {
        return strtr(__DIR__, '\\', '/');
    }
}

<?php

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

namespace Symfony\Bundle\DoctrineMigrationsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Bundle.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 */
class DoctrineMigrationsBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    /**
     * {@inheritdoc}
     */
    protected function getPath()
    {
        return __DIR__;
    }
}

[Bundle] Make getPath() less error prone by allowing both backward and forward slashes


<?php

$settings = array(
  'Database' => array('Prefix' => 'blog_', 'Database' => './conf/production.sqlite'),
  'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'),
  'Defaults' => array('PostsVisible' => 5),
  'Environment' => array('Production' => !file_exists('/Users/jbrowne/Sites/'))
);

<?php

// Maximum number of posts to show on a journal page
$postsVisibleOnPage = 5;

// Whether in production mode or not
$isProduction = false;

// Calculate database file name and path from production switch
$databaseFileName = $isProduction ? 'production' : 'debug';
$databaseFilePath = './conf/' . $databaseFileName . '.sqlite';

// Prefix for database tables
$tablePrefix = 'blog_';

// Aggregated settings array - required for running the backend
$settings = array(
  'Database' => array('Prefix' => $tablePrefix, 'Database' => $databaseFilePath),
  'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'),
  'Defaults' => array('PostsVisible' => $postsVisibleOnPage),
  'Environment' => array('Production' => $isProduction)
);

Make settings template slightly more self-explanatory


@foreach (session('flash_notification', collect())->toArray() as $message)
    @if (isset($message['overlay'] && $message['overlay'])
        @include('flash::modal', [
            'modalClass' => 'flash-modal',
            'title'      => $message['title'],
            'body'       => $message['message']
        ])
    @else
        <div class="alert
                    alert-{{ $message['level'] }}
                    {{ $message['important'] ? 'alert-important' : '' }}"
        >
            @if ($message['important'])
                <button type="button"
                        class="close"
                        data-dismiss="alert"
                        aria-hidden="true"
                >×</button>
            @endif

            {!! $message['message'] !!}
        </div>
    @endif
@endforeach

{{ session()->forget('flash_notification') }}

@foreach (session('flash_notification', collect())->toArray() as $message)
    @if ($message['overlay'])
        @include('flash::modal', [
            'modalClass' => 'flash-modal',
            'title'      => $message['title'],
            'body'       => $message['message']
        ])
    @else
        <div class="alert
                    alert-{{ $message['level'] }}
                    {{ $message['important'] ? 'alert-important' : '' }}"
        >
            @if ($message['important'])
                <button type="button"
                        class="close"
                        data-dismiss="alert"
                        aria-hidden="true"
                >×</button>
            @endif

            {!! $message['message'] !!}
        </div>
    @endif
@endforeach

{{ session()->forget('flash_notification') }}

Fix me being an idiot

Fix me being an idiot


<?php

namespace DCS\RatingBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use DCS\RatingBundle\DCSRatingEvents;
use DCS\RatingBundle\Event\RatingEvent;
use Symfony\Component\DependencyInjection\Container;

class RatingUpdateInfoEventListener implements EventSubscriberInterface
{
    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    private $request;

    public function __construct(Container $container)
    {
        $container->enterScope('request');
        $container->set('request', new Request(), 'request');
        $this->request = $container->get('request');
    }

    public static function getSubscribedEvents()
    {
        return array(
            DCSRatingEvents::RATING_PRE_PERSIST => 'updatePermalink',
        );
    }

    public function updatePermalink(RatingEvent $event)
    {
        $rating = $event->getRating();

        if (null === $rating->getPermalink()) {
            $rating->setPermalink($this->request->get('permalink'));
        }

        if (null === $rating->getSecurityRole()) {
            $rating->setSecurityRole($this->request->get('securityRole'));
        }
    }
}

<?php

namespace DCS\RatingBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use DCS\RatingBundle\DCSRatingEvents;
use DCS\RatingBundle\Event\RatingEvent;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;

class RatingUpdateInfoEventListener implements EventSubscriberInterface
{
    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    private $request;

    public function __construct(Container $container)
    {
        $container->enterScope('request');
        $container->set('request', new Request(), 'request');
        $this->request = $container->get('request');
    }

    public static function getSubscribedEvents()
    {
        return array(
            DCSRatingEvents::RATING_PRE_PERSIST => 'updatePermalink',
        );
    }

    public function updatePermalink(RatingEvent $event)
    {
        $rating = $event->getRating();

        if (null === $rating->getPermalink()) {
            $rating->setPermalink($this->request->get('permalink'));
        }

        if (null === $rating->getSecurityRole()) {
            $rating->setSecurityRole($this->request->get('securityRole'));
        }
    }
}

Solve error with import Request class;

Solve error with import Request class;


<?php

namespace Omnipay\Stripe\Message;

/**
 * Stripe Purchase Request
 */
class PurchaseRequest extends AuthorizeRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['capture'] = 'true';

        return $data;
    }
}

<?php

namespace Omnipay\Stripe\Message;

/**
 * Stripe Purchase Request
 */
class PurchaseRequest extends AuthorizeRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['capture'] = 'true';
        $data['statement_description'] = $this->getStatementDescriptor();
        return $data;
    }

    public function setStatementDescriptor($value)
    {
        return $this->setParameter('statementDescriptor', $value);
    }

    public function getStatementDescriptor()
    {
        return $this->getParameter('statementDescriptor');
    }
}

Add support for statement descriptor

Add support for statement descriptor


<?php

/*
 * Core variables.
 *
 * Set up the site.
 */

//
// Meta
//

$encoding = 'utf-8';
$title = 'Site';
if (isset($slug)) {
  $title = "$slug · $title";
}
$description = "Personal site.";
$author = 'Mr. Ghost';
$keywords = 'site, website, web';
$robots = 'noodp,noydir';
$viewport = 'width=device-width, initial-scale=1.0';
$styles = "$root/assets/css/main.css";
$favicon = "$root/favicon.ico";

//
// Copyright
//

$cpowner = $author;
$cpyear = 2013;
$copyright = '© ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y')
                                    : '') . ' ' . $cpowner;

?>

<?php

/*
 * Core variables.
 *
 * Set up the site.
 */

//
// Meta
//

$encoding = 'utf-8';
$title = 'Site';
if (isset($slug)) {
  $title = "$slug · $title";
}
$description = "Personal site of Mr. Ghost.";
$author = 'Mr. Ghost';
$keywords = 'site, website, web';
$robots = 'noodp,noydir';
$viewport = 'width=device-width, initial-scale=1.0';
$styles = "$root/assets/css/main.css";
$favicon = "$root/favicon.ico";

//
// Copyright
//

$cpowner = $author;
$cpyear = 2013;
$copyright = '© ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y')
                                    : '') . ' ' . $cpowner;

?>

Fix $description to match with $author

Fix $description to match with $author


<?php
/**
 * @package ActiveRecord
 */
namespace ActiveRecord;

/**
 * Singleton to manage any and all database connections.
 *
 * @package ActiveRecord
 */
class ConnectionManager extends Singleton
{
	/**
	 * Array of {@link Connection} objects.
	 * @var array
	 */
	static private $connections = array();

	/**
	 * If $name is null then the default connection will be returned.
	 *
	 * @see Config
	 * @param string $name Optional name of a connection
	 * @return Connection
	 */
	public static function get_connection($name=null)
	{
		$config = Config::instance();
		$name = $name ? $name : $config->get_default_connection();

		if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection)
			self::$connections[$name] = Connection::instance($config->get_connection($name));

		return self::$connections[$name];
	}

	/**
	 * Drops the connection from the connection manager. Does not actually close it since there
	 * is no close method in PDO.
	 *
	 * @param string $name Name of the connection to forget about
	 */
	public static function drop_connection($name=null)
	{
		if (isset(self::$connections[$name]))
			unset(self::$connections[$name]);
	}
}

<?php
/**
 * @package ActiveRecord
 */
namespace ActiveRecord;

/**
 * Singleton to manage any and all database connections.
 *
 * @package ActiveRecord
 */
class ConnectionManager extends Singleton
{
	/**
	 * Array of {@link Connection} objects.
	 * @var array
	 */
	static private $connections = array();

	/**
	 * If $name is null then the default connection will be returned.
	 *
	 * @see Config
	 * @param string $name Optional name of a connection
	 * @return Connection
	 */
	public static function get_connection($name=null)
	{
		$config = Config::instance();
		$name = $name ? $name : $config->get_default_connection();

		if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection)
			self::$connections[$name] = Connection::instance($config->get_connection($name));

		return self::$connections[$name];
	}

	/**
	 * Drops the connection from the connection manager. Does not actually close it since there
	 * is no close method in PDO.
	 *
	 * If $name is null then the default connection will be returned.
	 *
	 * @param string $name Name of the connection to forget about
	 */
	public static function drop_connection($name=null)
	{
		$config = Config::instance();
		$name = $name ? $name : $config->get_default_connection();

		if (isset(self::$connections[$name]))
			unset(self::$connections[$name]);
	}
}

Fix drop_connection for the default connection

While `get_connection()` used `get_default_connection()` if there is no specific connection,
(aka `$name = null`) , `drop_connection()` didn't and therefore did not drop a connection
if no specific name was given.

In `Table::reestablish_connection()` the connection (name) is retrieved like this:

    $connection = $this->class->getStaticPropertyValue('connection',null);

This meant that if no static property 'connection' is set, the `$connection` will be `null`.
This should mean that the default connection is use, but currently nothing will be
dropped, which is a bug.
This fix changes that, so that if the default connection is used, the default connection is dropped.

An alternative might have been to change this in the call
(`Table::reestablish_connection()` for instance), but it seems to me that keeping
`drop_connection`'s behaviour the same as `get_connection()` is the best way.


<?php namespace CodeIgniter\Config;

use Config\Format;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('Format', false);
		$NamespaceConfig = Config::get('Config\\Format', false);

		$this->assertInstanceOf(Format::class, $Config);
		$this->assertInstanceOf(Format::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('Format' );
		$Config2 = Config::get('Config\\Format');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

<?php namespace CodeIgniter\Config;

use Config\DocTypes;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('DocTypes', false);
		$NamespaceConfig = Config::get('Config\\DocTypes', false);

		$this->assertInstanceOf(DocTypes::class, $Config);
		$this->assertInstanceOf(DocTypes::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('DocTypes' );
		$Config2 = Config::get('Config\\DocTypes');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

Remove Email module - missed tests

Remove Email module - missed tests


<?php

namespace App\Middleware;

use App\Service\JWTManager;
use Interop\Container\ContainerInterface;
use Cartalyst\Sentinel\Sentinel;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Router;

/**
 * @property Router router
 * @property Sentinel sentinel
 * @property JWTManager jwt
 */
abstract class Middleware
{
    /**
     * Slim application container
     *
     * @var ContainerInterface
     */
    protected $container;

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

    public abstract function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next);

    public function __get($property)
    {
        return $this->container->get($property);
    }
}

<?php

namespace App\Middleware;

use App\Service\JWTManager;
use Interop\Container\ContainerInterface;
use Cartalyst\Sentinel\Sentinel;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Router;

/**
 * @property Router router
 * @property Sentinel sentinel
 * @property JWTManager jwt
 */
abstract class Middleware
{
    /**
     * Slim application container
     *
     * @var ContainerInterface
     */
    protected $container;

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

    abstract public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next);

    public function __get($property)
    {
        return $this->container->get($property);
    }
}

Put 'abstract' keyword before visibility to follow psr-2 standard


<?php

if (($RESTRICTED_OBJECTS_DIR = basename(dirname(__FILE__))) != 'restrictedobjects') {
	die("The restricted objects module must be installed in /restrictedobjects, not $RESTRICTED_OBJECTS_DIR");
}

if (!class_exists('MultiValueField')) {
	die('The restricted objects module requires the multivaluefield module from http://github.com/nyeholt/silverstripe-multivaluefield');
}

Director::addRules(100, array(
	'Security/logout' => 'RestrictedSecurityController',
));

Object::add_extension('Member', 'RestrictedMember');

// if we're in Dev, and have set "no initial checks", which is common during testing, disable perms
if ((Director::isDev() || Director::is_cli()) && isset($_GET['disable_perms'])) {
	Restrictable::set_enabled(false);
}

SS_Cache::set_cache_lifetime('restricted_perms', 3600);

FIX Updated cache lifetime for permissions to be 1hr by default


<?php

namespace Michaeljennings\Carpenter\Contracts;

use Closure;

interface Carpenter
{
    /**
     * Add a table closure into the table collection
     *
     * @param string          $name
     * @param callable|string $table
     */
    public function add($name, $table);

    /**
     * Retrieve a table from the table collection and run the closure
     *
     * @param  string $name
     * @return Table
     * @throws CarpenterCollectionException
     */
    public function get($name);

    /**
     * Create a new table without using the table collection.
     *
     * @param string   $name
     * @param callable $callback
     * @return Table
     */
    public function make($name, Closure $callback);
}

<?php

namespace Michaeljennings\Carpenter\Contracts;

use Closure;

interface Carpenter
{
    /**
     * Add a table closure into the table collection
     *
     * @param string          $name
     * @param callable|string $table
     */
    public function add($name, $table);

    /**
     * Retrieve a table from the table collection and run the closure
     *
     * @param  string $name
     * @return Table
     * @throws CarpenterCollectionException
     */
    public function get($name);

    /**
     * Create a new table without using the table collection.
     *
     * @param string   $name
     * @param callable $callback
     * @return Table
     */
    public function make($name, Closure $callback);

    /**
     * Set a manager extension.
     *
     * @param string         $manager
     * @param string         $key
     * @param string|Closure $extension
     * @return $this
     */
    public function extend($manager, $key, $extension);
}

Add extend method to carpenter contract

Add extend method to carpenter contract


<?php

namespace App;

use Nette;
use Nette\Application\Routers\RouteList;
use Nette\Application\Routers\Route;

class RouterFactory
{
	use Nette\StaticClass;

	/**
	 * @return Nette\Application\IRouter
	 */
	public static function createRouter()
	{
		$router = new RouteList;

		$router[] = new Route('song/', 'Song:list');
		$router[] = new Route('song[/<id>]', 'Song:detail');
		$router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default');

		return $router;
	}

}

<?php

namespace App;

use Nette;
use Nette\Application\Routers\RouteList;
use Nette\Application\Routers\Route;

class RouterFactory
{
	use Nette\StaticClass;

	/**
	 * @return Nette\Application\IRouter
	 */
	public static function createRouter()
	{
		$router = new RouteList;

		$router[] = new Route('song/', 'Song:list');
		$router[] = new Route('song/add', 'Song:add');
		$router[] = new Route('song[/<id>]', 'Song:detail');
		$router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default');

		return $router;
	}

}

Change route to add song

SongManager: Change route to add song


<?php
/**
 * ZnZend
 *
 * @author Zion Ng <zion@intzone.com>
 * @link   http://github.com/zionsg/ZnZend for canonical source repository
 */

namespace ZnZend;

use Zend\Db\TableGateway\Feature\GlobalAdapterFeature;
use Zend\Mvc\MvcEvent;

class Module
{
    /**
     * Set global/static db adapter for feature-enabled TableGateways such as ZnZend\Model\AbstractTable
     */
    public function onBootstrap(MvcEvent $e)
    {
        $sm = $e->getApplication()->getServiceManager();
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
        GlobalAdapterFeature::setStaticAdapter($dbAdapter);
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig($env = null)
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

<?php
/**
 * ZnZend
 *
 * @author Zion Ng <zion@intzone.com>
 * @link   http://github.com/zionsg/ZnZend for canonical source repository
 */

namespace ZnZend;

use Zend\Db\TableGateway\Feature\GlobalAdapterFeature;
use Zend\Mvc\MvcEvent;

class Module
{
    /**
     * Set global/static db adapter for feature-enabled TableGateways such as ZnZend\Model\AbstractTable
     */
    public function onBootstrap(MvcEvent $e)
    {
        $sm = $e->getApplication()->getServiceManager();
        if ($sm->has('Zend\Db\Adapter\Adapter')) {
            GlobalAdapterFeature::setStaticAdapter($sm->get('Zend\Db\Adapter\Adapter'));
        }
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig($env = null)
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

Set global db adapter only if there is one


<?php

namespace XmlTv\Tv;

class Programme
{
    const DATE_FORMAT = 'YmdHis';

    /**
     * @var string
     */
    public $start;

    /**
     * @var string
     */
    public $stop;

    /**
     * @var string
     */
    public $channel;

    /**
     * @var string
     */
    public $title;

    /**
     * @var string
     */
    public $subTitle;

    /**
     * @var string
     */
    public $desc;

    /**
     * @var Category[]
     */
    private $categories = [];

    /**
     * Programme constructor.
     *
     * @param string $start
     * @param string $stop
     * @param string $channel
     */
    public function __construct(string $start, string $stop, string $channel)
    {
        $this->start = $start;
        $this->stop = $stop;
        $this->channel = $channel;
    }

    /**
     * Add a category.
     *
     * @param Category $category
     */
    public function addCategory(Category $category)
    {
        array_push($this->categories, $category);
    }

    /**
     * Get all categories.
     *
     * @return array
     */
    public function getCategories()
    {
        return $this->categories;
    }
}

<?php

namespace XmlTv\Tv;

class Programme
{
    const DATE_FORMAT = 'YmdHis O';

    /**
     * @var string
     */
    public $start;

    /**
     * @var string
     */
    public $stop;

    /**
     * @var string
     */
    public $channel;

    /**
     * @var string
     */
    public $title;

    /**
     * @var string
     */
    public $subTitle;

    /**
     * @var string
     */
    public $desc;

    /**
     * @var Category[]
     */
    private $categories = [];

    /**
     * Programme constructor.
     *
     * @param string $start
     * @param string $stop
     * @param string $channel
     */
    public function __construct(string $start, string $stop, string $channel)
    {
        $this->start = $start;
        $this->stop = $stop;
        $this->channel = $channel;
    }

    /**
     * Add a category.
     *
     * @param Category $category
     */
    public function addCategory(Category $category)
    {
        array_push($this->categories, $category);
    }

    /**
     * Get all categories.
     *
     * @return array
     */
    public function getCategories()
    {
        return $this->categories;
    }
}

Add timezone to programme date format

Add timezone to programme date format


<?php
/**
 * User: matt
 * Date: 20/06/14
 * Time: 16:22
 */

class EHServerBuilder {

    private $driveBuilder;

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

    public function build (Server $server) {

        // first make drives

        // then make servers
    }
}

<?php
/**
 * User: matt
 * Date: 20/06/14
 * Time: 16:22
 */

class EHServerBuilder {

    public function __construct() {

    }

    public function build (Server $server) {

        // then make servers
    }
}

Change constructor to add dependency on DriveBuilder


<?php

	Class migration_241 extends Migration {

		static $publish_filtering_disabled = false;

		static function getVersion(){
			return '2.4.1';
		}

		static function getReleaseNotes(){
			return 'http://getsymphony.com/download/releases/version/2.4.1/';
		}

		static function upgrade() {
			// Add association interfaces
			try {
				Symphony::Database()->query('
					ALTER TABLE `tbl_fields_date`
					ADD `interface` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
					ADD `editor` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL;
				');
			}
			catch (Exception $ex) {}

			// Update the version information
			return parent::upgrade();
		}

		static function preUpdateNotes(){
			return array();
		}

		static function postUpdateNotes(){
			return array();
		}

	}

<?php

	Class migration_241 extends Migration {

		static $publish_filtering_disabled = false;

		static function getVersion(){
			return '2.4.1';
		}

		static function getReleaseNotes(){
			return 'http://getsymphony.com/download/releases/version/2.4.1/';
		}

		static function upgrade() {
			// Add association interfaces
			try {
				Symphony::Database()->query('
					ALTER TABLE `tbl_sections_association`
					ADD `interface` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
					ADD `editor` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL;
				');
			}
			catch (Exception $ex) {}

			// Update the version information
			return parent::upgrade();
		}

		static function preUpdateNotes(){
			return array();
		}

		static function postUpdateNotes(){
			return array();
		}

	}

Fix copy and paste error

Fix copy and paste error


<?php namespace Linko\Spam;

class SpamFilter
{
    /**
     * Holds registed spam detectors
     *
     * @var SpamDetectorInterface[]
     */
    private $_spamDetectors = array();

    /**
     * Checks if a string is spam or not
     *
     * @param $string
     *
     * @return SpamResult
     */
    public function check($string)
    {
        $failure = 0;

        foreach ($this->getDetectors() as $spamDetector) {
            if($spamDetector->detect($string)) {
                $failure++;
            }
        }

        return new SpamResult($failure > 0 ? true : false);
    }

    /**
     * Registers a Spam Detector
     *
     * @param SpamDetectorInterface $spamDetector
     *
     * @return SpamFilter
     */
    public function registerDetector(SpamDetectorInterface $spamDetector)
    {
        $detectorClass = get_class($spamDetector);
        $this->_spamDetectors[$detectorClass] = $spamDetector;

        return $this;
    }

    /**
     * Gets a list of all spam detectors
     *
     * @return SpamDetectorInterface[]
     */
    public function getDetectors()
    {
        return $this->_spamDetectors;
    }
}

<?php namespace Linko\Spam;

class SpamFilter
{
    /**
     * Holds registed spam detectors
     *
     * @var SpamDetectorInterface[]
     */
    private $_spamDetectors = array();

    /**
     * Checks if a string is spam or not
     *
     * @param $string
     *
     * @return SpamResult
     */
    public function check($string)
    {
        $failure = 0;
        $string = $this->_normalizeString($string);

        foreach ($this->getDetectors() as $spamDetector) {
            if($spamDetector->detect($string)) {
                $failure++;
            }
        }

        return new SpamResult($failure > 0 ? true : false);
    }

    /**
     * Registers a Spam Detector
     *
     * @param SpamDetectorInterface $spamDetector
     *
     * @return SpamFilter
     */
    public function registerDetector(SpamDetectorInterface $spamDetector)
    {
        $detectorClass = get_class($spamDetector);
        $this->_spamDetectors[$detectorClass] = $spamDetector;

        return $this;
    }

    /**
     * Gets a list of all spam detectors
     *
     * @return SpamDetectorInterface[]
     */
    public function getDetectors()
    {
        return $this->_spamDetectors;
    }

    /**
     * Used to normalize string before passing
     * it to detectors
     *
     * @param string $string
     *
     * @return string
     */
    private function _normalizeString($string)
    {
        return trim(strtolower($string));
    }
}

Normalize string before passing it to detectors


<?php

declare(strict_types=1);

namespace example;

use function Widmogrod\Monad\Control\Doo\doo;
use function Widmogrod\Monad\Control\Doo\in;
use function Widmogrod\Monad\Control\Doo\let;
use Widmogrod\Monad\Identity;

class FreeDooDSLTest extends \PHPUnit\Framework\TestCase
{
    public function test_it()
    {
        $result = doo(
            let('a', Identity::of(1)),
            let('b', Identity::of(3)),
            let('c', in(['a', 'b'], function (int $a, int $b): Identity {
                return Identity::of($a + $b);
            })),
            in(['c'], function (int $c): Identity {
                return Identity::of($c * $c);
            })
        );

        $this->assertEquals(Identity::of(16), $result);
    }
}

<?php

declare(strict_types=1);

namespace example;

use Widmogrod\Monad\Identity;
use function Widmogrod\Monad\Control\Doo\doo;
use function Widmogrod\Monad\Control\Doo\in;
use function Widmogrod\Monad\Control\Doo\let;

class FreeDooDSLTest extends \PHPUnit\Framework\TestCase
{
    public function test_example_with_do_notation()
    {
        $result = doo(
            let('a', Identity::of(1)),
            let('b', Identity::of(3)),
            let('c', in(['a', 'b'], function (int $a, int $b): Identity {
                return Identity::of($a + $b);
            })),
            in(['c'], function (int $c): Identity {
                return Identity::of($c * $c);
            })
        );

        $this->assertEquals(Identity::of(16), $result);
    }

    public function test_example_without_do_notation()
    {
        $result = Identity::of(1)
            ->bind(function ($a) {
                return Identity::of(3)
                    ->bind(function ($b) use ($a) {
                        return Identity::of($a + $b)
                            ->bind(function ($c) {
                                return Identity::of($c * $c);
                            });
                    });

            });

        $this->assertEquals(Identity::of(16), $result);
    }
}

Introduce contra example - how control flow looks like without do notation

Introduce contr example - how control flow looks like without do notation


<?php

namespace AppBundle\Tests\Controller;

class DreamControllerTest extends AbstractApiTest
{
    public function testGetDreamsAction()
    {
        $client   = static::createClient();
        $crawler  = $client->request('GET', '/dreams');

        $response = $client->getResponse();

        $this->assertJsonResponse($response, 200);
    }

    public function testGetDreamAction()
    {
        $client   = static::createClient();
        $crawler  = $client->request('GET', '/dreams/sunt');

        $response = $client->getResponse();

        $this->assertJsonResponse($response, 200);
    }
}

<?php

namespace AppBundle\Tests\Controller;

class DreamControllerTest extends AbstractApiTest
{
    /**
     * @dataProvider providerData
     */
    public function testGetDreamsAction($status,$limit,$sort_by,$sort_order)
    {
        $client   = static::createClient();

        $crawler  = $client->request('GET', '/dreams?limit=4&status=submitted&sort_by=status_update&sort_order=DESC');

        $response = $client->getResponse();

        $this->assertJsonResponse($response, 200);

        $this->assertTrue(
            $client->getResponse()->headers->contains(
                'Content-Type',
                'application/json'
            )
        );

        $this->assertEquals($client->getRequest()->query->get('status'),$status);
        $this->assertEquals($client->getRequest()->query->get('limit'),$limit);
        $this->assertEquals($client->getRequest()->query->get('sort_by'),$sort_by);
        $this->assertEquals($client->getRequest()->query->get('sort_order'),$sort_order);
    }

    public function testGetDreamAction()
    {
        $client   = static::createClient();
        $crawler  = $client->request('GET', '/dreams/sunt');

        $response = $client->getResponse();

        $this->assertJsonResponse($response, 200);
    }

    public function providerData(){
        return [
            ['submitted',4,'status_update','DESC']
        ];
    }
}

Create simple test on filters

Create simple test on filters


<?php
    namespace DB\Schema;

    class MySQLi implements ISchema
    {
        private $fields = array();

        public function addField($field)
        {
            $this->fields[] = "`$field->name` $field->type".($field->null?'':' NOT NULL ').
                ($field->autoinc?' AUTO_INCREMENT ':'');
        }

        public function create($table)
        {
            $fs = '';

            foreach ($this->fields as $field)
            {
                if ($fs === '')
                {
                    $fs = $field;
                }
                else
                {
                    $fs .= ', '. $field;
                }
            }

            $sql = "CREATE TABLE `$table` ($fs)";
            echo "$sql";
            //$this->db->query($sql);
        }
    }
?>

<?php
    namespace DB\Schema;

    class MySQLi implements ISchema
    {
        private $fields = array();
        private $cons = array();

        public function addField($field)
        {
            $this->fields[] = "`$field->name` $field->type".($field->null?'':' NOT NULL ').
                ($field->autoinc?' AUTO_INCREMENT ':'');
        }

        public function addConstraint($cons)
        {
            $k = '';
            switch ($cons->type) {
                case \DB\SchemaConstraint::TYPE_PRIMARY:
                    $k = 'PRIMARY KEY';
                    break;
                case \DB\SchemaConstraint::TYPE_UNIQUE:
                    $k = 'UNIQUE KEY';
                    break;
                case \DB\SchemaConstraint::TYPE_INDEX:
                    $k = 'INDEX KEY';
                    break;
            }

            $this->cons[] = "$k (`$cons->name`)";
        }
        public function create($table)
        {
            $fs = '';

            foreach ($this->fields as $field)
            {
                if ($fs === '')
                {
                    $fs = $field;
                }
                else
                {
                    $fs .= ', '. $field;
                }
            }

            foreach ($this->cons as $cons)
            {
                $fs .= ', '. $cons;
            }

            $sql = "CREATE TABLE `$table` ($fs)";
            $result = $this->db->query($sql);

            return !($result->isError());
        }
    }
?>

Add method to add constraint

Add method to add constraint


<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Проверяет слово "карма" и выводит статус
 *
 * Class KarmaRenderMiddleware
 * @package App\Gitter\Middleware
 */
class KarmaRenderMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        if (trim(mb_strtolower($message->text)) === 'карма') {
            $args = [
                'user' => $message->user->login,
                'karma' => $message->user->karma_text,
                'thanks' => $message->user->thanks_text
            ];

            $karmaMessage = $args['karma']
                ? \Lang::get('karma.count.message', $args)
                : \Lang::get('karma.count.empty', $args);

            $achievements = [];
            foreach ($message->user->achievements as $achieve) {
                $achievements[] = '"' . $achieve->title . '"';
            }

            if (count($achievements)) {
                $karmaMessage .= ("\n" . '- Достижения: ' . implode(', ', $achievements));
            }

            $message->italic($karmaMessage);
        }

        return $message;
    }
}

<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Проверяет слово "карма" и выводит статус
 *
 * Class KarmaRenderMiddleware
 * @package App\Gitter\Middleware
 */
class KarmaRenderMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        if (trim(mb_strtolower($message->text)) === 'карма') {
            $args = [
                'user' => $message->user->login,
                'karma' => $message->user->karma_text,
                'thanks' => $message->user->thanks_text
            ];

            $karmaMessage = $args['karma']
                ? \Lang::get('karma.count.message', $args)
                : \Lang::get('karma.count.empty', $args);

            $achievements = [];
            foreach ($message->user->achievements as $achieve) {
                $achievements[] = '"' . $achieve->title . '"';
            }

            if (count($achievements)) {
                $karmaMessage .= ("\n" . '- Достижения: ' . implode(', ', $achievements));
            }

            $karmaMessage .= "\n" . sprintf(
                '- [Профиль %s на laravel.su](http://karma.laravel.su/user/%s)',
                $message->user->login,
                $message->user->login
            );

            $message->italic($karmaMessage);
        }

        return $message;
    }
}

Add profile link inside karma render

Add profile link inside karma render


<?php

use Carbon\Carbon;

class CharacterLocation
{
	public $character_id;
	public $system_id;
	public $updated_at;

	public function __construct($props)
	{
		foreach ($props as $key => $value)
		{
			$this->$key = $value;
		}
	}

	public static function find(int $id)
	{
		$data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id')
												->param(':id', $id)
												->execute()
												->current();

		if($data != null)
		{
			return new CharacterLocation($data);
		}

		return null;
	}

	public static function findWithinCutoff(int $id, int $cutoffTimeMins = 1)
	{
		$cutoff = Carbon::now()->subMinutes($cutoffTimeMins)->toDateTimeString();
		$data = DB::query(Database::SELECT, 'SELECT * FROM character_location
											WHERE character_id=:id
											AND updated_at >= :cutoff')
												->param(':id', $id)
												->param(':cutoff', $cutoff)
												->execute()
												->current();

		if($data != null)
		{
			return new CharacterLocation($data);
		}

		return null;
	}
}

<?php

use Carbon\Carbon;

class CharacterLocation
{
	public $character_id;
	public $system_id;
	public $updated_at;

	public function __construct($props)
	{
		foreach ($props as $key => $value)
		{
			$this->$key = $value;
		}
	}

	public static function find(int $id)
	{
		$data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id')
												->param(':id', $id)
												->execute()
												->current();

		if($data != null)
		{
			return new CharacterLocation($data);
		}

		return null;
	}

	public static function findWithinCutoff(int $id, int $cutOffSeconds = 15)
	{
		$cutoff = Carbon::now()->subSeconds($cutOffSeconds)->toDateTimeString();
		$data = DB::query(Database::SELECT, 'SELECT * FROM character_location
											WHERE character_id=:id
											AND updated_at >= :cutoff')
												->param(':id', $id)
												->param(':cutoff', $cutoff)
												->execute()
												->current();

		if($data != null)
		{
			return new CharacterLocation($data);
		}

		return null;
	}
}

Reduce location cutoff and make it in seconds. Avoids issues with out of date locations.


<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
    <channel>
        <title>{{ $app_name }} Update</title>
        <description>New version available.</description>
        <language>en</language>
        <item>
            <title>Version {{ $version_name }}</title>
            <description>
                <![CDATA[

                    @foreach ($changes AS $change)

{{ $change }}

                    @endforeach

                ]]>
            </description>
            <pubDate>{{ $date }}</pubDate>
            <enclosure url="{{ url('/') }}/releases/{{ $file_name }}-{{ $version_number }}-{{ $platform }}.msi" length="0" sparkle:os="windows" sparkle:installerArguments="/quiet" sparkle:version="{{ $version_number }}" type="application/octet-stream"/>
        </item>
    </channel>
</rss>

<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
    <channel>
        <title>{{ $app_name }} Update</title>
        <description>New version available.</description>
        <language>en</language>
        <item>
            <title>Version {{ $version_name }}</title>
            <description>
                <![CDATA[

                    @foreach ($changes AS $change)

{{ $change }}

                    @endforeach

                ]]>
            </description>
            <pubDate>{{ $date }}</pubDate>
            <enclosure url="{{ url('/') }}/releases/{{ $file_name }}-{{ $version_number }}-{{ $platform }}.msi" length="0" sparkle:os="windows" sparkle:installerArguments="/quiet /norestart" sparkle:version="{{ $version_number }}" type="application/octet-stream"/>
        </item>
    </channel>
</rss>

Add /norestart flag to updater.

Add /norestart flag to updater.


<?php
namespace tests;
use LazyRecord\BaseModel;

class Wine extends BaseModel
{
    function schema($schema)
    {
        $schema->column('name')
            ->varchar(128);

        $schema->column('years')
            ->integer();
    }
}

<?php
namespace tests;
use LazyRecord\BaseModel;

class Wine extends BaseModel
{
    function schema($schema)
    {
        $schema->column('name')
            ->varchar(128);

        $schema->column('years')
            ->integer();
    }
#boundary start 7c7b528eb73d02172dcec82d792e1699
const schema_proxy_class = 'tests\\WineSchemaProxy';
const collection_class = 'tests\\WineCollection';
const model_class = 'tests\\Wine';
const table = 'wines';
#boundary end 7c7b528eb73d02172dcec82d792e1699
}

Use class injector to inject class contents


<?php

namespace Amp\Parallel\Worker;

interface Environment extends \ArrayAccess
{
    /**
     * @param string $key
     *
     * @return bool
     */
    public function exists(string $key);

    /**
     * @param string $key
     *
     * @return mixed|null Returns null if the key does not exist.
     */
    public function get(string $key);

    /**
     * @param string $key
     * @param mixed $value Using null for the value deletes the key.
     * @param int $ttl Number of seconds until data is automatically deleted. Use 0 for unlimited TTL.
     */
    public function set(string $key, $value, int $ttl = null);

    /**
     * @param string $key
     */
    public function delete(string $key);

    /**
     * Removes all values.
     */
    public function clear();
}

<?php

namespace Amp\Parallel\Worker;

interface Environment extends \ArrayAccess
{
    /**
     * @param string $key
     *
     * @return bool
     */
    public function exists(string $key): bool;

    /**
     * @param string $key
     *
     * @return mixed|null Returns null if the key does not exist.
     */
    public function get(string $key);

    /**
     * @param string $key
     * @param mixed $value Using null for the value deletes the key.
     * @param int $ttl Number of seconds until data is automatically deleted. Use 0 for unlimited TTL.
     */
    public function set(string $key, $value, int $ttl = null);

    /**
     * @param string $key
     */
    public function delete(string $key);

    /**
     * Removes all values.
     */
    public function clear();
}

Declare return type on exists()

Declare return type on exists()


<?php
/**
 * TinkerPlugin Controller
 */

namespace TinkerPlugin\Controller;

/**
 * TinkerPlugin Controller
 *
 * Just a mock up of a controller
 */
class TinkerPluginController extends \Tinker\Mvc\Controller
{

    /**
     * Provides a default landing page for TinkerMVC
     *
     * Sets View::vars an example of how to inject variables into the view
     *
     * @return void
     */
    public function index()
    {
        $this->View->vars['welcome'] = $this->TinkerPlugin->welcome();
    }

}

<?php
/**
 * TinkerPlugin Controller
 */

namespace TinkerPlugin\Controller;

/**
 * TinkerPlugin Controller
 *
 * Just a mock up of a controller
 */
class TinkerPluginController extends \Tinker\Mvc\Controller
{

    /**
     * Provides a default landing page for TinkerMVC
     *
     * Sets View::vars an example of how to inject variables into the view
     *
     * @return void
     */
    public function index()
    {
        $this->Theme->setTheme('TinkerPlugin');
        $this->View->vars['welcome'] = $this->TinkerPlugin->welcome();
    }

}

Set the tinker_plugin theme from the tinker_plugin controller.


<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == 'jamendo://') {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == 'track/stream/') {
		$id = substr($url, 23);
		return 'http://api.jamendo.com/get2/stream/track/redirect/?id=' . $id . '&streamencoding=ogg2';
	}

	if (substr($url, 10, 15) == 'album/download/') {
		$id = substr($url, 25);
		return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
	}

	if (substr($url, 10, 10) == 'album/art/') {
		$id = substr($url, 20);
		return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
	}

	// We don't know what this is
	return $url;
}

<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == 'jamendo://') {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == 'track/stream/') {
		$id = substr($url, 23);
		return 'http://gigue.rrbone.net/' . $id . '.ogg2';
	}

	if (substr($url, 10, 15) == 'album/download/') {
		$id = substr($url, 25);
		return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
	}

	if (substr($url, 10, 10) == 'album/art/') {
		$id = substr($url, 20);
		return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
	}

	// We don't know what this is
	return $url;
}

Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime.


<?php

class ReeCreate_PageTitle_Model_Observer
{
    /**
     * Change product or category page titles
     *
     * @pram Varien_Event_Observer $observer
     * @return ReeCreate_PageTitle_Model_Observer
     */
    public function controller_action_layout_generate_blocks_after(Varien_Event_Observer $observer)
    {
        $head = $observer->getLayout()->getBlock('head');

        if(Mage::registry('current_product'))
        {
            $title = Mage::registry('current_product')->getName();
        }

        if(Mage::registry('current_category') && empty($title))
        {
            $title = Mage::registry('current_category')->getName();
        }

        $head->setTitle($title);
    }
}

<?php

class ReeCreate_PageTitle_Model_Observer
{
    /**
     * Change product or category page titles
     *
     * @pram Varien_Event_Observer $observer
     * @return ReeCreate_PageTitle_Model_Observer
     */
    public function controller_action_layout_generate_blocks_after(Varien_Event_Observer $observer)
    {
        $head = $observer->getLayout()->getBlock('head');

        if(Mage::registry('current_product'))
        {
            $title = Mage::registry('current_product')->getName();
        }

        if(Mage::registry('current_category') && empty($title))
        {
            $title = Mage::registry('current_category')->getName();
        }

        if(!empty($title))
        {
            $head->setTitle($title);
        }
    }
}

Check For Empty String On Page Title Update

This commit fixes #8


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

use const E_WARNING;
use function restore_error_handler;
use function set_error_handler;
use function var_export;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class VariableExporter
{
    public function export(mixed $variable): ExportedVariable
    {
        $warningWasTriggered = false;

        set_error_handler(
            static function (int $errorNumber, string $errorString) use (&$warningWasTriggered): void {
                $warningWasTriggered = true;
            },
            E_WARNING
        );

        $exportedVariable = var_export($variable, true);

        restore_error_handler();

        return ExportedVariable::from($exportedVariable, $warningWasTriggered);
    }
}

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

use const E_WARNING;
use function restore_error_handler;
use function set_error_handler;
use function var_export;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class VariableExporter
{
    public function export(mixed $variable): ExportedVariable
    {
        $warningWasTriggered = false;

        set_error_handler(
            static function (int $errorNumber, string $errorString) use (&$warningWasTriggered): ?bool {
                $warningWasTriggered = true;

                return null;
            },
            E_WARNING
        );

        $exportedVariable = var_export($variable, true);

        restore_error_handler();

        return ExportedVariable::from($exportedVariable, $warningWasTriggered);
    }
}

Fix issue identified by Psalm

Fix issue identified by Psalm

Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>
Co-authored-by: Sebastian Bergmann <b70482a9c35b236639019cd8b2ecb03a9ee7db09@sebastian-bergmann.de>


<?php

namespace Packagist\WebBundle\Twig;

use Symfony\Bridge\Doctrine\RegistryInterface;

class PackagistExtension extends \Twig_Extension
{
    /**
     * @var \Symfony\Bridge\Doctrine\RegistryInterface
     */
    private $doctrine;

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

    public function getTests()
    {
        return array(
            'existing_package' => new \Twig_Test_Method($this, 'packageExistsTest')
        );
    }

    public function getName()
    {
        return 'packagist';
    }

    public function packageExistsTest($package)
    {
        if (!preg_match('/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/', $package)) {
            return false;
        }

        return $this->doctrine->getRepository('PackagistWebBundle:Package')
            ->packageExists($package);
    }
}

<?php

namespace Packagist\WebBundle\Twig;

use Symfony\Bridge\Doctrine\RegistryInterface;

class PackagistExtension extends \Twig_Extension
{
    /**
     * @var \Symfony\Bridge\Doctrine\RegistryInterface
     */
    private $doctrine;

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

    public function getTests()
    {
        return array(
            'existing_package' => new \Twig_Test_Method($this, 'packageExistsTest')
        );
    }

    public function getName()
    {
        return 'packagist';
    }

    public function packageExistsTest($package)
    {
        if (!preg_match('/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/', $package)) {
            return false;
        }

        return $this->doctrine->getRepository('PackagistWebBundle:Package')
            ->packageExists($package);
    }
}

Add bounds to the package name regex

Add bounds to the package name regex


Fix issue found by Scrutinizer.

Fix issue found by Scrutinizer.


<?php

namespace Nectary\Facades;

use Nectary\Models\Json_Feed;
use Nectary\Facades\Rss_Facade;

class Generic_Json_Facade extends Rss_Facade {
  private $url;

  public function load_dependencies() {
    return array( $this, 'get_feed' );
  }

  public function get_feed( $url ) {
    $this->url = $url;

    return new Json_Feed( $url, array( $this, 'get_curl_feed_data' ) );
  }

  public function get_curl_feed_data() {
    $session = curl_init( $url );

    curl_setopt( $session, CURLOPT_RETURNTRANSFER, true );

    $json = curl_exec( $session );

    if ( curl_error( $session ) ) {
      throw new Exception( 'JSON Call failed ' . curl_strerror( curl_errno( $session ) ) );
    }
    curl_close( $session );

    return $json;
  }
}

<?php

namespace Nectary\Facades;

use Nectary\Models\Json_Feed;
use Nectary\Facades\Rss_Facade;

class Generic_Json_Facade extends Rss_Facade {
  private $url;

  public function load_dependencies() {
    return array( $this, 'get_feed' );
  }

  public function get_feed( $url ) {
    $this->url = $url;

    return new Json_Feed( $url, array( $this, 'get_curl_feed_data' ) );
  }

  public function get_curl_feed_data() {
    $session = curl_init( $this->url );

    curl_setopt( $session, CURLOPT_RETURNTRANSFER, true );

    $json = curl_exec( $session );

    if ( curl_error( $session ) ) {
      throw new Exception( 'JSON Call failed ' . curl_strerror( curl_errno( $session ) ) );
    }
    curl_close( $session );

    return $json;
  }
}

Fix access to class member url in Generic Json Facade


<?php

namespace AMQPy;

use AMQPExchange;
use AMQPy\Client\Properties;
use AMQPy\Serializers\SerializersPool;

class Publisher
{
    private $exchange;
    private $serializers;

    public function __construct(AMQPExchange $exchange, SerializersPool $serializers_pool)
    {
        $this->exchange    = $exchange;
        $this->serializers = $serializers_pool;
    }

    public function getExchange()
    {
        return $this->exchange;
    }

    public function getSerializers()
    {
        return $this->serializers;
    }

    public function publish($message, $routing_key, Properties $properties = null, $flags = AMQP_NOPARAM)
    {
        $content_type = 'text/plain';
        $attributes   = [];

        if ($properties) {
            if ($properties->getContentType()) {
                $content_type = $properties->getContentType();
            }

            $attributes = $properties->toArray();
        }

        $message = $this->serializers->get($content_type)->serialize($message);

        $attributes['content_type'] = $content_type;

        $this->exchange->publish($message, $routing_key, $flags, $attributes);
    }
}

<?php

namespace AMQPy;

use AMQPExchange;
use AMQPy\Client\Properties;
use AMQPy\Serializers\SerializersPool;

class Publisher
{
    private $exchange;
    private $serializers;

    public function __construct(AMQPExchange $exchange, SerializersPool $serializers_pool)
    {
        $this->exchange    = $exchange;
        $this->serializers = $serializers_pool;
    }

    public function getExchange()
    {
        return $this->exchange;
    }

    public function getSerializers()
    {
        return $this->serializers;
    }

    public function publish($message, $routing_key, Properties $properties = null, $flags = AMQP_NOPARAM)
    {
        $content_type = 'text/plain';
        $attributes   = [];

        if ($properties) {
            if ($properties->getContentType()) {
                $content_type = $properties->getContentType();
            }

            $attributes = $properties->toArray();
        }

        $message = $this->serializers->get($content_type)->serialize($message);

        $attributes['content_type'] = $content_type;

        $attributes = array_filter($attributes);

        $this->exchange->publish($message, $routing_key, $flags, $attributes);
    }
}

Fix invalid arguments value issue

Fix invalid arguments value issue


<?php

class Zenc_EmailLogger_Block_Render_Html
    extends Mage_Core_Block_Abstract
    implements Zenc_EmailLogger_Block_Render_Interface
{
    public function getContentType()
    {
        return 'text/html';
    }

    protected function _toHtml()
    {
        $data = $this->getValue();

        switch (true) {
            case !empty(trim($data['body_html'])):
                return $data['body_html'];
            case !empty(trim($data['body_text'])):
                return $data['body_text'];
            default:
                return 'Email has no visible content';
        }
    }
}

<?php

class Zenc_EmailLogger_Block_Render_Html
    extends Mage_Core_Block_Abstract
    implements Zenc_EmailLogger_Block_Render_Interface
{
    public function getContentType()
    {
        return 'text/html';
    }

    protected function _toHtml()
    {
        $data = $this->getValue();

        switch (true) {
            case !empty($data['body_html']):
                return $data['body_html'];
            case !empty($data['body_text']):
                return $data['body_text'];
            default:
                return 'Email has no visible content';
        }
    }
}

Fix return value in write context

Fix return value in write context


<?php

namespace Keboola\Db\Import;

use    Keboola\Csv\CsvFile;

interface ImportInterface
{
    /**
     * @param $tableName
     * @param $columns
     * @param array CsvFile $csvFiles
     * @param array $options
     * @return Result
     */
    public function import($tableName, $columns, array $sourceData, array $options);

    public function getIncremental();

    /**
     * @param $incremental
     * @return $this
     */
    public function setIncremental($incremental);

    public function getIgnoreLines();

    /**
     * @param $linesCount
     * @return $this
     */
    public function setIgnoreLines($linesCount);

}

<?php

namespace Keboola\Db\Import;

use    Keboola\Csv\CsvFile;

interface ImportInterface
{
    /**
     * @param $tableName
     * @param $columns
     * @param array CsvFile $csvFiles
     * @return Result
     */
    public function import($tableName, $columns, array $sourceData);

    public function getIncremental();

    /**
     * @param $incremental
     * @return $this
     */
    public function setIncremental($incremental);

    public function getIgnoreLines();

    /**
     * @param $linesCount
     * @return $this
     */
    public function setIgnoreLines($linesCount);

}

Revert "add import options to interface"

This reverts commit 17b978e86a33826c4499255e71a27b862ed19380.


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

namespace Darvin\AdminBundle\Twig\Extension;

use Darvin\Utils\Service\ServiceProviderInterface;

/**
 * View widget Twig extension
 */
class ViewWidgetExtension extends \Twig_Extension
{
    /**
     * @var \Darvin\Utils\Service\ServiceProviderInterface
     */
    private $widgetPoolProvider;

    /**
     * @param \Darvin\Utils\Service\ServiceProviderInterface $widgetPoolProvider View widget pool provider
     */
    public function __construct(ServiceProviderInterface $widgetPoolProvider)
    {
        $this->widgetPoolProvider = $widgetPoolProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        $functions = [];

        foreach ($this->getWidgetPool()->getWidgets() as $alias => $widget) {
            $functions[] = new \Twig_SimpleFunction('admin_widget_'.$alias, [$widget, 'getContent'], [
                'is_safe' => ['html'],
            ]);
        }

        return $functions;
    }

    /**
     * @return \Darvin\AdminBundle\View\Widget\WidgetPool
     */
    private function getWidgetPool()
    {
        return $this->widgetPoolProvider->getService();
    }
}

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

namespace Darvin\AdminBundle\Twig\Extension;

use Darvin\AdminBundle\View\Widget\WidgetPool;
use Darvin\Utils\Service\ServiceProviderInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * View widget Twig extension
 */
class ViewWidgetExtension extends AbstractExtension
{
    /**
     * @var \Darvin\Utils\Service\ServiceProviderInterface
     */
    private $widgetPoolProvider;

    /**
     * @param \Darvin\Utils\Service\ServiceProviderInterface $widgetPoolProvider View widget pool provider
     */
    public function __construct(ServiceProviderInterface $widgetPoolProvider)
    {
        $this->widgetPoolProvider = $widgetPoolProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): iterable
    {
        foreach ($this->getWidgetPool()->getWidgets() as $alias => $widget) {
            yield new TwigFunction(sprintf('admin_widget_%s', $alias), [$widget, 'getContent'], [
                'is_safe' => ['html'],
            ]);
        }
    }

    /**
     * @return \Darvin\AdminBundle\View\Widget\WidgetPool
     */
    private function getWidgetPool(): WidgetPool
    {
        return $this->widgetPoolProvider->getService();
    }
}

Refactor view widget Twig extension.

Refactor view widget Twig extension.


<?php

namespace Benrowe\Laravel\Url;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

/**
 * Url Service Provider
 * Registers the service provider into the application IOC
 *
 */
class ServiceProvider extends LaravelServiceProvider
{
    protected $defer;

    public function boot()
    {
        // blade directives
        Blade::directives(
            'file',
            function ($expression) {
                return '<?php
                try {
                    echo app(\'filesystem-url\')->url' . $expression . ';
                } catch (Exception $e) {
                }
                ?>';
            }
        );
    }

    public function register()
    {
        $this->app->bindShared('filesystem-url', function ($app) {
            return new UrlService(config('filesystems'), $app['request']);
        });
        $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService');
    }

    public function provides()
    {
        return [
            'Benrowe\Laravel\Url\UrlService',
            'filesystem-url'
        ];
    }
}

<?php

namespace Benrowe\Laravel\Url;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

/**
 * Url Service Provider
 * Registers the service provider into the application IOC
 *
 */
class ServiceProvider extends LaravelServiceProvider
{
    protected $defer;

    public function boot()
    {
        // blade directives
        Blade::directives(
            'file',
            function ($expression) {
                return '<?php
                try {
                    echo app(\'filesystem-url\')->url' . $expression . ';
                } catch (Exception $e) {
                }
                ?>';
            }
        );
    }

    public function register()
    {
        $this->app->bindShared('filesystem-url', function ($app) {
            return new UrlService(config('filesystems'), $app['request']->secure());
        });
        $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService');
    }

    public function provides()
    {
        return [
            'Benrowe\Laravel\Url\UrlService',
            'filesystem-url'
        ];
    }
}

Update instanciation of UrlService to provide secure status


@extends('layouts.master')

@section('title', 'Miners')

@section('content')

                    Miner
                    Corporation
                    Amount owed
                    Total payments
                    Last payment

                    @foreach ($miners as $miner)

                            eve_id }}">{{ $miner->name }}
                            {{ $miner->corporation->name }}
                            {{ number_format($miner->amount_owed, 0) }}
                            {{ number_format($miner->total_payments, 0) }}

                                @if (isset($miner->latest_payment))
                                    {{ date('M j', strtotime($miner->latest_payment)) }}
                                @endif

                    @endforeach

@endsection

@extends('layouts.master')

@section('title', 'Miners')

@section('content')

                    Miner
                    Corporation
                    Amount owed
                    Total payments
                    Last payment

                    @foreach ($miners as $miner)

                            eve_id }}">{{ $miner->name }}
                            {{ $miner->corporation->name }}
                            {{ number_format($miner->amount_owed, 0) }}
                            {{ number_format($miner->total_payments, 0) }}

                                @if (isset($miner->latest_payment))
                                    {{ date('M j, Y', strtotime($miner->latest_payment)) }}
                                @endif

                    @endforeach

@endsection

Add year to miner table to make it sort properly.


<?php

namespace Drupal\display_modes_example;

use Drupal\Core\Entity\EntityViewBuilder;

/**
 * Class TapaViewBuilder
 *
 * Render controller for Tapas.
 */
class TapaViewBuilder extends EntityViewBuilder  {

  /**
   * {@inheritdoc}
   */
  public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
    parent::buildComponents($build, $entities, $displays, $view_mode);
    foreach ($entities as $id => $entity) {
      $bundle = $entity->bundle();
      $display = $displays[$bundle];
      if ($display->getComponent('common_text')) {
        $build[$id]['common_text'] = [
          '#theme' => 'common_text',
          '#text' => t('Taste this and other awesome Tapas at this DrupalCamp Es!!! '),
        ];
      }
    }
  }

}

<?php

namespace Drupal\display_modes_example;

use Drupal\Core\Entity\EntityViewBuilder;

/**
 * Class TapaViewBuilder
 *
 * Render controller for Tapas.
 */
class TapaViewBuilder extends EntityViewBuilder  {

  /**
   * {@inheritdoc}
   */
  public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
    parent::buildComponents($build, $entities, $displays, $view_mode);
    foreach ($entities as $id => $entity) {
      $bundle = $entity->bundle();
      $display = $displays[$bundle];
      if ($display->getComponent('common_text')) {
        $build[$id]['common_text'] = [
          '#theme' => 'common_text',
          '#text' => t('Taste this and other awesome Tapas!!! '),
        ];
      }
    }
  }

}

Generalize the common view text

Generalize the common view text


<?php

namespace Swarrot\Broker;

class Message
{
    /**
     * @var string
     */
    protected $body;

    /**
     * Properties are similar to headers when using an \AMQPEnvelope object.
     *
     * @var array
     */
    protected $properties;

    /**
     * @var int
     */
    protected $id;

    public function __construct($body, array $properties = array(), $id = null)
    {
        $this->body       = $body;
        $this->properties = $properties;
        $this->id         = $id;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function getHeaders()
    {
        trigger_error('getHeaders() method is deprecated. Use getProperties().', E_USER_DEPRECATED);

        return $this->getProperties();
    }

    public function getProperties()
    {
        return $this->properties;
    }

    public function getId()
    {
        return $this->id;
    }
}

<?php

namespace Swarrot\Broker;

class Message
{
    /**
     * @var string
     */
    protected $body;

    /**
     * Properties are similar to headers when using an \AMQPEnvelope object.
     *
     * @var array
     */
    protected $properties;

    /**
     * @var int
     */
    protected $id;

    /**
     * __construct
     *
     * In AMQP 0.9.1, a message contains properties. One of this properties is
     * "headers".
     * In AMQP 1.0, a message contains both properties and headers.
     *
     * For example, RabbitMQ implement AMQP 0.9.1.
     * The "getHeaders" method of "\AMQPEnvelope" object actually return
     * message properties AND headers at the same level.
     * But if you want to have additional informations, you have to put it in
     * the "headers" property. All unknown properties will be deleted by the
     * broker.
     *
     * More information on AMQP version:
     * @see: http://www.amqp.org/resources/download
     *
     * @param mixed $body
     * @param array $properties
     * @param mixed $id
     *
     * @return void
     */
    public function __construct($body, array $properties = array(), $id = null)
    {
        $this->body       = $body;
        $this->properties = $properties;
        $this->id         = $id;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function getHeaders()
    {
        trigger_error('getHeaders() method is deprecated. Use getProperties().', E_USER_DEPRECATED);

        return $this->getProperties();
    }

    public function getProperties()
    {
        return $this->properties;
    }

    public function getId()
    {
        return $this->id;
    }
}

Add more detailled informations about message properties


<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP post type
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */

class WPposttype extends WPaction
{
    protected $slug;
    protected $args;

    public function __construct($slug, $args = array())
    {
        parent::__construct('init');
        $this->slug = $slug;

        $defaults = array();
        $this->args = wp_parse_args($args, $defaults);

    }

    public function getSlug()
    {
        return $this->slug;
    }

    public function getLoop($args = array())
    {
        $defaults = array(
            'post_type' => $this->slug,
            'nopaging' => true
        );
        $args = wp_parse_args($args, $defaults);

        return new \WP_Query($args);
    }

    public function action()
    {
        register_post_type($this->slug, $this->args);
    }
}

<?php
/*
 * This file is part of WPCore project.
 *
 * (c) Louis-Michel Raynauld <louismichel@pweb.ca>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WPCore;

/**
 * WP post type
 *
 * @author Louis-Michel Raynauld <louismichel@pweb.ca>
 */

class WPposttype extends WPaction
{
    protected $slug;
    protected $args;

    public function __construct($slug, $args = array())
    {
        parent::__construct('init');
        $this->slug = $slug;

        $defaults = array();
        $this->args = wp_parse_args($args, $defaults);

    }

    public function setArg($arg, $value)
    {
        $this->args[$arg] = $value;

        return $this;
    }

    public function getSlug()
    {
        return $this->slug;
    }

    public function getLoop($args = array())
    {
        $defaults = array(
            'post_type' => $this->slug,
            'nopaging' => true
        );
        $args = wp_parse_args($args, $defaults);

        return new \WP_Query($args);
    }

    public function action()
    {
        register_post_type($this->slug, $this->args);
    }
}

Add setter for postype arguments

Add setter for postype arguments


<?php
include("mustache.php");

/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
	- $application_data: contains the application data required to render the
	  views such as:
		- the current user name
		- the list of all available languages with ISO2 code, language name, and
		  a selected attribute in the selected language
		- the ISO2 code of the selected language
		- the server name
		- the API url
		- the Sparql endpoint url
	- $theme_path: contains the full path of the theme root folder.
	- $mustache_data: contains all the data required to render the views
	- $mustache_template: contains the name of the template to load
	- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);

<?php
require_once("mustache.php");

/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
	- $application_data: contains the application data required to render the
	  views such as:
		- the current user name
		- the list of all available languages with ISO2 code, language name, and
		  a selected attribute in the selected language
		- the ISO2 code of the selected language
		- the server name
		- the API url
		- the Sparql endpoint url
	- $theme_path: contains the full path of the theme root folder.
	- $mustache_data: contains all the data required to render the views
	- $mustache_template: contains the name of the template to load
	- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);

Fix bug in login form

Fix bug in login form


<?php

namespace Juy\CharacterSolver;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the application services
     *
     * @return void
     */
    public function register()
    {
        // Default package configuration
        $this->mergeConfigFrom(
            __DIR__ . '/../config/charactersolver.php', 'charactersolver'
        );
    }

    /**
     * Perform post-registration booting of services
     *
     * @return void
     */
    public function boot()
    {
        // Publish the config file
        $this->publishConfig();

        // If running in console
        if ($this->app->runningInConsole())
        {
            return;
        }

        // If CharacterSolver is disabled
        if (!$this->app['config']->get('charactersolver.enabled'))
        {
            return;
        }

        // Add a new middleware to end of the stack if it does not already exist
        $this->registerMiddleware(Middleware\CharacterSolver::class);
    }

    /**
     * Register the CharacterSolver middleware
     *
     * @param  string $middleware
     */
    protected function registerMiddleware($middleware)
    {
        $kernel = $this->app['Illuminate\Contracts\Http\Kernel'];
        $kernel->pushMiddleware($middleware);
    }

    /**
     * Publish the config file
     */
    protected function publishConfig()
    {
        $this->publishes([
            __DIR__ . '/../config/charactersolver.php' => config_path('charactersolver.php')
        ], 'config');
    }
}

<?php

namespace Juy\CharacterSolver;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the application services
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Perform post-registration booting of services
     *
     * @return void
     */
    public function boot()
    {
        // Register configurations
        $this->registerConfigurations();

        // If running in console
        if ($this->app->runningInConsole())
        {
            return;
        }

        // If CharacterSolver is disabled
        if (!$this->app['config']->get('charactersolver.enabled'))
        {
            return;
        }

        // Add a new middleware to end of the stack if it does not already exist
        $this->registerMiddleware(Middleware\CharacterSolver::class);
    }

    /**
     * Register the CharacterSolver middleware
     *
     * @param  string $middleware
     */
    protected function registerMiddleware($middleware)
    {
        $kernel = $this->app['Illuminate\Contracts\Http\Kernel'];
        $kernel->pushMiddleware($middleware);
    }

    /**
     * Register configurations
     *
     * @return void
     */
    protected function registerConfigurations()
    {
        // Default package configuration
        $this->mergeConfigFrom(
            __DIR__ . '/../config/charactersolver.php', 'charactersolver'
        );

        // Publish the config file
        $this->publishes([
            __DIR__ . '/../config/charactersolver.php' => config_path('charactersolver.php')
        ], 'config');
    }

}

Create "Register configurations" method and move config codes


<?php

namespace Yajra\CMS\Themes;

use Illuminate\View\FileViewFinder;

class ThemeViewFinder extends FileViewFinder
{
    /**
     * Base path to look for blade files.
     *
     * @var string
     */
    protected $basePath;

    /**
     * Use the given theme as the current theme.
     *
     * @param string $theme
     */
    public function use($theme)
    {
        $theme    = $theme ?: config('themes.frontend', 'default');
        $basePath = config('themes.path.frontend', base_path('themes/frontend'));
        $this->removeBasePath();
        $this->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);

        config(['themes.frontend' => $theme]);
    }

    /**
     * Remove base path.
     */
    public function removeBasePath()
    {
        unset($this->paths[0]);
    }

    /**
     * Set file view finder base path.
     *
     * @param $path
     */
    public function setBasePath($path)
    {
        $this->basePath = $path;

        array_unshift($this->paths, $this->basePath);
    }
}

<?php

namespace Yajra\CMS\Themes;

use Illuminate\View\FileViewFinder;

class ThemeViewFinder extends FileViewFinder
{
    /**
     * Base path to look for blade files.
     *
     * @var string
     */
    protected $basePath;

    /**
     * Use the given theme as the current theme.
     *
     * @param string $theme
     * @param bool   $frontend
     */
    public function use($theme, $frontend = true)
    {
        $key      = $frontend ? 'frontend' : 'backend';
        $theme    = $theme ?: config('themes.' . $key, 'default');
        $basePath = config('themes.path.' . $key, base_path('themes/' . $key));
        $this->removeBasePath();
        $this->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);

        config(['themes.' . $key => $theme]);
    }

    /**
     * Remove base path.
     */
    public function removeBasePath()
    {
        unset($this->paths[0]);
    }

    /**
     * Set file view finder base path.
     *
     * @param $path
     */
    public function setBasePath($path)
    {
        $this->basePath = $path;

        array_unshift($this->paths, $this->basePath);
    }
}

Add option to set theme on frontend or backend.


<?php

namespace Frozzare\Tank;

use BadMethodCallException;

abstract class Service_Provider {

	/**
	 * The container.
	 *
	 * @var \Frozzare\Tank\Container
	 */
	protected $container;

	/**
	 * The constructor.
	 *
	 * @param \Frozzare\Tank\Container $container
	 */
	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Registers service provider.
	 */
	abstract public function register();

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

	/**
	 * Dynamically handle missing method calls.
	 *
	 * @param  string $method
	 * @param  array  $parameters
	 *
	 * @throws \BadMethodCallException
	 *
	 * @return mixed
	 */
	public function __call( $method, $parameters ) {
		throw new BadMethodCallException( "Call to undefined method `{$method}`" );
	}
}

<?php

namespace Frozzare\Tank;

use BadMethodCallException;

abstract class Service_Provider {

	/**
	 * The container.
	 *
	 * @var \Frozzare\Tank\Container
	 */
	protected $container;

	/**
	 * The constructor.
	 *
	 * @param \Frozzare\Tank\Container $container
	 */
	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Registers service provider.
	 */
	abstract public function register();

	/**
	 * Get the services provided by the provider.
	 *
	 * @codeCoverageIgnore
	 *
	 * @return array
	 */
	public function provides() {
		return [];
	}

	/**
	 * Dynamically handle missing method calls.
	 *
	 * @param  string $method
	 * @param  array  $parameters
	 *
	 * @throws \BadMethodCallException
	 *
	 * @return mixed
	 */
	public function __call( $method, $parameters ) {
		throw new BadMethodCallException( "Call to undefined method `{$method}`" );
	}
}

Add codeCoverageIgnore to provides method


<?php

namespace Captcha\Controller;

use App\Controller\AppController;
use Cake\Event\EventInterface;

/**
 * @property \Captcha\Model\Table\CaptchasTable $Captchas
 * @property \Captcha\Controller\Component\PreparerComponent $Preparer
 */
class CaptchaController extends AppController {

	/**
	 * @var string
	 */
	protected $modelClass = 'Captcha.Captchas';

	/**
	 * @return void
	 */
	public function initialize(): void {
		parent::initialize();

		$this->loadComponent('Captcha.Preparer');
	}

	/**
	 * @param \Cake\Event\EventInterface $event
	 * @return \Cake\Http\Response|null|void
	 */
	public function beforeFilter(EventInterface $event) {
		if (isset($this->Auth)) {
			$this->Auth->allow();
		}
	}

	/**
	 * Displays a captcha image
	 *
	 * @param int|null $id
	 * @return \Cake\Http\Response|null|void
	 */
	public function display($id = null) {
		$captcha = $this->Captchas->get($id);
		$captcha = $this->Preparer->prepare($captcha);

		$this->set(compact('captcha'));

		$this->viewBuilder()->setClassName('Captcha.Captcha');
		$this->viewBuilder()->setTemplatePath('Captcha');
	}

}

<?php

namespace Captcha\Controller;

use App\Controller\AppController;
use Cake\Event\EventInterface;

/**
 * @property \Captcha\Model\Table\CaptchasTable $Captchas
 * @property \Captcha\Controller\Component\PreparerComponent $Preparer
 */
class CaptchaController extends AppController {

	/**
	 * @var string
	 */
	protected $modelClass = 'Captcha.Captchas';

	/**
	 * @return void
	 */
	public function initialize(): void {
		parent::initialize();

		$this->loadComponent('Captcha.Preparer');
	}

	/**
	 * @param \Cake\Event\EventInterface $event
	 * @return \Cake\Http\Response|null|void
	 */
	public function beforeFilter(EventInterface $event) {
		if (isset($this->Auth)) {
			$this->Auth->allow();
		} elseif (isset($this->Authentication) && method_exists($this->Authentication, 'addUnauthenticatedActions')) {
			$this->Authentication->addUnauthenticatedActions(['display']);
		}
	}

	/**
	 * Displays a captcha image
	 *
	 * @param int|null $id
	 * @return \Cake\Http\Response|null|void
	 */
	public function display($id = null) {
		$captcha = $this->Captchas->get($id);
		$captcha = $this->Preparer->prepare($captcha);

		$this->set(compact('captcha'));

		$this->viewBuilder()->setClassName('Captcha.Captcha');
		$this->viewBuilder()->setTemplatePath('Captcha');
	}

}

Add support for new auth plugins.

Add support for new auth plugins.


<?php

namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table;

use Bolt\Storage\Database\Schema\Table\BaseTable;

/**
 * Account table.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Account extends BaseTable
{
    /**
     * @inheritDoc
     */
    protected function addColumns()
    {
        $this->table->addColumn('guid',        'guid',       []);
        $this->table->addColumn('email',       'string',     ['length'  => 128]);
        $this->table->addColumn('displayname', 'string',     ['length'  => 32, 'notnull' => false]);
        $this->table->addColumn('enabled',     'boolean',    ['default' => 0]);
        $this->table->addColumn('roles',       'json_array', ['length'  => 1024, 'notnull' => false]);
        $this->table->addColumn('lastseen',    'datetime',   ['default' => '']);
        $this->table->addColumn('lastip',      'string',     ['length'  => 32, 'notnull' => false]);
    }

    /**
     * @inheritDoc
     */
    protected function addIndexes()
    {
        $this->table->addUniqueIndex(['email']);

        $this->table->addIndex(['enabled']);
    }

    /**
     * @inheritDoc
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['guid']);
    }
}

<?php

namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table;

use Bolt\Storage\Database\Schema\Table\BaseTable;

/**
 * Account table.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Account extends BaseTable
{
    /**
     * @inheritDoc
     */
    protected function addColumns()
    {
        $this->table->addColumn('guid',        'guid',       []);
        $this->table->addColumn('email',       'string',     ['length'  => 128]);
        $this->table->addColumn('displayname', 'string',     ['length'  => 32, 'notnull' => false]);
        $this->table->addColumn('enabled',     'boolean',    ['default' => 0]);
        $this->table->addColumn('roles',       'json_array', ['length'  => 1024, 'notnull' => false]);
        $this->table->addColumn('lastseen',    'datetime',   ['notnull' => false, 'default' => null]);
        $this->table->addColumn('lastip',      'string',     ['length'  => 32, 'notnull' => false]);
    }

    /**
     * @inheritDoc
     */
    protected function addIndexes()
    {
        $this->table->addUniqueIndex(['email']);

        $this->table->addIndex(['enabled']);
    }

    /**
     * @inheritDoc
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['guid']);
    }
}

Update schema to handle null and default for datatime