<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Result;

use PhpSchool\PhpWorkshop\Check\CheckInterface;

/**
 * A failure result representing the situation where there were function usage requirements
 * and they were not met.
 */
class FunctionRequirementsFailure implements FailureInterface
{
    use ResultTrait;

    /**
     * @var array<array{function: string, line: int}>
     */
    private $bannedFunctions;

    /**
     * @var array<int, string>
     */
    private $missingFunctions;

    /**
     * @param CheckInterface $check The check that produced this result.
     * @param array<array{function: string, line: int}> $bannedFunctions A list of functions that were used, but were banned.
     * @param array<int, string> $missingFunctions A list of functions that were not used, but were required.
     */
    public function __construct(CheckInterface $check, array $bannedFunctions, array $missingFunctions)
    {
        $this->check = $check;
        $this->bannedFunctions = $bannedFunctions;
        $this->missingFunctions = $missingFunctions;
    }

    /**
     * Get the list of functions that were used, but were banned.
     *
     * @return array<array{function: string, line: int}>
     */
    public function getBannedFunctions(): array
    {
        return $this->bannedFunctions;
    }

    /**
     * Get the list of functions that were not used, but were required.
     *
     * @return array<int, string>
     */
    public function getMissingFunctions(): array
    {
        return $this->missingFunctions;
    }
}

<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Result;

use PhpSchool\PhpWorkshop\Check\CheckInterface;

/**
 * A failure result representing the situation where there were function usage requirements
 * and they were not met.
 */
class FunctionRequirementsFailure implements FailureInterface
{
    use ResultTrait;

    /**
     * @var array<array{function: string, line: int}>
     */
    private $bannedFunctions;

    /**
     * @var array<int, string>
     */
    private $missingFunctions;

    /**
     * @param CheckInterface $check The check that produced this result.
     * @param array<array{function: string, line: int}> $bannedFunctions Functions that were used, but were banned.
     * @param array<int, string> $missingFunctions Functions that were not used, but were required.
     */
    public function __construct(CheckInterface $check, array $bannedFunctions, array $missingFunctions)
    {
        $this->check = $check;
        $this->bannedFunctions = $bannedFunctions;
        $this->missingFunctions = $missingFunctions;
    }

    /**
     * Get the list of functions that were used, but were banned.
     *
     * @return array<array{function: string, line: int}>
     */
    public function getBannedFunctions(): array
    {
        return $this->bannedFunctions;
    }

    /**
     * Get the list of functions that were not used, but were required.
     *
     * @return array<int, string>
     */
    public function getMissingFunctions(): array
    {
        return $this->missingFunctions;
    }
}

Fix CS failure for docblock line length

Fix CS failure for docblock line length


<?php
declare(strict_types=1);

namespace TMCms\Background;

use TMCms\Traits\singletonInstanceTrait;

defined('INC') or exit;

/**
 * Class ProcessQueue
 * @package TMCms\Background
 *
 * @usage   - code should be supplied as string only
 * $file_path = DIR_BASE . 'log.txt';
 * $time_sleep = 15;
 * $write = '
 * sleep('. $time_sleep .');
 * file_put_contents("'. $file_path .'", '. NOW .');'
 * ;
 *
 * ProcessQueue::getInstance()->addBackgroundTaskInQueue($write);
 */
class ProcessQueue
{
    use singletonInstanceTrait;

    public function addBackgroundTaskInQueue(string $function_code)
    {
        $process = new Process($function_code);
        $process->runProcess();
    }
}

<?php
declare(strict_types=1);

namespace TMCms\Background;

use TMCms\Traits\singletonInstanceTrait;

defined('INC') or exit;

/**
 * Class ProcessQueue
 * @package TMCms\Background
 *
 * @usage   - code should be supplied as string only
 * $file_path = DIR_BASE . 'log.txt';
 * $time_sleep = 15;
 * $write = '
 * sleep('. $time_sleep .');
 * file_put_contents("'. $file_path .'", '. NOW .');'
 * ;
 *
 * ProcessQueue::getInstance()->addBackgroundTaskInQueue($write);
 */
class ProcessQueue
{
    use singletonInstanceTrait;

    public function addBackgroundTaskInQueue(string $function_code)
    {
        $process = new Process($function_code);
        $process->runProcess();

        return $process->getPid();
    }
}

Return PID of running process in background


<?php namespace	STS\Tunneler;

use Illuminate\Support\ServiceProvider;
use STS\Tunneler\Console\TunnelerCommand;
use STS\Tunneler\Jobs\CreateTunnel;

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

    /**
     * Default path to configuration
     * @var string
     */
    protected $configPath = __DIR__ . '/../config/tunneler.php';

    public function boot()
    {
        // helps deal with Lumen vs Laravel differences
        if (function_exists('config_path')) {
            $publishPath = config_path('tunneler.php');
        } else {
            $publishPath = base_path('config/tunneler.php');
        }

        $this->publishes([$this->configPath => $publishPath], 'config');

        if (config('tunneler.on_boot')){
            dispatch(new CreateTunnel());
        }
    }

    public function register()
    {
        if ( is_a($this->app,'Laravel\Lumen\Application')){
            $this->app->configure('tunneler');
        }
        $this->mergeConfigFrom($this->configPath, 'tunneler');

        $this->app->singleton('command.tunneler.activate',
            function ($app) {
                return new TunnelerCommand();
            }
        );

        $this->commands('command.tunneler.activate');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('command.tunneler.activate');
    }

}

<?php namespace	STS\Tunneler;

use Illuminate\Support\ServiceProvider;
use STS\Tunneler\Console\TunnelerCommand;
use STS\Tunneler\Jobs\CreateTunnel;

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

    /**
     * Default path to configuration
     * @var string
     */
    protected $configPath = __DIR__ . '/../config/tunneler.php';

    public function boot()
    {
        // helps deal with Lumen vs Laravel differences
        if (function_exists('config_path')) {
            $publishPath = config_path('tunneler.php');
        } else {
            $publishPath = base_path('config/tunneler.php');
        }

        $this->publishes([$this->configPath => $publishPath], 'config');

        if (config('tunneler.on_boot')){
            dispatch(new CreateTunnel());
        }
    }

    public function register()
    {
        if ( is_a($this->app,'Laravel\Lumen\Application')){
            $this->app->configure('tunneler');
        }
        $this->mergeConfigFrom($this->configPath, 'tunneler');

        $this->app->singleton('command.tunneler.activate',
            function ($app) {
                return new TunnelerCommand();
            }
        );

        $this->commands('command.tunneler.activate');
    }

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

}

Use the cool new array syntax

Use the cool new array syntax


<?php namespace Flarum\Core\Notifications\Types;

abstract class Notification
{
    abstract public static function getType();
}

<?php namespace Flarum\Core\Notifications\Types;

abstract class Notification
{
    /**
     * Returns the serialized type of this notification.
     *
     * This method should be overwritten by subclasses.
     *
     * @return string
     */
    public static function getType()
    {
        return 'notification';
    }
}

Fix code error, static methods can not be abstract.


<?php

/*
 * This file is part of php-cache\apcu-adapter package.
 *
 * (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cache\Adapter\Apcu;

use Cache\Adapter\Common\AbstractCachePool;
use Psr\Cache\CacheItemInterface;

/**
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
class ApcuCachePool extends AbstractCachePool
{
    protected function fetchObjectFromCache($key)
    {
        return apcu_fetch($key);
    }

    protected function clearAllObjectsFromCache()
    {
        return apcu_clear_cache();
    }

    protected function clearOneObjectFromCache($key)
    {
        apcu_delete($key);

        return true;
    }

    protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
    {
        return apcu_store($key, $item, $ttl);
    }
}

<?php

/*
 * This file is part of php-cache\apcu-adapter package.
 *
 * (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cache\Adapter\Apcu;

use Cache\Adapter\Common\AbstractCachePool;
use Psr\Cache\CacheItemInterface;

/**
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
class ApcuCachePool extends AbstractCachePool
{
    protected function fetchObjectFromCache($key)
    {
        $success = false;
        $data    = apcu_fetch($key, $success);

        return [$success, $data];
    }

    protected function clearAllObjectsFromCache()
    {
        return apcu_clear_cache();
    }

    protected function clearOneObjectFromCache($key)
    {
        apcu_delete($key);

        return true;
    }

    protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
    {
        return apcu_store($key, $item->get(), $ttl);
    }
}

Make sure we are compatible with common 0.3


<?=$Version;?>

Home Page: http://www.python.org/

Download: http://www.python.org/download/

<?=$Version;?>

Paul Grahm's Essay

Home Page: http://www.python.org/

Download: http://www.python.org/download/

Add a Paul Graham's note about Python.

Add a Paul Graham's note about Python.


<?php

namespace donatj\MDDom;

class DocumentDepth extends AbstractNestingElement {

	protected function generateMarkdown( $fragmentLevel = 0 ) {
		$content = trim(parent::generateMarkdown($fragmentLevel));

		return $content;

	}

}

<?php

namespace donatj\MDDom;

use donatj\MDDom\Interfaces\BlockElementInterface;

class DocumentDepth extends AbstractNestingElement implements BlockElementInterface {

	protected function generateMarkdown( $fragmentLevel = 0 ) {
		$content = trim(parent::generateMarkdown($fragmentLevel));

		return $content;
	}

}

Fix a problem with documents starting with block level elements


<?php

namespace Asmaster\EquipTwig\Exception;

use InvalidArgumentException;

class ExtensionException extends InvalidArgumentException
{
    /**
     * @param mixed $extension
     *
     * @return static
     */
    public static function invalidExtension($extension)
    {
        if (is_object($extension)) {
            $extension = get_class($extension);
        }

        return new static(sprintf(
            'Twig extension `%s` must implement Twig_ExtensionInterface',
            $extension
        ));
    }
}

<?php

namespace Asmaster\EquipTwig\Exception;

use InvalidArgumentException;
use Twig_ExtensionInterface;

class ExtensionException extends InvalidArgumentException
{
    /**
     * @param mixed $extension
     *
     * @return static
     */
    public static function invalidExtension($extension)
    {
        if (is_object($extension)) {
            $extension = get_class($extension);
        }

        return new static(sprintf(
            'Twig extension `%s` must implement `%s`',
            $extension,
            Twig_ExtensionInterface::class
        ));
    }
}

Improve exception for an invalid extension


<?php

namespace Tests\Becklyn\AssetsBundle\Twig;

use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\Loader\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;

class AssetsTwigExtensionTest extends TestCase
{
    /**
     * Assert that the exposed twig functions don't change
     */
    public function testMethodNames ()
    {
        $htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class)
            ->disableOriginalConstructor()
            ->getMock();

        $assetUrl = $this->getMockBuilder(AssetUrl::class)
            ->disableOriginalConstructor()
            ->getMock();

        $fileLoader = $this->getMockBuilder(FileLoader::class)
            ->disableOriginalConstructor()
            ->getMock();

        $extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader);
        $functions = \array_map(
            function (\Twig_SimpleFunction $f)
            {
                return $f->getName();
            },
            $extension->getFunctions()
        );

        self::assertContains("assets_css", $functions);
        self::assertContains("assets_js", $functions);
        self::assertContains("asset", $functions);
    }

}

<?php

namespace Tests\Becklyn\AssetsBundle\Twig;

use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\Loader\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;

class AssetsTwigExtensionTest extends TestCase
{
    /**
     * Assert that the exposed twig functions don't change
     */
    public function testMethodNames ()
    {
        $htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class)
            ->disableOriginalConstructor()
            ->getMock();

        $assetUrl = $this->getMockBuilder(AssetUrl::class)
            ->disableOriginalConstructor()
            ->getMock();

        $fileLoader = $this->getMockBuilder(FileLoader::class)
            ->disableOriginalConstructor()
            ->getMock();

        $extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader);
        $functions = \array_map(
            function (\Twig_SimpleFunction $f)
            {
                return $f->getName();
            },
            $extension->getFunctions()
        );

        self::assertContains("assets_css", $functions);
        self::assertContains("assets_js", $functions);
        self::assertContains("asset", $functions);
        self::assertContains("asset_inline", $functions);
    }

}

Test for new twig function

Test for new twig function


<?php

function ircReport($stuff)
{
	$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
	socket_write($sock, $stuff."\n");
	socket_close($sock);
}

function ircUserColor($name, $gender, $power) {
	$gColors = array(0 => 12, 1 => 13, 2 => '02');
	$pChars  = array(1 => "+", 2 => "%", 3 => "$", 4 => "#", 5 => ">");

	$color = $gColors[$gender];
	if ($power > 0)
		$powerChar = $pChars[$power];
	else
		$powerChar = "";

	if ($power === -1)
		$color = 14;
	else if ($power === 5)
		$color = 4;

	return "\x0314" . $powerChar . "\x03" . $color . $name;
}

function ircColor($c)
{
	return sprintf('%02d', $c);
}

<?php

function ircReport($stuff)
{
	$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
	socket_write($sock, $stuff."\n");
	socket_close($sock);
}

function ircUserColor($name, $gender, $power) {
	$gColors = array(0 => 12, 1 => 13, 2 => '02');
	$pChars  = array(1 => "%", 2 => "@", 3 => "&", 4 => "~", 5 => "+");

	$color = $gColors[$gender];
	if ($power > 0)
		$powerChar = $pChars[$power];
	else
		$powerChar = "";

	if ($power === -1)
		$color = 14;
	else if ($power === 5)
		$color = 4;

	return "\x0314" . $powerChar . "\x03" . $color . $name;
}

function ircColor($c)
{
	return sprintf('%02d', $c);
}

Use IRC style symbols instead of weird mix of IRC symbols and shell symbols.


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

namespace LdapTools\Log;

/**
 * LDAP Logging interface.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
interface LdapLoggerInterface
{
    public function start(LogOperation $operation);

    public function end(LogOperation $operation);
}

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

namespace LdapTools\Log;

/**
 * LDAP Logging interface.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
interface LdapLoggerInterface
{
    /**
     * The start method is called against a LDAP operation prior to the operation being executed.
     *
     * @param LogOperation $operation
     */
    public function start(LogOperation $operation);

    /**
     * The end method is called against a LDAP operation after the operation has finished executing.
     *
     * @param LogOperation $operation
     */
    public function end(LogOperation $operation);
}

Add some phpdoc to the interface.

Add some phpdoc to the interface.


<?php
namespace ZaLaravel\LaravelUser\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use ZaLaravel\LaravelUser\Models\Role;
use ZaLaravel\LaravelUser\Models\Interfaces\UserInterface;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, UserInterface
{

    use Authenticatable, CanResetPassword;

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

    protected $fillable = ['user_name', 'email', 'password', 'blocked'];
    protected $guarded = ['_token'];
    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * Get the roles a user has
     */
    public function roles()
    {
        return $this->belongsToMany('ZaLaravel\LaravelUser\Models\Role', 'users_roles');
    }

    /**
     * Find out if user has a specific role
     *
     * $return boolean
     */
    public function hasRole($check)
    {
        return in_array($check, array_fetch($this->roles->toArray(), 'name'));
    }

}

<?php
namespace ZaLaravel\LaravelUser\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use ZaLaravel\LaravelUser\Models\Role;
use ZaLaravel\LaravelUser\Models\Interfaces\UserInterface;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, UserInterface
{

    use Authenticatable, CanResetPassword;

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

    protected $fillable = ['name', 'email', 'password', 'blocked'];
    protected $guarded = ['_token'];
    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * Get the roles a user has
     */
    public function roles()
    {
        return $this->belongsToMany('ZaLaravel\LaravelUser\Models\Role', 'users_roles');
    }

    /**
     * Find out if user has a specific role
     *
     * $return boolean
     */
    public function hasRole($check)
    {
        return in_array($check, array_fetch($this->roles->toArray(), 'name'));
    }

}

Change fillable user_name to name in model


<?php

namespace PhpAbac;

class Abac {
    /** @var array **/
    private static $container;

    /**
     * @param \PDO $connection
     */
    public function __construct($connection)
    {
        self::set('policy-rule-manager', new PolicyRuleManager());
        self::set('attribute-manager', new AttributeManager());
        self::set('pdo-connection', $connection);
    }

    /**
     * @param string $serviceName
     * @param mixed $service
     * @param boolean $force
     * @throws \InvalidArgumentException
     */
    public static function set($serviceName, $service, $force = false) {
        if(self::has($serviceName) && $force === false) {
            throw new \InvalidArgumentException(
                "The service $serviceName is already set in PhpAbac container. ".
                'Please set $force parameter to true if you want to replace the set service'
            );
        }
        self::$container[$serviceName] = $service;
    }

    /**
     * @param string $serviceName
     * @return boolean
     */
    public static function has($serviceName) {
        return isset(self::$container[$serviceName]);
    }

    /**
     * @throws \InvalidArgumentException
     * @return mixed
     */
    public static function get($serviceName) {
        if(!self::has($serviceName)) {
            throw new \InvalidArgumentException("The PhpAbac container has no service named $serviceName");
        }
        return self::$container[$serviceName];
    }
}

<?php

namespace PhpAbac;

use PhpAbac\Manager\AttributeManager;
use PhpAbac\Manager\PolicyRuleManager;

class Abac {
    /** @var array **/
    private static $container;

    /**
     * @param \PDO $connection
     */
    public function __construct(\PDO $connection)
    {
        // Set the main managers
        self::set('pdo-connection', $connection);
        self::set('policy-rule-manager', new PolicyRuleManager());
        self::set('attribute-manager', new AttributeManager());
    }

    public static function resetSchema() {
        self::get('pdo-connection')->exec(
            file_get_contents(dirname(dirname(__DIR__)) . '/sql/schema.sql')
        );
    }

    public static function clearContainer() {
        self::$container = null;
    }

    /**
     * @param string $serviceName
     * @param mixed $service
     * @param boolean $force
     * @throws \InvalidArgumentException
     */
    public static function set($serviceName, $service, $force = false) {
        if(self::has($serviceName) && $force === false) {
            throw new \InvalidArgumentException(
                "The service $serviceName is already set in PhpAbac container. ".
                'Please set $force parameter to true if you want to replace the set service'
            );
        }
        self::$container[$serviceName] = $service;
    }

    /**
     * @param string $serviceName
     * @return boolean
     */
    public static function has($serviceName) {
        return isset(self::$container[$serviceName]);
    }

    /**
     * @throws \InvalidArgumentException
     * @return mixed
     */
    public static function get($serviceName) {
        if(!self::has($serviceName)) {
            throw new \InvalidArgumentException("The PhpAbac container has no service named $serviceName");
        }
        return self::$container[$serviceName];
    }
}

Add method to reset SQL schema and to empty the container


    <?php

    if (is_singular()) {
        the_title('
', '
');
    } elseif (is_front_page() && is_home()) {
        the_title('
', '
');
    } else {
        the_title('
', '
');
    }

    if ('post' === get_post_type()) {
        echo '
';
        if (is_single() || is_archive() || is_home()) {
            keitaro_posted_on();
        }
        echo '
';
    };

    ?>

    <?php

    if (is_sticky() && !is_single()):
        printf('
%s
', __('Must read', 'keitaro'));
    endif;

    if (is_singular()) :
        the_title('
', '
');
    elseif (is_front_page() && is_home()) :
        the_title('
', '
');
    elseif (is_sticky()) :
        the_title('
', '
');
    else :
        the_title('
', '
');
    endif;

    if ('post' === get_post_type()) :
        echo '
';
        if (is_single() || is_archive() || is_home()) :
            keitaro_posted_on();
        endif;
        echo '
';
    endif;

    ?>

Add small title specifically for Sticky posts and restructure if-else blocks


<?php

namespace App\Handlers\Events;

use App\Events\NewUserWasRegistered;
use App\TransMail;

class SendMailUserWelcome
{
    private $transmail;

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

    /**
     * Handle the event.
     *
     * @param NewUserWasRegistered $event
     *
     * @return void
     */
    public function handle(NewUserWasRegistered $event)
    {
        logger()->info('Handle NewUserWasRegistered.SendMailUserWelcome()');

        $params = [
            'user' => $event->user,
        ];
        $header = [
            'name'  => $event->user->name,
            'email' => $event->user->email,
        ];
        $this->transmail->template('appointments.manager._new')
                        ->subject('user.welcome.subject')
                        ->send($header, $params);
    }
}

<?php

namespace App\Handlers\Events;

use App\Events\NewUserWasRegistered;
use App\TransMail;

class SendMailUserWelcome
{
    private $transmail;

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

    /**
     * Handle the event.
     *
     * @param NewUserWasRegistered $event
     *
     * @return void
     */
    public function handle(NewUserWasRegistered $event)
    {
        logger()->info('Handle NewUserWasRegistered.SendMailUserWelcome()');

        $params = [
            'user' => $event->user,
        ];
        $header = [
            'name'  => $event->user->name,
            'email' => $event->user->email,
        ];
        $this->transmail->template('welcome')
                        ->subject('user.welcome.subject')
                        ->send($header, $params);
    }
}

Fix template name for this event

Fix template name for this event


<?php snippet_detect('html_head', array(
	'criticalcss' => 'home',
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

	<div class="CoverImage FluidEmbed FluidEmbed--3by2 FluidEmbed--compact16by9 FluidEmbed--medium2by1 FluidEmbed--large3by1"
		style="background-image: url('<?php echo page('home')->images()->shuffle()->first()->url(); ?>')">

<?php echo $page->title()->smartypants()->widont(); ?>

			<?php echo $page->intro()->kirbytext(); ?>
			<?php echo $page->text()->kirbytext(); ?>

		<?php snippet('share_page'); ?>

<?php snippet_detect('footer'); ?>

<?php snippet_detect('html_head', array(
	'criticalcss' => 'home',
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

	<div <?php echo imgsrc($page->images()->first(), array('bgimage' => true, 'class' => 'CoverImage FluidEmbed--3by2 FluidEmbed--large16by9 FluidEmbed--huge2by1')); ?>>

<?php echo $page->title()->smartypants()->widont(); ?>

			<?php echo $page->intro()->kirbytext(); ?>
			<?php echo $page->text()->kirbytext(); ?>

		<?php snippet('share_page'); ?>

<?php snippet_detect('footer'); ?>

Use imgsrc plugin/snippet for background example.


<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Laravel 5');
    }
}

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Chris McCluskey');
    }
}

CI: Modify test case to include correct information


<?php

use Git4p\Git;
use Git4p\GitObject;
use Git4p\GitTree;

class GitTreeTest extends PHPUnit_Framework_TestCase {

    protected $git     = false;
    protected $gittree = false;

    public function setup() {
        $this->git     = new Git('/tmp/phpunit/gittestrepo');
        $this->gittree = new GitTree($this->git);
    }

    public function teardown() {
        $this->git    = false;
        $this->gittree = false;
    }

    public function testShouldReturnGitTreeType() {
        $this->assertEquals($this->gittree->type(), GitObject::TYPE_TREE);
    }

    public function testShouldHaveDirectoryName() {
        $this->gittree->setName('SomeDirectoryName');

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

}

<?php

use Git4p\Git;
use Git4p\GitObject;
use Git4p\GitTree;

class GitTreeTest extends PHPUnit_Framework_TestCase {

    protected $git     = false;
    protected $gittree = false;

    public function setup() {
        $this->git     = new Git('/tmp/phpunit/gittestrepo');
        $this->gittree = new GitTree($this->git);
    }

    public function teardown() {
        $this->git    = false;
        $this->gittree = false;
    }

    public function testShouldReturnGitTreeType() {
        $this->assertEquals($this->gittree->type(), GitObject::TYPE_TREE);
    }

    public function testShouldHaveDirectoryName() {
        $this->gittree->setName('SomeDirectoryName');

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

    public function testShouldContainReferencesToFiles() {
        $data = ['file1', 'file2'];

        $this->gittree->setData($data);
        $this->assertEquals($this->gittree->entries(), $data);
    }

}

Add some tests for GitTree

Add some tests for GitTree


<?php

namespace Oro\Bundle\TestFrameworkBundle\Provider;

use Oro\Bundle\EntityBundle\Provider\EntityAliasProviderInterface;

/**
 * This alias provider excludes aliases generation for test entities to avoid duplications of aliases.
 * TestActivity entity does not covered by this class because it should have aliases.
 */
class EntityAliasProvider implements EntityAliasProviderInterface
{
    protected static $classes = [
        'Oro\Bundle\TestFrameworkBundle\Entity\Item',
        'Oro\Bundle\TestFrameworkBundle\Entity\ItemValue',
        'Oro\Bundle\TestFrameworkBundle\Entity\Product',
        'Oro\Bundle\TestFrameworkBundle\Entity\TestActivityTarget',
        'Oro\Bundle\TestFrameworkBundle\Entity\WorkflowAwareEntity',
    ];

    /**
     * {@inheritdoc}
     */
    public function getEntityAlias($entityClass)
    {
        if (in_array($entityClass, self::$classes)) {
            return false;
        }

        return null;
    }
}

<?php

namespace Oro\Bundle\TestFrameworkBundle\Provider;

use Oro\Bundle\EntityBundle\Provider\EntityAliasProviderInterface;

/**
 * This alias provider excludes aliases generation for test entities to avoid duplications of aliases.
 * TestActivity entity does not covered by this class because it should have aliases
 * to build correct association API routes.
 */
class EntityAliasProvider implements EntityAliasProviderInterface
{
    protected static $classes = [
        'Oro\Bundle\TestFrameworkBundle\Entity\Item',
        'Oro\Bundle\TestFrameworkBundle\Entity\ItemValue',
        'Oro\Bundle\TestFrameworkBundle\Entity\Product',
        'Oro\Bundle\TestFrameworkBundle\Entity\TestActivityTarget',
        'Oro\Bundle\TestFrameworkBundle\Entity\WorkflowAwareEntity',
    ];

    /**
     * {@inheritdoc}
     */
    public function getEntityAlias($entityClass)
    {
        if (in_array($entityClass, self::$classes)) {
            return false;
        }

        return null;
    }
}

Fix API requests for B2B instance

BAP-9408: Fix API requests for B2B instance


<?php

namespace Illuminate\Http\Testing;

class FileFactory
{
    /**
     * Create a new fake file.
     *
     * @param  string  $name
     * @param  int  $kilobytes
     * @return \Illuminate\Http\Testing\File
     */
    public function create($name, $kilobytes = 0)
    {
        return tap(new File($name, tmpfile()), function ($file) use ($kilobytes) {
            $file->sizeToReport = $kilobytes * 1024;
        });
    }

    /**
     * Create a new fake image.
     *
     * @param  string  $name
     * @param  int  $width
     * @param  int  $height
     * @return \Illuminate\Http\Testing\File
     */
    public function image($name, $width = 10, $height = 10)
    {
        return new File($name, $this->generateImage($width, $height));
    }

    /**
     * Generate a dummy image of the given width and height.
     *
     * @param  int  $width
     * @param  int  $height
     * @return resource
     */
    protected function generateImage($width, $height)
    {
        return tap(tmpfile(), function ($temp) use ($width, $height) {
            imagepng(imagecreatetruecolor($width, $height), $temp);
        });
    }
}

<?php

namespace Illuminate\Http\Testing;

class FileFactory
{
    /**
     * Create a new fake file.
     *
     * @param  string  $name
     * @param  int  $kilobytes
     * @return \Illuminate\Http\Testing\File
     */
    public function create($name, $kilobytes = 0)
    {
        return tap(new File($name, tmpfile()), function ($file) use ($kilobytes) {
            $file->sizeToReport = $kilobytes * 1024;
        });
    }

    /**
     * Create a new fake image.
     *
     * @param  string  $name
     * @param  int  $width
     * @param  int  $height
     * @return \Illuminate\Http\Testing\File
     */
    public function image($name, $width = 10, $height = 10)
    {
        return new File($name, $this->generateImage($width, $height));
    }

    /**
     * Generate a dummy image of the given width and height.
     *
     * @param  int  $width
     * @param  int  $height
     * @return resource
     */
    protected function generateImage($width, $height)
    {
        return tap(tmpfile(), function ($temp) use ($width, $height) {
            ob_start();
            imagepng(imagecreatetruecolor($width, $height));
            fwrite($temp, ob_get_clean());
        });
    }
}

[5.4] Fix issue in php5.6 when generate fake images for testing


<?php

namespace MusicBrainz\Tests;

use MusicBrainz\MusicBrainz;

/**
 * @covers MusicBrainz\MusicBrainz
 */
class MusicBrainzTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->brainz = new MusicBrainz();
    }

    public function MBIDProvider()
    {
        return array(
            array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
          , array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
          , array(false, '4dbf5678-7a314-06aabb-e232f-8ac2cd63') // invalid spacing for UUID's
          , array(false, '4dbf5678-7a31-406a-abbe-232f8az2cd63') // z is an invalid character
        );
    }

    /**
     * @dataProvider MBIDProvider
     */
    public function testIsValidMBID($validation, $mbid)
    {
        $this->assertEquals($validation, $this->brainz->isValidMBID($mbid));
    }
}

<?php

namespace MusicBrainz\Tests;

use MusicBrainz\MusicBrainz;
use Guzzle\Http\Client;

/**
 * @covers MusicBrainz\MusicBrainz
 */
class MusicBrainzTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->brainz = new MusicBrainz(new Client());
    }

    public function MBIDProvider()
    {
        return array(
            array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
          , array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
          , array(false, '4dbf5678-7a314-06aabb-e232f-8ac2cd63') // invalid spacing for UUID's
          , array(false, '4dbf5678-7a31-406a-abbe-232f8az2cd63') // z is an invalid character
        );
    }

    /**
     * @dataProvider MBIDProvider
     */
    public function testIsValidMBID($validation, $mbid)
    {
        $this->assertEquals($validation, $this->brainz->isValidMBID($mbid));
    }
}

Fix unit test to pass Guzzle as a dependency


<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Input;
use DB;
use Log;

class ChartDimension extends Model {
	public $timestamps = false;
	protected $guarded = array();

	public function chart() {
		return $this->belongsTo('App\Chart', 'chartId');
	}
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Input;
use DB;
use Log;

class ChartDimension extends Model {
	public $timestamps = false;
	protected $guarded = array();

    // HACK (Mispy): Bug with some versions of PHP(?) where integers come back
    // as strings from the database.
    protected $casts = [
        'chartId' => 'integer',
        'variableId' => 'integer',
        'order' => 'integer',
        'tolerance' => 'integer',
        'targetYear' => 'integer'
    ];

	public function chart() {
		return $this->belongsTo('App\Chart', 'chartId');
	}
}

Fix dimension integers being cast to strings for no good reason


<?php

class MaterialRepositoryCache extends MaterialRepository
{
  const CACHE_KEY = "materialRepository";
  public function parse()
  {
    if(Cache::has(self::CACHE_KEY))
    {
      $this->database = Cache::get(self::CACHE_KEY);
      return;
    }
    $this->database = parent::read();
    Cache::put(self::CACHE_KEY, $this->database, 60);
  }

}

<?php

class MaterialRepositoryCache extends MaterialRepository
{
  const CACHE_KEY = "materialRepository";
  public function parse()
  {
    if(Cache::has(self::CACHE_KEY))
    {
      $this->database = Cache::get(self::CACHE_KEY);
      return;
    }
    $this->database = parent::read();
    $this->snapshot();
  }

  public function snapshot()
  {
    Cache::put(self::CACHE_KEY, $this->database, 60);
  }

}

Make the material repository cache behave like the other caches.


<?php namespace Anomaly\PreferencesModule\Http\Middleware\Command;

use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class SetDatetime
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\PreferencesModule\Http\Middleware\Command
 */
class SetDatetime implements SelfHandling
{

    /**
     * Handle the command.
     *
     * @param Repository                    $config
     * @param PreferenceRepositoryInterface $preferences
     */
    function handle(Repository $config, PreferenceRepositoryInterface $preferences)
    {
        // Set the timezone.
        if ($timezone = $preferences->get('streams::timezone')) {
            $config->set('app.timezone', $timezone);
        }

        // Set the date format.
        if ($format = $preferences->get('streams::date_format')) {
            $config->set('streams::datetime.date_format', $format);
        }

        // Set the time format.
        if ($format = $preferences->get('streams::time_format')) {
            $config->set('streams::datetime.time_format', $format);
        }
    }
}

<?php namespace Anomaly\PreferencesModule\Http\Middleware\Command;

use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class SetDatetime
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\PreferencesModule\Http\Middleware\Command
 */
class SetDatetime implements SelfHandling
{

    /**
     * Handle the command.
     *
     * @param Repository                    $config
     * @param PreferenceRepositoryInterface $preferences
     */
    function handle(Repository $config, PreferenceRepositoryInterface $preferences)
    {
        // Set the timezone.
        if ($timezone = $preferences->get('streams::timezone')) {
            $config->set('app.timezone', $timezone);
            $config->set('streams::datetime.timezone', $timezone);
        }

        // Set the date format.
        if ($format = $preferences->get('streams::date_format')) {
            $config->set('streams::datetime.date_format', $format);
        }

        // Set the time format.
        if ($format = $preferences->get('streams::time_format')) {
            $config->set('streams::datetime.time_format', $format);
        }
    }
}

Set streams too since it's the same

Set streams too since it's the same


<?php

namespace Maghead\Runtime\Config;

use PHPUnit\Framework\TestCase;

class ApcuConfigLoaderTest extends TestCase
{
    public function setUp() {
        parent::setUp();
        if (!extension_loaded('apcu')) {
            return $this->markTestSkipped('require apcu extension.');
        }
    }

    public function testApcuConfigLoader()
    {
        $config = ApcuConfigLoader::load("testapp", function() {
            return FileConfigLoader::load('tests/config/mysql.yml');
        });
        $this->assertInstanceOf('Maghead\\Runtime\\Config\\Config', $config);
    }
}

<?php

namespace Maghead\Runtime\Config;

use PHPUnit\Framework\TestCase;

class ApcuConfigLoaderTest extends TestCase
{
    public function setUp() {
        parent::setUp();
        if (!extension_loaded('apcu')) {
            return $this->markTestSkipped('require apcu extension.');
        }
    }

    public function testApcuConfigLoaderFallback()
    {
        $config = ApcuConfigLoader::load("testapp", function() {
            return FileConfigLoader::load('tests/config/mysql.yml');
        });
        $this->assertInstanceOf('Maghead\\Runtime\\Config\\Config', $config);
    }

    public function testApcuConfigLoaderSecondFallback()
    {
        $config = ApcuConfigLoader::load("testapp", function() {
            return false;
        }, function() {
            return FileConfigLoader::load('tests/config/mysql.yml');
        });
        $this->assertInstanceOf('Maghead\\Runtime\\Config\\Config', $config);
    }
}

Test apcu config loader second fallback

Test apcu config loader second fallback


<?php

use League\FactoryMuffin\Facade as FactoryMuffin;

abstract class AbstractTestCase extends PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
    }

    public static function tearDownAfterClass()
    {
        FactoryMuffin::deleteSaved();
    }
}

<?php

use League\FactoryMuffin\Facade as FactoryMuffin;

abstract class AbstractTestCase extends PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::setFakerLocale('en_GB')->loadFactories(__DIR__ . '/factories');
    }

    public static function tearDownAfterClass()
    {
        FactoryMuffin::deleteSaved();
    }
}

Cover the set faker method

Cover the set faker method


<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\Markdown;

use Michelf\MarkdownExtra;

class MichelfMarkdown implements MarkdownInterface
{
    private $converter;

    public function __construct(MarkdownExtra $converter = null)
    {
        if (null === $converter) {
            $converter = new MarkdownExtra();
            $converter->hard_wrap = true;
        }

        $this->converter = $converter;
    }

    public function convert(string $body): string
    {
        return $this->converter->defaultTransform($body);
    }
}

<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\Markdown;

use Michelf\MarkdownExtra;

class MichelfMarkdown implements MarkdownInterface
{
    private $converter;

    public function __construct(MarkdownExtra $converter = null)
    {
        if (null === $converter) {
            $converter = new MarkdownExtra();
            $converter->hard_wrap = true;
        }

        $this->converter = $converter;
    }

    public function convert(string $body): string
    {
        return $this->converter->transform($body);
    }
}

Fix transform call to Michelf\MarkdownExtra

As per the documentation here:

  https://michelf.ca/projects/php-markdown/configuration/#configure

Calling defaultTransform() will use the default options, thus ignoring
the "hard_wrap" option. Calling transform() instead, which takes the
options into account.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShopAssignment extends Model
{
    protected $fillable = [
        'shop_id',
        'user_id',
        'roles_id'
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }
    public function roles()
    {
        return $this->hasMany('App\Role');
    }
    public function shops()
    {
        retrun $this->hasMany('App\Shop')
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShopAssignment extends Model
{
    protected $fillable = [
        'shop_id',
        'user_id',
        'role_id'
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }
    public function roles()
    {
        return $this->hasMany('App\Role');
    }
    public function shops()
    {
        return $this->hasMany('App\Shop')
    }
}

feat(shopassignment): Create relationship for shopassignment table

Create relationship for shopassignment table

see #138


<?php

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

class CreateRoleAssignmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('party_assignments', function (Blueprint $table) {
            $table->uuid('party_uuid');
            $table->uuid('agreement_uuid');
            $table->uuid('role_uuid');
            $table->unique(['role_uuid', 'agreement_uuid']);
            $table->timestamps();
        });
    }

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

<?php

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

class CreateRoleAssignmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('party_assignments', function (Blueprint $table) {
            $table->uuid('party_uuid');
            $table->foreign('party_uuid')->references('uuid')->on('parties');
            $table->uuid('agreement_uuid');
            $table->foreign('agreement_uuid')->references('uuid')->on('agreements');
            $table->uuid('role_uuid');
            $table->foreign('role_uuid')->references('uuid')->on('roles');
            $table->unique(['role_uuid', 'agreement_uuid']);
            $table->timestamps();
        });
    }

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

Add role assignments foreign keys to db

Add role assignments foreign keys to db


<?php
namespace Baum\Generators;

class MigrationGenerator extends Generator {

  /**
   * Create a new migration at the given path.
   *
   * @param  string  $name
   * @param  string  $path
   * @return string
   */
  public function create($name, $path) {
    $path = $this->getPath($name, $path);

    $stub = $this->getStub('migration');

    $this->files->put($path, $this->parseStub($stub, [
      'table' => $this->tableize($name),
      'class' => $this->classify($name)
    ]));

    return $path;
  }

  /**
   * Get the full path name to the migration.
   *
   * @param  string  $name
   * @param  string  $path
   * @return string
   */
  protected function getPath($name, $path) {
    return $path . '/' . $this->getDatePrefix() . '_create_' . $this->tableize($name) . '_table.php';
  }

  /**
   * Get the date prefix for the migration.
   *
   * @return int
   */
  protected function getDatePrefix() {
    return date('Y_m_d_His');
  }

}

<?php
namespace Baum\Generators;

class MigrationGenerator extends Generator {

  /**
   * Create a new migration at the given path.
   *
   * @param  string  $name
   * @param  string  $path
   * @return string
   */
  public function create($name, $path) {
    $path = $this->getPath($name, $path);

    $stub = $this->getStub('migration');

    $this->files->put($path, $this->parseStub($stub, [
      'table' => $this->tableize($name),
      'class' => $this->getMigrationClassName($name)
    ]));

    return $path;
  }

  /**
   * Get the migration name.
   *
   * @param string $name
   * @return string
   */
  protected function getMigrationName($name) {
    return 'create_' . $this->tableize($name) . '_table';
  }

  /**
   * Get the name for the migration class.
   *
   * @param string $name
   */
  protected function getMigrationClassName($name) {
    return $this->classify($this->getMigrationName($name));
  }

  /**
   * Get the full path name to the migration.
   *
   * @param  string  $name
   * @param  string  $path
   * @return string
   */
  protected function getPath($name, $path) {
    return $path . '/' . $this->getDatePrefix() . '_' . $this->getMigrationName($name) . '.php';
  }

  /**
   * Get the date prefix for the migration.
   *
   * @return int
   */
  protected function getDatePrefix() {
    return date('Y_m_d_His');
  }

}

Fix generated migration class name.

Fix generated migration class name.


<?php

namespace ProcessWire\GraphQL\Field\Traits;

use Youshido\GraphQL\Config\Field\FieldConfig;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Field\InputField;
use Youshido\GraphQL\Type\Scalar\StringType;
use ProcessWire\GraphQL\Utils;
use ProcessWire\NullPage;
use ProcessWire\FieldtypeDatetime;

trait DatetimeResolverTrait {

  public function build(FieldConfig $config)
  {
    $config->addArgument(new InputField([
      'name' => 'format',
      'type' => new StringType(),
      'description' => 'PHP date formatting string. Refer to https://devdocs.io/php/function.date',
    ]));
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    $fieldName = $this->getName();

    if (isset($args['format'])) {
      $format = $args['format'];
      $rawValue = $value->$fieldName;
      if (Utils::fields()->get($fieldName) instanceof FieldtypeDatetime) {
        $rawValue = $value->getUnformatted($fieldName);
      }
      if ($rawValue) {
        return date($format, $rawValue);
      } else {
        return "";
      }
    }

    return $value->$fieldName;
  }
}

<?php

namespace ProcessWire\GraphQL\Field\Traits;

use Youshido\GraphQL\Config\Field\FieldConfig;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Field\InputField;
use Youshido\GraphQL\Type\Scalar\StringType;
use ProcessWire\GraphQL\Utils;
use ProcessWire\NullPage;
use ProcessWire\FieldtypeDatetime;

trait DatetimeResolverTrait {

  public function build(FieldConfig $config)
  {
    $config->addArgument(new InputField([
      'name' => 'format',
      'type' => new StringType(),
      'description' => 'PHP date formatting string. Refer to https://devdocs.io/php/function.date',
    ]));
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    $fieldName = $this->getName();

    if (isset($args['format'])) {
      $format = $args['format'];
      $rawValue = $value->$fieldName;
      $field = Utils::fields()->get($fieldName);
      if ($field && $field->type instanceof FieldtypeDatetime) {
        $rawValue = $value->getUnformatted($fieldName);
      }
      if ($rawValue) {
        return date($format, $rawValue);
      } else {
        return "";
      }
    }

    return $value->$fieldName;
  }
}

Add 'format' argument to built-in fields 'created' & 'modified'.


<?php
namespace LazyRecord\SqlBuilder;
use LazyRecord\Schema;
use LazyRecord\Schema\DeclareSchema;
use LazyRecord\Schema\SchemaInterface;
use LazyRecord\Schema\RuntimeColumn;
use LazyRecord\Schema\DeclareColumn;
use SQLBuilder\ArgumentArray;

/**
 * Schema SQL builder
 *
 * @see http://www.sqlite.org/docs.html
 */
class PgsqlBuilder extends BaseBuilder
{

    public function buildColumnSql(SchemaInterface $schema, DeclareColumn $column) {
        $name = $column->name;
        $isa  = $column->isa ?: 'str';
        if (!$column->type && $isa == 'str') {
            $column->type = 'text';
        }
        $args = new ArgumentArray;
        $sql = $column->buildDefinitionSql($this->driver, $args);
        return $sql;
    }

    public function dropTable(SchemaInterface $schema)
    {
        return 'DROP TABLE IF EXISTS '
                . $this->driver->quoteIdentifier( $schema->getTable() )
                . ' CASCADE';
    }

}

<?php
namespace LazyRecord\SqlBuilder;
use LazyRecord\Schema;
use LazyRecord\Schema\DeclareSchema;
use LazyRecord\Schema\SchemaInterface;
use LazyRecord\Schema\RuntimeColumn;
use LazyRecord\Schema\DeclareColumn;
use SQLBuilder\ArgumentArray;

/**
 * Schema SQL builder
 *
 * @see http://www.sqlite.org/docs.html
 */
class PgsqlBuilder extends BaseBuilder
{

    public function buildColumnSql(SchemaInterface $schema, DeclareColumn $column) {
        $name = $column->name;
        $isa  = $column->isa ?: 'str';
        if (!$column->type && $isa == 'str') {
            $column->type = 'text';
        }

        // Note that pgsql doesn't support unsigned integer primary key column
        if ($column->autoIncrement) {
            $column->unsigned = false;
        }

        $args = new ArgumentArray;
        $sql = $column->buildDefinitionSql($this->driver, $args);
        return $sql;
    }

    public function dropTable(SchemaInterface $schema)
    {
        return 'DROP TABLE IF EXISTS '
                . $this->driver->quoteIdentifier( $schema->getTable() )
                . ' CASCADE';
    }

}

Fix primary key column for pgsql

Fix primary key column for pgsql


<?php

namespace Egzaminer\Exam;

use Exception;
use Egzaminer\Question\Questions;
use Egzaminer\Question\Answers;
use Egzaminer\Admin\Dashboard as Controller;

class Exam extends Controller
{
    public function showAction($id)
    {
        $testInfo = (new ExamModel())->getInfo($id);

        if (false === $testInfo) {
            throw new Exception('Exam not exists!');
        }

        $questions = (new Questions())->getByExamId($id);
        $answers = (new Answers())->getAnswersByQuestions($questions);

        // if form was send
        if (!empty($_POST)) {
            $stats = (new ExamStat())->getStats($testInfo, $questions, $_POST);

            $this->data['test-check'] = [
                'test' => $testInfo,
                'questions' => $questions,
                'answers' => $answers,
                'stats' => $stats,
            ];

            $template = 'test-check';
        } else {
            $this->data['test'] = [
                'title' => $testInfo['title'],
                'questions' => $questions,
                'answers' => $answers,
            ];

            $template = 'test';
        }

        $this->render($template, $testInfo['title']);
    }
}

<?php

namespace Egzaminer\Exam;

use Exception;
use Egzaminer\Question\Questions;
use Egzaminer\Question\Answers;
use Egzaminer\Controller as Controller;

class Exam extends Controller
{
    public function showAction($id)
    {
        $testInfo = (new ExamModel())->getInfo($id);

        if (false === $testInfo) {
            throw new Exception('Exam not exists!');
        }

        $questions = (new Questions())->getByExamId($id);
        $answers = (new Answers())->getAnswersByQuestions($questions);

        // if form was send
        if (!empty($_POST)) {
            $stats = (new ExamStat())->getStats($testInfo, $questions, $_POST);

            $this->data['test-check'] = [
                'test' => $testInfo,
                'questions' => $questions,
                'answers' => $answers,
                'stats' => $stats,
            ];

            $template = 'test-check';
        } else {
            $this->data['test'] = [
                'title' => $testInfo['title'],
                'questions' => $questions,
                'answers' => $answers,
            ];

            $template = 'test';
        }

        $this->render($template, $testInfo['title']);
    }
}

Fix access to one exam page

Fix access to one exam page

now is only for logged users


<?php

namespace PragmaRX\Tracker\Vendor\Laravel\Middlewares;

use Closure;

class Tracker
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app('tracker')->boot();

        return $next($request);
    }
}

<?php

namespace PragmaRX\Tracker\Vendor\Laravel\Middlewares;

use Config;
use Closure;

class Tracker
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Config::get('tracker.enabled'))
        {
            app('tracker')->boot();
        }

        return $next($request);
    }
}

Fix tracker disabled state when using middleware


<?php

use yii\db\Migration;

/**
 * Handles the creation for table `profile`.
 */
class m160622_095150_create_profile extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {

        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('profile', [
            'id' => $this->primaryKey(),
            'sex' => $this->string(),
        ]);
        $this->addForeignKey('FK_profile_user', 'profile', 'id', 'user', 'id');;
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `profile`
        $this->dropForeignKey(
            'FK_profile_user',
            'profile'
        );
        $this->dropTable('profile');
    }
}

<?php

use yii\db\Migration;

/**
 * Handles the creation for table `profile`.
 */
class m160622_095150_create_profile extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {

        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('profile', [
            'id' => $this->primaryKey(),
            'sex' => $this->string(),
            'email' => $this->string()->notNull()->unique(),
        ], $tableOptions);

        $this->addForeignKey('FK_profile_user', 'profile', 'email', 'user', 'email');
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `profile`
        $this->dropForeignKey(
            'FK_profile_user',
            'profile'
        );
        $this->dropTable('profile');
    }
}

Use email as foreign key

Use email as foreign key


<?php

use Hubzero\Content\Migration\Base;

/**
 * Migration script for com_tools to specify display ranges assigned to a hub,
 * i.e., the range used on an execution host.
 **/

class Migration20180703151011ComTools extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		// ADD COLUMN first_display to table host
		if ($mwdb->tableExists('host') && !$mwdb->tableHasField('host', 'first_display'))
		{
			$query = "ALTER TABLE host ADD COLUMN first_display INT DEFAULT 1;";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		// Drop column first_display
		if ($mwdb->tableExists('host') && $mwdb->tableHasField('host', 'first_display'))
		{
			$query = "ALTER TABLE host DROP COLUMN first_display;";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}
}

<?php

use Hubzero\Content\Migration\Base;

/**
 * Migration script for com_tools to specify display ranges assigned to a hub,
 * i.e., the range used on an execution host.
 **/

class Migration20180703151011ComTools extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		// ADD COLUMN first_display to table host
		if ($mwdb->tableExists('host') && !$mwdb->tableHasField('host', 'first_display'))
		{
			$query = "ALTER TABLE host ADD COLUMN first_display INT DEFAULT 1;";
			$mwdb->setQuery($query);
			$mwdb->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if (!$mwdb = $this->getMWDBO())
		{
			$this->setError('Failed to connect to the middleware database', 'warning');
			return false;
		}

		// Drop column first_display
		if ($mwdb->tableExists('host') && $mwdb->tableHasField('host', 'first_display'))
		{
			$query = "ALTER TABLE host DROP COLUMN first_display;";
			$mwdb->setQuery($query);
			$mwdb->query();
		}
	}
}

Use middleware db for the query

[fix] Use middleware db for the query


Update local config cache settings.

Update local config cache settings.


<?php
namespace MartinBean\Facebook\Laravel;

use Facebook\FacebookRedirectLoginHelper as BaseFacebookRedirectLoginHelper;
use Request;
use Session;

class FacebookRedirectLoginHelper extends BaseFacebookRedirectLoginHelper
{
    /**
     * Check if a redirect has a valid state.
     *
     * @return bool
     */
    protected function isValidRedirect()
    {
        return $this->getCode() && Request::get('state', null) == $this->state;
    }

    /**
     * Return the code.
     *
     * @return string|null
     */
    protected function getCode()
    {
        return Request::get('code', null);
    }

    /**
     * Stores a state string in session storage for CSRF protection.
     *
     * @param string $state
     */
    protected function storeState($state)
    {
        Session::put($this->getSessionKey(), $state);
    }

    /**
     * Loads a state from session storage for CSRF validation.
     *
     * @return string|null
     */
    protected function loadState()
    {
        return $this->state = Session::get($this->getSessionKey(), null);
    }

    /**
     * A helper method to get the session key to use.
     *
     * @return string
     */
    protected function getSessionKey()
    {
        return 'facebook.state';
    }
}

<?php
namespace MartinBean\Facebook\Laravel;

use Facebook\FacebookRedirectLoginHelper as BaseFacebookRedirectLoginHelper;
use Request;
use Session;

class FacebookRedirectLoginHelper extends BaseFacebookRedirectLoginHelper
{
    /**
     * Check if a redirect has a valid state.
     *
     * @return bool
     */
    protected function isValidRedirect()
    {
        $this->loadState();
        return $this->getCode() && Request::get('state', null) == $this->state;
    }

    /**
     * Return the code.
     *
     * @return string|null
     */
    protected function getCode()
    {
        return Request::get('code', null);
    }

    /**
     * Stores a state string in session storage for CSRF protection.
     *
     * @param string $state
     */
    protected function storeState($state)
    {
        Session::put($this->getSessionKey(), $state);
    }

    /**
     * Loads a state from session storage for CSRF validation.
     *
     * @return string|null
     */
    protected function loadState()
    {
        return $this->state = Session::get($this->getSessionKey(), null);
    }

    /**
     * A helper method to get the session key to use.
     *
     * @return string
     */
    protected function getSessionKey()
    {
        return 'facebook.state';
    }
}

Load the state before checking whether the state values match.


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Exception;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

Fix CS issues reported by php-cs-fixer

Fix CS issues reported by php-cs-fixer

- Remove unused use


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\OutputConverter;

/**
 * Basic output converter that supports gif/png/jpg.
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\OutputConverters
 */
class Basic implements OutputConverterInterface {
    public function getSupportedFormatsWithCallbacks() {
        return [
            [
                'mime' => 'image/png',
                'extension' => 'png',
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/jpeg',
                'extension' => ['jpg', 'jpeg'],
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/gif',
                'extension' => 'gif',
                'callback' => [$this, 'convert'],
            ],
        ];
    }

    public function convert($imagick, $image, $extension, $mime = null) {
        try {
            $imagick->setImageFormat($extension);
        } catch (ImagickException $e) {
            throw new OutputConversionException($e->getMessage(), 400, $e);
        }
    }
}

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\OutputConverter;

/**
 * Basic output converter that supports gif/png/jpg.
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\OutputConverters
 */
class Basic implements OutputConverterInterface {
    public function getSupportedFormatsWithCallbacks() {
        return [
            [
                'mime' => 'image/jpeg',
                'extension' => ['jpg', 'jpeg'],
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/png',
                'extension' => 'png',
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/gif',
                'extension' => 'gif',
                'callback' => [$this, 'convert'],
            ],
        ];
    }

    public function convert($imagick, $image, $extension, $mime = null) {
        try {
            $imagick->setImageFormat($extension);
        } catch (ImagickException $e) {
            throw new OutputConversionException($e->getMessage(), 400, $e);
        }

        $image->hasBeenTransformed(true);
    }
}

Change priority of output converters

Change priority of output converters


<?php

namespace Aureka\VBBundle\Handler;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

use Aureka\VBBundle\VBUsers,
    Aureka\VBBundle\VBSession;
use Aureka\VBBundle\Exception\VBUserException;

class LoginHandler implements AuthenticationSuccessHandlerInterface
{

    private $userProvider;
    private $session;

    private $userToLogIn;

    public function __construct(VBUsers $user_provider, VBSession $session)
    {
        $this->userProvider = $user_provider;
        $this->session = $session;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        try {
            $this->userToLogIn = $this->userProvider->load($this->session, $user->getUsername());
        } catch (VBUserException $e) {
            $this->userToLogIn = $this->userProvider->create($this->session, $user->getUsername(), $user->getPassword());
        }
        return new RedirectResponse('/');
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        if (!is_null($this->userToLogIn)) {
            $this->session->login($event->getResponse());
            $this->userProvider->updateSession($this->session);
            $this->userToLogIn = null;
        }
    }
}

<?php

namespace Aureka\VBBundle\Handler;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

use Aureka\VBBundle\VBUsers,
    Aureka\VBBundle\VBSession;
use Aureka\VBBundle\Exception\VBUserException;

class LoginHandler implements AuthenticationSuccessHandlerInterface
{

    private $userProvider;
    private $session;

    private $userToLogIn;

    public function __construct(VBUsers $user_provider, VBSession $session)
    {
        $this->userProvider = $user_provider;
        $this->session = $session;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        try {
            $this->userToLogIn = $this->userProvider->load($this->session, $user->getUsername());
        } catch (VBUserException $e) {
            $this->userToLogIn = $this->userProvider->create($this->session, $user->getUsername(), $user->getPassword());
        }
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        if (!is_null($this->userToLogIn)) {
            $this->session->login($event->getResponse());
            $this->userProvider->updateSession($this->session);
            $this->userToLogIn = null;
        }
    }
}

Revert "The login handler now returns a response"

This reverts commit 90c53eebeece07cb7e8f54b757c509a364502022.


<?php

namespace Common\BlockEditor\Blocks;

final class QuoteBlock extends AbstractBlock
{
    public function getConfig(): array
    {
        return [
            'class' => 'BlockEditor.blocks.Quote',
        ];
    }

    public function getValidation(): array
    {
        return [
            'text' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'caption' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'alignment' => [
                'canBeOnly' => '["left", "center"]',
            ],
        ];
    }

    public function parse(array $data): string
    {
        return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data);
    }

    public function getJavaScriptUrl(): ?string
    {
        return null;
    }
}

<?php

namespace Common\BlockEditor\Blocks;

final class QuoteBlock extends AbstractBlock
{
    public function getConfig(): array
    {
        return [
            'class' => 'BlockEditor.blocks.Quote',
        ];
    }

    public function getValidation(): array
    {
        return [
            'text' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'caption' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'alignment' => [
                'type' => 'string',
                'canBeOnly' => ['left', 'center'],
            ],
        ];
    }

    public function parse(array $data): string
    {
        return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data);
    }

    public function getJavaScriptUrl(): ?string
    {
        return null;
    }
}

Add canOnlyBe values for alignment

Add canOnlyBe values for alignment


<?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\Metadata;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AttributeReader implements Reader
{
    /**
     * @psalm-param class-string $className
     */
    public function forClass(string $className): MetadataCollection
    {
        return MetadataCollection::fromArray([]);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forMethod(string $className, string $methodName): MetadataCollection
    {
        return MetadataCollection::fromArray([]);
    }
}

<?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\Metadata;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AttributeReader implements Reader
{
    /**
     * @psalm-param class-string $className
     */
    public function forClass(string $className): MetadataCollection
    {
        $result = [];

        return MetadataCollection::fromArray($result);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forMethod(string $className, string $methodName): MetadataCollection
    {
        $result = [];

        return MetadataCollection::fromArray($result);
    }
}

Make this slightly less as simple as possible


<?php

/**
 * @file
 * template.php
 */

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_block(&$vars) {

  switch ($vars['block_html_id']) {

  case 'block-serchilo-namespaces':

    // Put a well around namespaces block.
    $vars['classes_array'][] = 'well';
    $vars['classes_array'][] = 'well-sm';

    break;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_button(&$vars) {

  switch ($vars['element']['#id']) {
  case 'edit-submit-shortcuts':
    // Make Go button a primary button.
    $vars['element']['#attributes']['class'][] = 'btn-primary';
    break;
  case 'edit-reset':
    // Make Reset button a warning button.
    $vars['element']['#attributes']['class'][] = 'btn-warning';
    break;
  }
}

<?php

/**
 * @file
 * template.php
 */

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_block(&$vars) {

  switch ($vars['block_html_id']) {

  case 'block-serchilo-namespaces':

    // Put a well around namespaces block.
    $vars['classes_array'][] = 'well';
    $vars['classes_array'][] = 'well-sm';

    break;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_button(&$vars) {

  switch ($vars['element']['#id']) {
  // Make Go button a primary button.
  // Make Apply button a primary button.
  case 'edit-submit':
  case 'edit-submit-shortcuts':
    $vars['element']['#attributes']['class'][] = 'btn-primary';
    break;
  case 'edit-reset':
    // Make Reset button a warning button.
    $vars['element']['#attributes']['class'][] = 'btn-warning';
    break;
  }
}

Make Go and Apply button a primary button.


<?php
namespace Concrete\Core\Html\Service;

class Seo
{
    private $siteName = '';
    private $titleSegments = array();
    private $titleSegmentSeparator = ' :: ';
    private $titleFormat = '%1$s :: %2$s';
    private $hasCustomTitle = false;

    public function setSiteName($name)
    {
        $this->siteName = $name;
    }

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

    public function setCustomTitle($title)
    {
        $this->hasCustomTitle = true;
        $this->titleSegments = array();
        $this->addTitleSegmentBefore($title);
        return $this;
    }

    public function addTitleSegment($segment)
    {
        array_push($this->titleSegments, $segment);
        return $this;
    }

    public function addTitleSegmentBefore($segment)
    {
        array_unshift($this->titleSegments, $segment);
        return $this;
    }

    public function setTitleFormat($format)
    {
        $this->titleFormat = $format;
        return $this;
    }

    public function setTitleSegmentSeparator($separator)
    {
        $this->titleSegmentSeparator = $separator;
        return $this;
    }

    public function getTitle()
    {
        $segments = '';
        if (count($this->titleSegments) > 0) {
            $segments = implode($this->titleSegmentSeparator, $this->titleSegments);
        }
        return sprintf($this->titleFormat, $this->siteName, $segments);
    }
}

<?php
namespace Concrete\Core\Html\Service;

class Seo
{
    private $siteName = '';
    private $titleSegments = array();
    private $titleSegmentSeparator = ' :: ';
    private $titleFormat = '%1$s :: %2$s';
    private $hasCustomTitle = false;

    public function setSiteName($name)
    {
        $this->siteName = $name;
    }

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

    public function setCustomTitle($title)
    {
        $this->hasCustomTitle = true;
        $this->clearTitleSegments();
        $this->addTitleSegmentBefore($title);
        return $this;
    }

    public function addTitleSegment($segment)
    {
        array_push($this->titleSegments, $segment);
        return $this;
    }

    public function addTitleSegmentBefore($segment)
    {
        array_unshift($this->titleSegments, $segment);
        return $this;
    }

    public function clearTitleSegments()
    {
        $this->titleSegments = array();
    }

    public function setTitleFormat($format)
    {
        $this->titleFormat = $format;
        return $this;
    }

    public function setTitleSegmentSeparator($separator)
    {
        $this->titleSegmentSeparator = $separator;
        return $this;
    }

    public function getTitle()
    {
        $segments = '';
        if (count($this->titleSegments) > 0) {
            $segments = implode($this->titleSegmentSeparator, $this->titleSegments);
        }
        return sprintf($this->titleFormat, $this->siteName, $segments);
    }
}

Add clearTitleSegments method to seo helper

Former-commit-id: 7eaed8690b7c184f477a748e87ea13cb89bb9ef8
Former-commit-id: 52e068afc53274320ccd396396bb64f1c71343d0


<?php

namespace Oro\Bundle\CalendarBundle\Migrations\Schema\v1_4;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroCalendarBundle implements Migration
{

    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $table = $schema->getTable('oro_calendar_event');
        $table->addIndex(['updated_at'], 'oro_calendar_event_updated_at_idx', []);
    }
}

BAP-5789: Return updatedAt field for API methods of Calendar Events. CS fix


<?php

namespace framework

class Database {

	public function conect($dsn){
	}
	private function executeSql($sql){
	}
	public function insert ($table, $fields, $datas){
		$this->executeSql("INSERT INTO {$table}(". implode(',',$fields).") VALUES (". implode(',',$datas).");");
	}
	public function update($table, $fields, $datas){
		$this->executeSql("UPDATE {$table} SET ------ = ------- WHERE id = {$id}");
	}
	public function delete($table, $id){
		$this->executeSql("DELETE FROM {$table} WHERE id = {$id}");
	}
	public function select($table, $fields, $where){
		$this->executeSql("SELECT FROM {$table} WHERE id = {$id}");
	}

}

?>

<?php

namespace framework

class Database {

	public function conect($dsn){
	}
	private function executeSql($sql){
	}
	public function insert ($table, $fields, $datas){
		$this->executeSql("INSERT INTO {$table}(". implode(',',$fields).") VALUES (". implode(',',$datas).");");
	}
	public function update($table, $fields, $datas){
	}
	public function delete($table, $id){
	}
	public function select($table, $fields, $where){
	}

}

?>

Revert "Segunda Tentativa - Funções"

Revert "Segunda Tentativa - Funções"

This reverts commit 167ae524b3e5a3e25540d123cc2b9535df9453bb.


<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider {

	/**
	 * This namespace is applied to the controller routes in your routes file.
	 *
	 * In addition, it is set as the URL generator's root namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'App\Http\Controllers';

	/**
	 * Define your route model bindings, pattern filters, etc.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function boot(Router $router)
	{
		parent::boot($router);

		$router->model('contact',  'App\Contact');
		$router->model('business', 'App\Business');
		$router->model('service',  'App\Service');
		$router->bind('business_slug', function($business_slug)
		{
			return \App\Business::where('slug', $business_slug)->first();
		});
	}

	/**
	 * Define the routes for the application.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function map(Router $router)
	{
		$router->group(['namespace' => $this->namespace], function($router)
		{
			require app_path('Http/routes.php');
		});
	}

}

<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App\Business;

class RouteServiceProvider extends ServiceProvider {

	/**
	 * This namespace is applied to the controller routes in your routes file.
	 *
	 * In addition, it is set as the URL generator's root namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'App\Http\Controllers';

	/**
	 * Define your route model bindings, pattern filters, etc.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function boot(Router $router)
	{
		parent::boot($router);

		$router->model('contact',  'App\Contact');
		$router->model('business', 'App\Business');
		$router->model('service',  'App\Service');
		$router->bind('business_slug', function($business_slug)
		{
			return Business::where('slug', $business_slug)->first();
		});
	}

	/**
	 * Define the routes for the application.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function map(Router $router)
	{
		$router->group(['namespace' => $this->namespace], function($router)
		{
			require app_path('Http/routes.php');
		});
	}

}

Remove class namespace prefix and declare on top


<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

Add versioning to api routes (api/v1)

Add versioning to api routes (api/v1)


<?php

namespace Nodes\Backend\Models\User\Validation;

use Nodes\Validation\AbstractValidator;

/**
 * Class UserValidation.
 */
class UserValidator extends AbstractValidator
{
    /**
     * Validation rules.
     *
     * @var array
     */
    protected $rules = [
        'create' => [
            'name' => ['required'],
            'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
            'password' => ['required_without:id', 'min:6', 'confirmed'],
            'user_role' => ['required', 'exists:backend_roles,slug'],
        ],
        'update-password' => [
            'password' => ['required_without:id', 'min:6', 'confirmed'],
        ],
    ];
}

<?php

namespace Nodes\Backend\Models\User\Validation;

use Nodes\Validation\AbstractValidator;

/**
 * Class UserValidation.
 */
class UserValidator extends AbstractValidator
{
    /**
     * Validation rules.
     *
     * @var array
     */
    protected $rules = [
        'create' => [
            'name' => ['required'],
            'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
            'password' => ['required_without:id', 'min:6', 'confirmed'],
            'user_role' => ['required', 'exists:backend_roles,slug'],
            'image' => ['mimes:jpeg,png']
        ],
        'update-password' => [
            'password' => ['required_without:id', 'min:6', 'confirmed'],
            'image' => ['mimes:jpeg,png']
        ],
    ];
}

Enforce image on backend users images to be actual images


<?php namespace Orchestra\Asset;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class AssetServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['orchestra.asset'] = $this->app->share(function ($app) {
            return new Environment($app);
        });

        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('Orchestra\Asset', 'Orchestra\Support\Facades\Asset');
        });
    }

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

<?php namespace Orchestra\Asset;

use Illuminate\Support\ServiceProvider;

class AssetServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['orchestra.asset'] = $this->app->share(function ($app) {
            return new Environment($app);
        });
    }

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

Remove alias from service provider

Remove alias from service provider

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


<?php

namespace Vaffel\Tuski\Silex\Provider;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\ControllerProviderInterface;
use Silex\Application;

class TusControllerProvider implements ControllerProviderInterface
{
    public function setBaseRoute($baseRoute)
    {
        $this->baseRoute = $baseRoute;

        return $this;
    }

    public function connect(Application $app)
    {
        return $this->extractControllers($app);
    }

    private function extractControllers(Application $app)
    {
        $controllers = $app['controllers_factory'];

        // HEAD request for checking file upload status
        $controllers->head('/{resourceId}', function (Request $req, $resourceId) use ($app) {
            $fileStatus = $app[TusServiceProvider::GET_FILE_STATUS]($resourceId);

            if (!$fileStatus) {
                return new Response('Not Found', 404);
            }

            return new Response('', 200, ['Offset' => 1337])
        });

        return $controllers;
    }
}

<?php

namespace Vaffel\Tuski\Silex\Provider;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\ControllerProviderInterface;
use Silex\Application;

class TusControllerProvider implements ControllerProviderInterface
{
    public function setBaseRoute($baseRoute)
    {
        $this->baseRoute = $baseRoute;

        return $this;
    }

    public function connect(Application $app)
    {
        return $this->extractControllers($app);
    }

    private function extractControllers(Application $app)
    {
        $controllers = $app['controllers_factory'];

        // HEAD request for checking file upload status
        $controllers->match('/{resourceId}', function (Request $req, $resourceId) use ($app) {
            $fileStatus = $app[TusServiceProvider::GET_FILE_STATUS]($resourceId);

            if (!$fileStatus) {
                return new Response('Not Found', 404);
            }

            return new Response('', 200, ['Offset' => 1337]);
        }, 'HEAD');

        return $controllers;
    }
}

Use match instead of non-existant head routing method


<?php

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

namespace App\Http\Middleware;

class VerifyUserAlways extends VerifyUser
{
    public static function isRequired($user)
    {
        return $user !== null && ($user->isPrivileged() || $user->isInactive());
    }

    public function requiresVerification($request)
    {
        if ($this->user === null) {
            return false;
        }

        $method = $request->getMethod();
        $isPostAction = config('osu.user.post_action_verification')
            ? !in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)
            : false;

        $isRequired = $isPostAction || $method === 'DELETE' || session()->get('requires_verification');

        return $isRequired;
    }
}

<?php

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

namespace App\Http\Middleware;

class VerifyUserAlways extends VerifyUser
{
    const GET_ACTION_METHODS = [
        'GET' => true,
        'HEAD' => true,
        'OPTIONS' => true,
    ];

    public static function isRequired($user)
    {
        return $user !== null && ($user->isPrivileged() || $user->isInactive());
    }

    public function requiresVerification($request)
    {
        if ($this->user === null) {
            return false;
        }

        $method = $request->getMethod();
        $isPostAction = config('osu.user.post_action_verification')
            ? !isset(static::GET_ACTION_METHODS[$method])
            : false;

        $isRequired = $isPostAction || $method === 'DELETE' || session()->get('requires_verification');

        return $isRequired;
    }
}

Use array key lookup to check action method