<?php namespace Anomaly\Streams\Addon\FieldType\Datetime;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;
use Carbon\Carbon;

/**
 * Class DatetimeFieldTypePresenter
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\Streams\Addon\FieldType\Datetime
 */
class DatetimeFieldTypePresenter extends FieldTypePresenter
{

    /**
     * The carbon instance loaded with our value.
     *
     * @var \Carbon\Carbon
     */
    protected $carbon;

    /**
     * Create a new DatetimeFieldTypePresenter instance.
     *
     * @param $resource
     */
    public function __construct(DatetimeFieldType $resource)
    {
        $value = $resource->getValue();

        if ($value and !$resource->isZeros()) {

            $this->carbon = new Carbon($value);
        }

        parent::__construct($resource);
    }

    /**
     * Return the difference from now or
     * other in human readable format.
     *
     * @return null|string
     */
    public function diffForHumans($other = null)
    {
        if ($this->carbon instanceof Carbon) {

            return $this->carbon->diffForHumans($other);
        }

        return null;
    }

    /**
     * Return the value and difference from now
     * or other in human readable format.
     *
     * @param null $other
     * @return null|string
     */
    public function valueAndDiffForHumans($other = null)
    {
        if ($this->carbon instanceof Carbon) {

            $value = $this->resource->getValue();

            $diff = $this->carbon->diffForHumans($other);

            return "{$value} ({$diff})";
        }

        return null;
    }
}

<?php namespace Anomaly\Streams\Addon\FieldType\Datetime;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;
use Carbon\Carbon;

/**
 * Class DatetimeFieldTypePresenter
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\Streams\Addon\FieldType\Datetime
 */
class DatetimeFieldTypePresenter extends FieldTypePresenter
{

    /**
     * Return the difference from now or
     * other in human readable format.
     *
     * @return null|string
     */
    public function diffForHumans($other = null)
    {
        $value = $this->resource->getValue();

        if ($value instanceof Carbon) {

            return $value->diffForHumans($other);
        }

        return null;
    }

    /**
     * Return the value and difference from now
     * or other in human readable format.
     *
     * @param null $other
     * @return null|string
     */
    public function valueAndDiffForHumans($other = null)
    {
        $value = $this->resource->getValue();

        if ($value instanceof Carbon) {

            $diff = $value->diffForHumans($other);

            return "{$value} ({$diff})";
        }

        return null;
    }
}

Use the value directly cause it's carbon from the model


<?php

namespace App\Providers;

use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use Illuminate\Support\ServiceProvider;

class LastModifiedServiceProvider extends ServiceProvider
{
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('lastModified', function () {
            return $this->getLastModifiedDate();
        });
    }

    protected function getLastModifiedDate()
    {
        date_default_timezone_set(config('app.timezone'));

        $timeStamp = null;

        $directories = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->app->basePath()));

        foreach ($directories as $path => $object) {
            if (basename($path) !== '.ftpquota' &&
                basename($path) !== 'DO_NOT_UPLOAD_HERE' &&
                basename($path) !== 'tmp') {
                $timeStamp = filemtime($path) > $timeStamp ? filemtime($path) : $timeStamp;
            }
        }

        return date('F jS, Y', $timeStamp).' at '.date('h:i:s A T', $timeStamp);
    }
}

<?php

namespace App\Providers;

use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use Illuminate\Support\ServiceProvider;

class LastModifiedServiceProvider extends ServiceProvider
{
    /**
     * List of excluded directories when traversing application folders.
     *
     * @var array
     */
    private $excludedDirectories = [
        'vendor',
        'node_modules',
        'tmp',
        'storage',
        'tests',
        'cache',
    ];

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('lastModified', function () {
            return $this->getLastModifiedDate();
        });
    }

    /**
     * Function to get the last modified file time for the web application directory.
     *
     * @return string
     */
    protected function getLastModifiedDate()
    {
        date_default_timezone_set(config('app.timezone'));

        $timeStamp = null;

        $directories = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->app->basePath()));

        foreach ($directories as $path => $object) {
            if (! in_array(basename($path), $this->excludedDirectories, true)) {
                $timeStamp = filemtime($path) > $timeStamp ? filemtime($path) : $timeStamp;
            }
        }

        return date('F jS, Y', $timeStamp).' at '.date('h:i:s A T', $timeStamp);
    }
}

LatModifiedServiceProvider: Create an array of directories to exclude

when traversing the folder structure to get the last modified file time.


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => env('STORAGE_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path().'/app',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('S3_KEY'),
            'secret' => env('S3_SECRET'),
            'region' => 'us-east-1',
            'bucket' => env('S3_BUCKET'),
            'base_url' => 'https://s3-external-1.amazonaws.com',
            'public_url' => env('S3_URL'),
        ],
        ],

    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => env('STORAGE_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path().'/app',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('S3_KEY'),
            'secret' => env('S3_SECRET'),
            'region' => 'us-east-1',
            'bucket' => env('S3_BUCKET'),
        ],

    ],

];

Remove unused S3 config vars.

Remove unused S3 config vars.


<?php

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

namespace Symfony\Component\HttpKernel\CacheWarmer;

/**
 * Aggregates several cache warmers into a single one.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @final
 */
class CacheWarmerAggregate implements CacheWarmerInterface
{
    private $warmers;
    private $optionalsEnabled = false;

    public function __construct(iterable $warmers = array())
    {
        $this->warmers = $warmers;
    }

    public function enableOptionalWarmers()
    {
        $this->optionalsEnabled = true;
    }

    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        foreach ($this->warmers as $warmer) {
            if (!$this->optionalsEnabled && $warmer->isOptional()) {
                continue;
            }

            $warmer->warmUp($cacheDir);
        }
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * @return bool always false
     */
    public function isOptional()
    {
        return false;
    }
}

<?php

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

namespace Symfony\Component\HttpKernel\CacheWarmer;

/**
 * Aggregates several cache warmers into a single one.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @final
 */
class CacheWarmerAggregate implements CacheWarmerInterface
{
    private $warmers;
    private $optionalsEnabled = false;
    private $onlyOptionalsEnabled = false;

    public function __construct(iterable $warmers = array())
    {
        $this->warmers = $warmers;
    }

    public function enableOptionalWarmers()
    {
        $this->optionalsEnabled = true;
    }

    public function enableOnlyOptionalWarmers()
    {
        $this->onlyOptionalsEnabled = $this->optionalsEnabled = true;
    }

    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        foreach ($this->warmers as $warmer) {
            if (!$this->optionalsEnabled && $warmer->isOptional()) {
                continue;
            }
            if ($this->onlyOptionalsEnabled && !$warmer->isOptional()) {
                continue;
            }

            $warmer->warmUp($cacheDir);
        }
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * @return bool always false
     */
    public function isOptional()
    {
        return false;
    }
}

[FrameworkBundle] Remove double cache generation by detecting fresh kernels on cache:clear


<?php
namespace Passengers\Event;

use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;

class SignInEvent implements EventListenerInterface {

    public function implementedEvents()
    {
        return array(
	        'Controller.Users.beforeSignIn' => array(
                'callable' => 'beforeUsersControllerSignIn',
            ),
        );
    }

    public function beforeUsersControllerSignIn(Event $event)
    {
        $controller = $event->subject();
        $active = true;
        if($controller->request->is('post')){
            if($controller->request->data('username') || $controller->request->data('email')) {
                $active = $controller->Users->find('all', [
                    'conditions' => [
                        'Users.active' => true,
                        'OR' => [
                            'Users.email' => $controller->request->data('email'),
                            'Users.username' => $controller->request->data('username')
                        ]
                    ]
                ])->count();
            }
        }
        if(!$active){
            $event->stopPropagation();
            return __d('passengers', 'Sorry, but your account has been not activated yet.');
        }
    }

}

<?php
namespace Passengers\Event;

use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;

class SignInEvent implements EventListenerInterface {

    public function implementedEvents()
    {
        return array(
	        'Controller.Users.beforeSignIn' => array(
                'callable' => 'beforeUsersControllerSignIn',
            ),
        );
    }

    public function beforeUsersControllerSignIn(Event $event)
    {
        $controller = $event->subject();
        $active = true;
        if($controller->request->is('post')){
            $userName = '';
            if ($controller->request->data('username'))
                $userName = $controller->request->data('username');
            if ($controller->request->data('email'))
                $userName = $controller->request->data('email');
            if($userName) {
                $active = $controller->Users->find('all', [
                    'conditions' => [
                        'Users.active' => true,
                        'OR' => [
                            'Users.email' => $userName,
                            'Users.username' => $userName
                        ]
                    ]
                ])->count();
            }
        }
        if(!$active){
            $event->stopPropagation();
            return __d('passengers', 'Sorry, but your account has been not activated yet.');
        }
    }

}

Fix check user is active by email or username


<?php
declare(strict_types=1);

namespace WyriHaximus\Travis\Resource\Sync;

use WyriHaximus\ApiClient\Resource\CallAsyncTrait;
use WyriHaximus\Travis\Resource\Job as BaseJob;

class Job extends BaseJob
{
    /**
     * @return array
     */
    public function annotations(): array
    {
        return $this->wait($this->observableToPromise($this->callAsync('annotations')->toArray()));
    }
    use CallAsyncTrait;

    public function refresh(): Job
    {
        return $this->wait($this->callAsync('refresh'));
    }
}

<?php
declare(strict_types=1);

namespace WyriHaximus\Travis\Resource\Sync;

use WyriHaximus\ApiClient\Resource\CallAsyncTrait;
use WyriHaximus\Travis\Resource\Job as BaseJob;

class Job extends BaseJob
{
    use CallAsyncTrait;

    /**
     * @return array
     */
    public function annotations(): array
    {
        return $this->wait($this->observableToPromise($this->callAsync('annotations')->toArray()));
    }

    public function refresh(): Job
    {
        return $this->wait($this->callAsync('refresh'));
    }
}

Use trait at the top of a class

Use trait at the top of a class


<?php
class Susy_Kwc_TextImage_Layout extends Susy_Layout
{
    protected function _isSupportedContext($context)
    {
        if ($context['spans'] < 3) return false;
        return true;
    }

    public function getChildContexts(Kwf_Component_Data $data, Kwf_Component_Data $child)
    {
        $ownContexts = parent::getChildContexts($data, $child);

        if ($child->id == 'image') {
            if (!$data->getComponent()->getRow()->image) {
                return null;
            }

            $imageWidth = $data->getComponent()->getRow()->image_width;
            if (!$imageWidth) $imageWidth = 25;
            $widthCalc = 100/$imageWidth;
            $ret = array();
            $masterLayouts = Susy_Helper::getLayouts();
            foreach ($ownContexts as $context) {
                $breakpoint = $masterLayouts[$context['masterLayout']][$context['breakpoint']];
                //same logic in scss
                if (!isset($breakpoint['breakpoint']) || (int)$breakpoint['breakpoint'] * $context['spans'] / $breakpoint['columns'] < 300) {
                    //full width
                    $ret[] = $context;
                } else {
                    $context['spans'] = floor($context['spans'] * $widthCalc);
                    if ($context['spans'] < 1) {
                        $context['spans'] = 1;
                    }
                    $ret[] = $context;
                }
            }
            return $ret;
        } else {
            return $ownContexts;
        }
    }
}

<?php
class Susy_Kwc_TextImage_Layout extends Susy_Layout
{
    protected function _isSupportedContext($context)
    {
        if ($context['spans'] < 3) return false;
        return true;
    }

    public function getChildContexts(Kwf_Component_Data $data, Kwf_Component_Data $child)
    {
        $ownContexts = parent::getChildContexts($data, $child);

        if ($child->id == 'image') {
            if (!$data->getComponent()->getRow()->image) {
                return array();
            }

            $imageWidth = $data->getComponent()->getRow()->image_width;
            if (!$imageWidth) $imageWidth = 25;
            $widthCalc = 100/$imageWidth;
            $ret = array();
            $masterLayouts = Susy_Helper::getLayouts();
            foreach ($ownContexts as $context) {
                $breakpoint = $masterLayouts[$context['masterLayout']][$context['breakpoint']];
                //same logic in scss
                if (!isset($breakpoint['breakpoint']) || (int)$breakpoint['breakpoint'] * $context['spans'] / $breakpoint['columns'] < 300) {
                    //full width
                    $ret[] = $context;
                } else {
                    $context['spans'] = floor($context['spans'] * $widthCalc);
                    if ($context['spans'] < 1) {
                        $context['spans'] = 1;
                    }
                    $ret[] = $context;
                }
            }
            return $ret;
        } else {
            return $ownContexts;
        }
    }
}

Return array instead of null because return value is evaluated in foreach


<?php

namespace App\Api\Controllers\Auth;

use Validator;
use Illuminate\Http\Request;
use App\Api\Controllers\ApiController;

class LoginController extends ApiController
{
    /**
     * Get a validator for an incoming login request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
    }

    /**
     * Check a users credentials and log them in.
     *
     * @param  array  $data
     * @return response
     */
    protected function login(Request $request)
    {
        $validator = $this->validator($request->input('data.attributes'));

        if ($validator->fails()) {
            $response = $this->apiErrorResponse($validator->errors());

            return $response;
        }

        try {
            if (!$token = \JWTAuth::attempt($request->input('data.attributes'))) {
                $response = $this->apiErrorResponse('Invalid credentials');

                return $response;
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'], 500);
        }

        $response = $this->apiResponse($token);

        return $response;
    }
}

<?php

namespace App\Api\Controllers\Auth;

use Validator;
use Illuminate\Http\Request;
use App\Api\Controllers\ApiController;

class LoginController extends ApiController
{
    /**
     * Get a validator for an incoming login request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
    }

    /**
     * Check a users credentials and log them in.
     *
     * @param  array  $data
     * @return response
     */
    protected function login(Request $request)
    {
        $validator = $this->validator($request->input('data.attributes'));

        if ($validator->fails()) {
            $response = $this->apiErrorResponse($validator->errors());

            return $response;
        }

        try {
            if (!$token = \JWTAuth::attempt($request->input('data.attributes'))) {
                $response = $this->apiErrorResponse('Invalid credentials');

                return $response;
            }
        } catch (JWTException $e) {
            return $this->apiErrorResponse($e->getMessage());
        }

        $response = $this->apiResponse($token);

        return $response;
    }
}

Add apiErrorResponse to caught errors during login


<?php

namespace Becklyn\AssetsBundle\Command;

use Becklyn\AssetsBundle\Cache\CacheWarmer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class AssetsCacheCommand extends Command
{
    /**
     * @var CacheWarmer
     */
    private $cacheWarmer;

    /**
     * @param CacheWarmer $cacheWarmer
     */
    public function __construct (CacheWarmer $cacheWarmer)
    {
        $this->cacheWarmer = $cacheWarmer;
        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure ()
    {
        $this
            ->setDescription("Resets (clears and warms) the assets cache")
            ->addOption(
                "no-warmup",
                null,
                InputOption::VALUE_OPTIONAL,
                "Should be cache be automatically warmed up?",
                false
            );
    }

    /**
     * @inheritdoc
     */
    protected function execute (InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        $io->title("Becklyn Assets: Reset");
        $this->cacheWarmer->clearCache($io);

        if (!$input->getOption("no-warmup"))
        {
            $this->cacheWarmer->fillCache($io);
        }

        $io->success("finished");
    }
}

<?php

namespace Becklyn\AssetsBundle\Command;

use Becklyn\AssetsBundle\Cache\CacheWarmer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class AssetsCacheCommand extends Command
{
    public static $defaultName = "becklyn:assets:reset";

    /**
     * @var CacheWarmer
     */
    private $cacheWarmer;

    /**
     * @param CacheWarmer $cacheWarmer
     */
    public function __construct (CacheWarmer $cacheWarmer)
    {
        $this->cacheWarmer = $cacheWarmer;
        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure ()
    {
        $this
            ->setName(self::$defaultName)
            ->setDescription("Resets (clears and warms) the assets cache")
            ->addOption(
                "no-warmup",
                null,
                InputOption::VALUE_OPTIONAL,
                "Should be cache be automatically warmed up?",
                false
            );
    }

    /**
     * @inheritdoc
     */
    protected function execute (InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        $io->title("Becklyn Assets: Reset");
        $this->cacheWarmer->clearCache($io);

        if (!$input->getOption("no-warmup"))
        {
            $this->cacheWarmer->fillCache($io);
        }

        $io->success("finished");
    }
}

Set name explicitly in the command itself, too


<?php

namespace SocialiteProviders\Manager;

use SocialiteProviders\Manager\Contracts\ConfigInterface;

trait ConfigTrait
{
    /**
     * @var array
     */
    protected $config;

    /**
     * @param \SocialiteProviders\Manager\Contracts\OAuth1\ProviderInterface|\SocialiteProviders\Manager\Contracts\OAuth2\ProviderInterface $config
     */
    public function setConfig(ConfigInterface $config)
    {
        $config = $config->get();

        $this->config = $config;
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->redirectUrl = $config['redirect'];

        return $this;
    }

    /**
     * @return array
     */
    public static function additionalConfigKeys()
    {
        return [];
    }

    /**
     * @param string $key
     * @param mixed  $default
     *
     * @return mixed|array
     */
    protected function getConfig($key = null, $default = null)
    {
        // check manually if a key is given and if it exists in the config
        // this has to be done to check for spoofed additional config keys so that null isn't returned
        if (!empty($key) && empty($this->config[$key])) {
            return $default;
        }

        return $key ? array_get($this->config, $key, $default) : $this->config;
    }
}

<?php

namespace SocialiteProviders\Manager;

use Illuminate\Support\Arr;
use SocialiteProviders\Manager\Contracts\ConfigInterface;

trait ConfigTrait
{
    /**
     * @var array
     */
    protected $config;

    /**
     * @param \SocialiteProviders\Manager\Contracts\OAuth1\ProviderInterface|\SocialiteProviders\Manager\Contracts\OAuth2\ProviderInterface $config
     */
    public function setConfig(ConfigInterface $config)
    {
        $config = $config->get();

        $this->config = $config;
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->redirectUrl = $config['redirect'];

        return $this;
    }

    /**
     * @return array
     */
    public static function additionalConfigKeys()
    {
        return [];
    }

    /**
     * @param string $key
     * @param mixed  $default
     *
     * @return mixed|array
     */
    protected function getConfig($key = null, $default = null)
    {
        // check manually if a key is given and if it exists in the config
        // this has to be done to check for spoofed additional config keys so that null isn't returned
        if (!empty($key) && empty($this->config[$key])) {
            return $default;
        }

        return $key ? Arr::get($this->config, $key, $default) : $this->config;
    }
}

Replace depricated array helper method

Replace depricated array helper method


<?php
/**
 * @package CRC_Contact_Fields
 * @version 0.9
 */

/**
 * Plugin Name: CRC Contact Fields
 * Plugin URI: https://github.com/robo-crc/wp-crc-contact-fields
 * Description: Adds additional contact fields relevant to CRC's WordPress site
 * Author: Michael Sanford
 * Version: 0.9
 * Author URI: http://michaelsanford.com
 */

/**
 * @param array $user_contact
 * @return array
 */
function modify_user_contact_methods($user_contact) {

	/* Add school */
	$user_contact['school'] = __('School');

	return $user_contact;
}

/**
 * Hook
 */
add_filter('user_contactmethods', 'modify_user_contact_methods');

<?php
/**
 * @package CRC_Contact_Fields
 * @version 0.9
 */

/**
 * Plugin Name: CRC Contact Fields
 * Plugin URI: https://github.com/robo-crc/crc-contact-fields
 * Description: Adds additional contact fields relevant to CRC's WordPress site
 * Author: Michael Sanford
 * Version: 0.9
 * Author URI: http://michaelsanford.com
 */

/**
 * @param array $user_contact
 * @return array
 */
function modify_user_contact_methods($user_contact) {

	/* Add school */
	$user_contact['school'] = __('School');

	return $user_contact;
}

/**
 * Hook
 */
add_filter('user_contactmethods', 'modify_user_contact_methods');

Update plugin link in details comments

Update plugin link in details comments


<?php
/*
 * Use this file to add ability to get your test to use your application code
 */

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

require_once "MultiLoader.php";

/**
 * Register for the SPL autoload
 *
 * Simple wrapper function to simplify autoloading
 * of multiple directories.
 *
 *
 * @param string $class
 *
 * @return void
 */
function multiAutoload($class)
{
	$srcPath = __DIR__ . '/src';

    $loader = new MultiLoader();
    $loader->loadSrcDirectory($class, $srcPath, 'Awoods/World');
}

spl_autoload_register('multiAutoload');

<?php
/*
 * Use this file to add ability to get your test to use your application code
 */

require_once 'vendor/autoload.php';

/**
 * Register for the SPL autoload
 *
 * Simple wrapper function to simplify autoloading
 * of multiple directories.
 *
 *
 * @param string $class
 *
 * @return void
 */
function multiAutoload($class)
{
	$srcPath = __DIR__ . '/src';

    $loader = new MultiLoader();
    $loader->loadSrcDirectory($class, $srcPath, 'Awoods/World');
}

Use composer's autoloader instead of mine


<?php

namespace SSilence\ImapClient;

class TypeAttachments
{
    public $types;

    public function __construct()
    {
        $this->types = ['JPEG', 'PNG', 'PDF', 'X-MPEG', 'MSWORD', 'OCTET-STREAM'];
    }

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

}

<?php

namespace SSilence\ImapClient;

class TypeAttachments
{
    public $types;

    public function __construct()
    {
        $this->types = ['JPEG', 'PNG', 'GIF', 'PDF', 'X-MPEG', 'MSWORD', 'OCTET-STREAM'];
    }

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

}

Add type attachments like gif

Add type attachments like gif


<?php

/*
* (c) Andreas Fischer <bantu@owncloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

/**
* Tests math related to large file sizes.
*/
class MathTest extends PHPUnit_Framework_TestCase
{
    public function testLargeFloatStringWithoutWorkaround()
    {
        $this->assertSame('4503599627370496', (string) pow(2, 52));
    }

    public function testLargeFloatStringWithWorkaround()
    {
        $this->assertSame('4503599627370496', format_bytes(pow(2, 52)));
    }
}

<?php

/*
* (c) Andreas Fischer <bantu@owncloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

/**
* Tests math related to large file sizes.
*/
class MathTest extends PHPUnit_Framework_TestCase
{
    public function testFloatEqualityComparison()
    {
        $this->assertSame(4503599627370496, pow(2, 52));
    }

    public function testNumberCasting()
    {
        $this->assertSame(4503599627370496, 0 + '4503599627370496');
    }

    public function testLargeFloatStringWithoutWorkaround()
    {
        $this->assertSame('4503599627370496', (string) pow(2, 52));
    }

    public function testLargeFloatStringWithWorkaround()
    {
        $this->assertSame('4503599627370496', format_bytes(pow(2, 52)));
    }
}

Add tests for number casting and float comparison.


<?php
namespace Nubs\RandomNameGenerator;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass \Nubs\RandomNameGenerator\Vgng
 * @covers ::<protected>
 */
class VgngTest extends PHPUnit_Framework_TestCase
{
    /**
     * Verify that getName returns the expected name.
     *
     * @test
     * @covers ::__construct
     * @covers ::getName
     */
    public function getName()
    {
        $vgng = new Vgng();

        srand(1);
        $this->assertSame("Jackie Chan's Penguin Anthology", $vgng->getName());
    }
}

<?php
namespace Nubs\RandomNameGenerator;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass \Nubs\RandomNameGenerator\Vgng
 * @covers ::<protected>
 */
class VgngTest extends PHPUnit_Framework_TestCase
{
    /**
     * Verify that getName returns the expected name.
     *
     * @test
     * @covers ::__construct
     * @covers ::getName
     */
    public function getNameBasic()
    {
        $vgng = new Vgng();

        srand(1);
        $this->assertSame("Jackie Chan's Penguin Anthology", $vgng->getName());
    }
}

Fix name of test so it doesn't conflict with PHPUnit.


<?php

require_once('../../../www/_include.php');

$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();

SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');

if (!$config->getValue('enable.saml20-idp', false)) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}

if (!isset($_GET['RelayState'])) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

$returnTo = $_GET['RelayState'];

/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'saml2/idp/SingleLogoutService.php',
	array('ReturnTo' => $returnTo));

?>

<?php

require_once('../../../www/_include.php');

$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();

SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');

if (!$config->getValue('enable.saml20-idp', false)) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}

if (!isset($_GET['RelayState'])) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

$returnTo = $_GET['RelayState'];

$slo = $metadata->getGenerated('SingleLogoutService', 'saml20-idp-hosted');

/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect($slo, array('ReturnTo' => $returnTo));

?>

SAML2: Support metadata overrides of SingleLogoutService for IdP initiated SLO.

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


<?php namespace Jigsaw\Jigsaw\Console;

use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class InitCommand extends Command
{
    private $files;
    private $base;

    public function __construct(Filesystem $files)
    {
        $this->files = $files;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('init')
            ->setDescription('Scaffold a new Jigsaw project.')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Where should we initialize this project?'
            );
    }

    protected function fire()
    {
        if ($base = $this->input->getArgument('name')) {
            $this->base = getcwd() . '/' . $base;
            $this->createBaseDirectory();
        }
        $this->createSourceFolder();
        $this->createBaseConfig();
        $this->info('Site initialized successfully!');
    }

    private function createBaseDirectory()
    {
        if (! $this->files->isDirectory($this->base)) {
            $this->files->makeDirectory($this->base);
        }
    }

    private function createSourceFolder()
    {
        $this->files->makeDirectory($this->base . '/source');
    }

    private function createBaseConfig()
    {
        $this->files->put($this->base . '/config.php', <<<EOT
<?php

return [
    'production' = false,
];
EOT
        );
    }
}

<?php namespace Jigsaw\Jigsaw\Console;

use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class InitCommand extends Command
{
    private $files;
    private $base;

    public function __construct(Filesystem $files)
    {
        $this->files = $files;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('init')
            ->setDescription('Scaffold a new Jigsaw project.')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Where should we initialize this project?'
            );
    }

    protected function fire()
    {
        if ($base = $this->input->getArgument('name')) {
            $this->base = getcwd() . '/' . $base;
            $this->createBaseDirectory();
        }
        $this->createSourceFolder();
        $this->createBaseConfig();
        $this->info('Site initialized successfully!');
    }

    private function createBaseDirectory()
    {
        if (! $this->files->isDirectory($this->base)) {
            $this->files->makeDirectory($this->base);
        }
    }

    private function createSourceFolder()
    {
        $this->files->makeDirectory($this->base . '/source');
    }

    private function createBaseConfig()
    {
        $this->files->put($this->base . '/config.php', <<<EOT
<?php

return [
    'production' => false,
];
EOT
        );
    }
}

Fix broken default config file

Fix broken default config file


<?php

namespace Concrete\Core\Authentication;

use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerAwareInterface;
use Concrete\Core\Logging\LoggerAwareTrait;
use Concrete\Core\User\User;
use Page;
use Controller;
use Concrete\Core\Support\Facade\Application;

abstract class AuthenticationTypeController extends Controller implements LoggerAwareInterface,
    AuthenticationTypeControllerInterface
{
    protected $authenticationType;
    protected $app;

    use LoggerAwareTrait;

    public function getLoggerChannel()
    {
        return Channels::CHANNEL_AUTHENTICATION;
    }

    abstract public function getAuthenticationTypeIconHTML();

    abstract public function view();

    /**
     * @param AuthenticationType $type This type may be null only for access points that do not rely on the type.
     */
    public function __construct(AuthenticationType $type = null)
    {
        $this->authenticationType = $type;
        $this->app = Application::getFacadeApplication();
    }

    public function getAuthenticationType()
    {
        if (!$this->authenticationType) {
            $this->authenticationType = AuthenticationType::getByHandle($this->getHandle());
        }

        return $this->authenticationType;
    }

    public function completeAuthentication(User $u)
    {
        $c = Page::getByPath('/login');
        $controller = $c->getPageController();
        return $controller->finishAuthentication($this->getAuthenticationType(), $u);
    }

    /**
     * @return string
     */
    abstract public function getHandle();
}

<?php

namespace Concrete\Core\Authentication;

use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerAwareInterface;
use Concrete\Core\Logging\LoggerAwareTrait;
use Concrete\Core\User\User;
use Page;
use Controller;
use Concrete\Core\Support\Facade\Application;

abstract class AuthenticationTypeController extends Controller implements LoggerAwareInterface,
    AuthenticationTypeControllerInterface
{
    protected $authenticationType;
    protected $app;

    use LoggerAwareTrait;

    public function getLoggerChannel()
    {
        return Channels::CHANNEL_AUTHENTICATION;
    }

    abstract public function getAuthenticationTypeIconHTML();

    abstract public function view();

    /**
     * @param AuthenticationType $type This type may be null only for access points that do not rely on the type.
     */
    public function __construct(AuthenticationType $type = null)
    {
        $this->authenticationType = $type;
        $this->app = Application::getFacadeApplication();
    }

    public function getAuthenticationType()
    {
        if (!$this->authenticationType || !$this->authenticationType->getAuthenticationTypeID()) {
            $this->authenticationType = AuthenticationType::getByHandle($this->getHandle());
        }

        return $this->authenticationType;
    }

    public function completeAuthentication(User $u)
    {
        $c = Page::getByPath('/login');
        $controller = $c->getPageController();
        return $controller->finishAuthentication($this->getAuthenticationType(), $u);
    }

    /**
     * @return string
     */
    abstract public function getHandle();
}

Fix get authentication type failed

Fix get authentication type failed


<?php

return [
    'production' => true,
    'twitter' => '@laravelbrussels',
    'meetup_url' => '//meetup.com/Laravel-Brussels',
    'other_organisations' => [
        'PHP Antwerp' => '//www.meetup.com/phpantwerp',
        'PHP Brussels' => '//www.meetup.com/BrusselsPHP',
        'PHP Gent' => '//www.meetup.com/phpgent',
        'PHP Leuven' => '//www.meetup.com/PHP-Leuven-Web-Innovation-Group',
        'PHP Limburg (BE)' => '//www.meetup.com/PHP-Limburg-BE',
        'Laracon EU' => '//laracon.eu',
        ],
];

<?php

return [
    'production' => true,
    'twitter' => '@laravelbrussels',
    'meetup_url' => '//meetup.com/Laravel-Brussels',
    'other_organisations' => [
        'PHP Antwerp' => '//www.meetup.com/phpantwerp',
        'PHP Benelux' => '//www.phpbenelux.eu',
        'PHP Brussels' => '//www.meetup.com/BrusselsPHP',
        'PHP Gent' => '//www.meetup.com/phpgent',
        'PHP Leuven' => '//www.meetup.com/PHP-Leuven-Web-Innovation-Group',
        'PHP Limburg (BE)' => '//www.meetup.com/PHP-Limburg-BE',
        'Laracon EU' => '//laracon.eu',
        ],
];

Add PHP Benelux to other organisations

Add PHP Benelux to other organisations


<?php declare(strict_types = 1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (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 SebastianBergmann\CodeCoverage\Report\Xml;

use TheSeer\Tokenizer\NamespaceUri;
use TheSeer\Tokenizer\Tokenizer;
use TheSeer\Tokenizer\XMLSerializer;

class Source
{
    /** @var \DOMElement */
    private $context;

    /**
     * @param \DOMElement $context
     */
    public function __construct(\DOMElement $context)
    {
        $this->context = $context;
    }

    /**
     * @param string $source
     */
    public function setSourceCode($source)
    {
        $context = $this->context;

        $tokens = (new Tokenizer())->parse($source);
        $srcDom = (new XMLSerializer(new NamespaceUri($context->namespaceURI)))->toDom($tokens);

        $context->parentNode->replaceChild(
            $context->ownerDocument->importNode($srcDom->documentElement, true),
            $context
        );
    }
}

<?php
/*
 * This file is part of the php-code-coverage package.
 *
 * (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 SebastianBergmann\CodeCoverage\Report\Xml;

use TheSeer\Tokenizer\NamespaceUri;
use TheSeer\Tokenizer\Tokenizer;
use TheSeer\Tokenizer\XMLSerializer;

class Source
{
    /** @var \DOMElement */
    private $context;

    /**
     * @param \DOMElement $context
     */
    public function __construct(\DOMElement $context)
    {
        $this->context = $context;
    }

    /**
     * @param string $source
     */
    public function setSourceCode($source)
    {
        $context = $this->context;

        $tokens = (new Tokenizer())->parse($source);
        $srcDom = (new XMLSerializer(new NamespaceUri($context->namespaceURI)))->toDom($tokens);

        $context->parentNode->replaceChild(
            $context->ownerDocument->importNode($srcDom->documentElement, true),
            $context
        );
    }
}

Remove declare strict to be consistent with rest of code base


<?php namespace Flarum\Core\Handlers\Events;

use Illuminate\Mail\Mailer;
use Flarum\Core\Events\UserWasRegistered;
use Flarum\Core\Events\EmailWasChanged;
use Config;
use Illuminate\Contracts\Events\Dispatcher;

class EmailConfirmationMailer
{
    protected $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param \Illuminate\Contracts\Events\Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen('Flarum\Core\Events\UserWasRegistered', __CLASS__.'@whenUserWasRegistered');
        $events->listen('Flarum\Core\Events\EmailWasChanged', __CLASS__.'@whenEmailWasChanged');
    }

    public function whenUserWasRegistered(UserWasRegistered $event)
    {
        $user = $event->user;

        $forumTitle = Config::get('flarum::forum_title');

        $data = [
            'username' => $user->username,
            'forumTitle' => $forumTitle,
            'url' => route('flarum.forum.confirm', ['id' => $user->id, 'token' => $user->confirmation_token])
        ];

        $this->mailer->send(['text' => 'flarum::emails.confirm'], $data, function ($message) use ($user) {
            $message->to($user->email);
            $message->subject('Email Address Confirmation');
        });
    }

    public function whenEmailWasChanged(EmailWasChanged $event)
    {
    }
}

<?php namespace Flarum\Core\Handlers\Events;

use Illuminate\Mail\Mailer;
use Flarum\Core\Events\UserWasRegistered;
use Flarum\Core\Events\EmailWasChanged;
use Config;
use Illuminate\Contracts\Events\Dispatcher;

class EmailConfirmationMailer
{
    protected $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param \Illuminate\Contracts\Events\Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen('Flarum\Core\Events\UserWasRegistered', __CLASS__.'@whenUserWasRegistered');
        $events->listen('Flarum\Core\Events\EmailWasChanged', __CLASS__.'@whenEmailWasChanged');
    }

    public function whenUserWasRegistered(UserWasRegistered $event)
    {
        $user = $event->user;

        $forumTitle = Config::get('flarum::forum_title');

        $data = [
            'username' => $user->username,
            'forumTitle' => $forumTitle,
            'url' => route('flarum.forum.confirm', ['id' => $user->id, 'token' => $user->confirmation_token])
        ];

        $this->mailer->send(['text' => 'flarum::emails.confirm'], $data, function ($message) use ($user) {
            $message->to($user->email);
            $message->subject('Confirm Your Email Address');
        });
    }

    public function whenEmailWasChanged(EmailWasChanged $event)
    {
    }
}

Update email address confirmation subject


<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 12.02.16
 * Time: 21:13
 */

namespace CoreBundle\Model\Request\Game;

use CoreBundle\Model\Request\SecurityRequestAwareTrait;
use CoreBundle\Model\Request\SecurityRequestInterface;
use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class GameGetRequest
 * @package CoreBundle\Model\Request\Game
 */
class GameGetRequest extends GameRequest implements SecurityRequestInterface
{
    use SecurityRequestAwareTrait;

    /**
     * @var int
     *
     * @JMS\Type("integer")
     */
    private $id;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     * @return GameGetRequest
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 12.02.16
 * Time: 21:13
 */

namespace CoreBundle\Model\Request\Game;

use CoreBundle\Model\Request\SecurityRequestAwareTrait;
use CoreBundle\Model\Request\SecurityRequestInterface;
use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class GameGetRequest
 * @package CoreBundle\Model\Request\Game
 */
class GameGetRequest extends GameRequest implements SecurityRequestInterface
{
    use SecurityRequestAwareTrait;

    /**
     * @var int
     *
     * @JMS\Type("integer")
     */
    private $id;

    /**
     * @var string
     *
     * @JMS\Expose
     * @JMS\Type("string")
     */
    protected $login;

    /**
     * @var string
     *
     * @JMS\Expose
     * @JMS\Type("string")
     */
    protected $token;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     * @return GameGetRequest
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }
}

Fix for observing game by guest.

fix(backend): Fix for observing game by guest.


<?php

namespace MageTest\PHPSpec2\MagentoExtension;

use PHPSpec2\Extension\ExtensionInterface,
    PHPSpec2\Console\ExtendableApplicationInterface as ApplicationInterface,
    PHPSpec2\Configuration\Configuration;

use MageTest\PHPSpec2\MagentoExtension\Loader\SpecificationClassLoader;
use PHPSpec2\ServiceContainer;

class Extension implements ExtensionInterface
{
    private $application;
    private $configuration;

    public function initialize(ServiceContainer $container)
    {
        $container->set('specifications_loader', $container->share(function($c) {
            return new SpecificationClassLoader;
        }));
    }
}

<?php

namespace MageTest\PHPSpec2\MagentoExtension;

use PHPSpec2\Extension\ExtensionInterface,
    PHPSpec2\Console\ExtendableApplicationInterface as ApplicationInterface,
    PHPSpec2\Configuration\Configuration;

use MageTest\PHPSpec2\MagentoExtension\Loader\SpecificationClassLoader;
use PHPSpec2\ServiceContainer;

class Extension implements ExtensionInterface
{
    private $application;

    public function initialize(ServiceContainer $container)
    {
        $container->set('specifications_loader', $container->share(function($c) {
            return new SpecificationClassLoader;
        }));
    }
}

Remove config from extension. It is included in container


<?php

class Denkmal_Scraper_DescriptionTest extends CMTest_TestCase {

	public function testGetDescriptionAndGenres() {
		$description = new Denkmal_Scraper_Description('foo bar');

		$this->assertSame('Foo bar', $description->getDescriptionAndGenres());
	}
}

<?php

class Denkmal_Scraper_DescriptionTest extends CMTest_TestCase {

	public function testGetDescriptionAndGenres() {
		$description = new Denkmal_Scraper_Description('foo bar');

		$this->assertSame('Foo bar', $description->getDescriptionAndGenres());
	}

	public function testGetDescriptionAndGenresWithGenres() {
		$genres = new Denkmal_Scraper_Genres('rock, rap');
		$description = new Denkmal_Scraper_Description('foo bar', null, $genres);

		$this->assertSame('Foo bar. Rock, rap', $description->getDescriptionAndGenres());
	}
}

Add test for description scraper with genres


<?php

class m170831_100900_add_system_setting_disable_correspondence_notes_copy extends CDbMigration
{
    public function up()
    {
        $this->insert('setting_metadata', array(
            'display_order' => 0,
            'field_type_id' => 3,
            'key' => 'disable_correspondence_notes_copy',
            'name' => 'Require Dose/Freq for systemic meds',
            'data' => serialize(array('on'=>'On', 'off'=>'Off')),
            'default_value' => 'on'
        ));

        $this->insert('setting_installation', array(
            'key' => 'disable_correspondence_notes_copy',
            'value' => 'on'
        ));
    }

    public function down()
    {
        $this->delete('setting_installation', '`key`="disable_correspondence_notes_copy"');
        $this->delete('setting_metadata', '`key`="disable_correspondence_notes_copy"');
    }
}

<?php

class m170831_100900_add_system_setting_disable_correspondence_notes_copy extends CDbMigration
{
    public function up()
    {
        $this->insert('setting_metadata', array(
            'display_order' => 0,
            'field_type_id' => 3,
            'key' => 'disable_correspondence_notes_copy',
            'name' => 'Disable copy for notes in correspondence',
            'data' => serialize(array('on'=>'On', 'off'=>'Off')),
            'default_value' => 'on'
        ));

        $this->insert('setting_installation', array(
            'key' => 'disable_correspondence_notes_copy',
            'value' => 'on'
        ));
    }

    public function down()
    {
        $this->delete('setting_installation', '`key`="disable_correspondence_notes_copy"');
        $this->delete('setting_metadata', '`key`="disable_correspondence_notes_copy"');
    }
}

Fix duplicate Require Dose/Freq for systemic meds setting


<?php

namespace Kunstmaan\FormBundle\Tests\DependencyInjection;

use Kunstmaan\FormBundle\DependencyInjection\Configuration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class ConfigurationTest
 */
class ConfigurationTest extends TestCase
{
    public function testConfiguration()
    {
        $object = new Configuration();
        $tree = $object->getConfigTreeBuilder();

        $this->assertInstanceOf(TreeBuilder::class, $tree);

        $node = $tree->root('hosts');
        $this->assertInstanceOf(ArrayNodeDefinition::class, $node);
    }
}

<?php

namespace Kunstmaan\FormBundle\Tests\DependencyInjection;

use Kunstmaan\FormBundle\DependencyInjection\Configuration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class ConfigurationTest
 */
class ConfigurationTest extends TestCase
{
    public function testConfiguration()
    {
        $object = new Configuration();
        $tree = $object->getConfigTreeBuilder();

        $this->assertInstanceOf(TreeBuilder::class, $tree);

        if (method_exists($tree, 'getRootNode')) {
            $node = $tree->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $node = $tree->root('kunstmaan_form');
        }
        $this->assertInstanceOf(ArrayNodeDefinition::class, $node);
    }
}

[FormBundle] Use the root method on the configuration class is deprecated


<?php

namespace Zend\Console;

use Zend\Stdlib\Message;
use Zend\Stdlib\ResponseInterface;

class Response extends Message implements ResponseInterface
{
}

<?php

namespace Zend\Console;

use Zend\Stdlib\Message;
use Zend\Stdlib\ResponseInterface;

class Response extends Message implements ResponseInterface
{
    protected $contentSent = false;

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

    /**
     * Set the error level that will be returned to shell.
     *
     * @param integer   $errorLevel
     * @return Response
     */
    public function setErrorLevel($errorLevel){
        $this->setMetadata('errorLevel', $errorLevel);
        return $this;
    }

    /**
     * Get response error level that will be returned to shell.
     *
     * @return integer|0
     */
    public function getErrorLevel(){
        return $this->getMetadata('errorLevel', 0);
    }

    public function sendContent()
    {
        if ($this->contentSent()) {
            return $this;
        }
        echo $this->getContent();
        $this->contentSent = true;
        return $this;
    }

    public function send()
    {
        $this->sendContent();
        $errorLevel = (int)$this->getMetadata('errorLevel',0);
        exit($errorLevel);
    }
}

[WIP] Introduce Console rendering strategies and more incremental changes.

- Console\Response now supports setting and getting errorLevel (stored as metadata).
- Console\Response now properly supports send()ing, including exiting the application with an error level.
- Add Mvc\View\Console\DefaultRenderingStrategy for building console response from plain-text action controller
responses.
- Currently, the default console rendering strategy does NOT use Zend\View nor Rendering to produce responses (it
just concatenates plain-text responses from controllers and puts them into console response object)
- Remove View\Strategy\ConsoleStrategy because of its bad design.


<?php

return array(

    'table'    => '',

    'instance' => 'Algorit\Synchronizer\Storage\SyncInterface',

    'create'   => function($system, $resource, $entity, $type)
    {
        $company_id 	   = null;
        $representative_id = null;

        // Not the best code in the world.
        $class = explode('\\', get_class($this->resource));

        switch(end($class))
        {
            case 'Erp':
                $erp_id = $resource->id;
            break;
            case 'Company':
                $company_id = $resource->id;
                $erp_id 	= $resource->erp->id;
            break;
            case 'Representative':
                $representative_id = $resource->id;
                $company_id 	   = $resource->company->id;
                $erp_id 		   = $resource->company->erp->id;
            break;
        }

        return array(
            'erp_id' 			=> $erp_id,
            'company_id' 		=> $company_id,
            'representative_id' => $representative_id,
            'entity' 			=> $entity,
            'type' 				=> $type,
            'class' 			=> get_class($system),
            'status' 			=> 'processing',
        );
    },
);

<?php

return array(

    'table'    => '',

    'instance' => '',

    'create'   => function($system, $resource, $entity, $type)
    {
        $company_id 	   = null;
        $representative_id = null;

        // Not the best code in the world.
        $class = explode('\\', get_class($this->resource));

        switch(end($class))
        {
            case 'Erp':
                $erp_id = $resource->id;
            break;
            case 'Company':
                $company_id = $resource->id;
                $erp_id 	= $resource->erp->id;
            break;
            case 'Representative':
                $representative_id = $resource->id;
                $company_id 	   = $resource->company->id;
                $erp_id 		   = $resource->company->erp->id;
            break;
        }

        return array(
            'erp_id' 			=> $erp_id,
            'company_id' 		=> $company_id,
            'representative_id' => $representative_id,
            'entity' 			=> $entity,
            'type' 				=> $type,
            'class' 			=> get_class($system),
            'status' 			=> 'processing',
        );
    },
);

Set instance config null by default

Set instance config null by default


<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms
{
    private $manager;

    /**
     * TraitsOfOrganisms constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @param 'fennec_ids' => [13,7,12,5]
     * @returns array $result
     * <code>
     * array(type_cvterm_id => array(
     * 'trait_type' => 'habitat',
     * 'trait_entry_ids' => array(1, 20, 36, 7),
     * 'fennec_ids' => array(13, 20, 5)
     * );
     * </code>
     */
    public function execute($fennec_ids)
    {
        if(isset($_REQUEST['fennec_ids'])){
            $fennec_ids = $_REQUEST['fennec_ids'];
        }
        return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
    }
}

<?php

namespace AppBundle\API\Details;

use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms
{
    private $manager;

    /**
     * TraitsOfOrganisms constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @param 'fennec_ids' => [13,7,12,5]
     * @returns array $result
     * <code>
     * array(type_cvterm_id => array(
     * 'trait_type' => 'habitat',
     * 'trait_entry_ids' => array(1, 20, 36, 7),
     * 'fennec_ids' => array(13, 20, 5)
     * );
     * </code>
     */
    public function execute($fennec_ids)
    {
        return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
    }
}

Remove unused statement for setting fennecIds in service


<?php
/**
 * Test database configuration.
 */
return [
    'default-connection' => 'travis',
    'connections' => [
        'travis' => [
            'driver' => 'c5_pdo_mysql',
            'server' => 'localhost',
            'database' => 'concrete5_tests',
            'username' => 'travis',
            'password' => '',
            'charset' => 'utf8',
            'driverOptions' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'",
            ],
        ],
        'travisWithoutDB' => [
            'driver' => 'c5_pdo_mysql',
            'server' => 'localhost',
            'username' => 'travis',
            'password' => '',
            'charset' => 'utf8',
            'driverOptions' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'",
            ],
        ],
    ],
];

<?php
/**
 * Test database configuration.
 */
return [
    'default-connection' => 'travis',
    'connections' => [
        'travis' => [
            'driver' => 'c5_pdo_mysql',
            'server' => '127.0.0.1',
            'database' => 'concrete5_tests',
            'username' => 'travis',
            'password' => '',
            'charset' => 'utf8',
            'driverOptions' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'",
            ],
        ],
        'travisWithoutDB' => [
            'driver' => 'c5_pdo_mysql',
            'server' => '127.0.0.1',
            'username' => 'travis',
            'password' => '',
            'charset' => 'utf8',
            'driverOptions' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'",
            ],
        ],
    ],
];

Use 127.0.0.1 instead of localhost in test DB connection

Using localhost prevents from running tests in WSL


<?php

namespace Busayo\Mention;

use Busayo\Mention\Factory\MentionBuilder;
use Illuminate\Support\ServiceProvider;

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

    public function boot()
    {
        $this->setup(__DIR__)
             ->publishConfig()
             ->publishViews()
             ->publishAssets()
             ->loadViews()
             ->loadRoutes()
             ->mergeConfig('mentions');
    }

    /**
     * Register the application services
     * @return void
     */
    public function register()
    {
         $this->app->singleton('mentionBuilder', function ($app) {
            $form = new MentionBuilder($app['html'], $app['url'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

}

<?php

namespace Busayo\Mention;

use Busayo\Mention\Factory\MentionBuilder;
use Illuminate\Support\ServiceProvider;

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

    public function boot()
    {
        $config = realpath(__DIR__.'/../resources/config/mentions.php');
        $views  = realpath(__DIR__.'/../resources/views');
        $script = realpath(__DIR__.'/../resources/assets');

        $this->publishes([
            $config => config_path('mentions.php'),
            $views  => base_path('resources/views/vendor/mentions'),
            $script => public_path('js'),
        ]);

        $this->loadViewsFrom(__DIR__.'/../resources/views', 'mentions');

         if (! $this->app->routesAreCached()) {
            require __DIR__.'/../Http/routes.php';
        }
    }

    /**
     * Register the application services
     * @return void
     */
    public function register()
    {
         $this->app->singleton('mentionBuilder', function ($app) {
            $form = new MentionBuilder($app['html'], $app['url'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

}

Add publishing feature to ServiceProvider


<?php

define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'user');
define('MYSQL_PASSWORD', 'password');
define('MYSQL_DATABASE', 'database');
define('TWITTER_USERNAME', 'mathias');
define('GOOGLE_PLUS_ID', '106697091536876736486');
define('SHORT_URL', 'http://mths.be/'); // include the trailing slash!
define('DEFAULT_URL', 'http://mathiasbynens.be'); // omit the trailing slash!

?>

<?php

define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'user');
define('MYSQL_PASSWORD', 'password');
define('MYSQL_DATABASE', 'database');
define('TWITTER_USERNAME', 'mathias');
define('GOOGLE_PLUS_ID', '106697091536876736486');
define('SHORT_URL', 'https://mths.be/'); // include the trailing slash!
define('DEFAULT_URL', 'https://mathiasbynens.be'); // omit the trailing slash!

?>

Update placeholder values to encourage HTTPS usage


<?php

class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * Eager load pivot relations.
     *
     * @param  array $models
     * @return void
     */
    protected function loadPivotRelations($models)
    {
        $query = head($models)->pivot->newQuery()->with('unit');
        $pivots = array_pluck($models, 'pivot');
        $pivots = head($pivots)->newCollection($pivots);

        $pivots->load($this->getPivotRelations());
    }

    /**
     * Get the pivot relations to be eager loaded.
     *
     * @return array
     */
    protected function getPivotRelations()
    {
        $relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
            return $relation != 'pivot';
        });

        return array_map(function ($relation) {
            return substr($relation, strlen('pivot.'));
        }, $relations);
    }

    /**
     * Override. Eager load relations of pivot models.
     * Eagerly load the relationship on a set of models.
     *
     * @param  array     $models
     * @param  string    $name
     * @param  \Closure  $constraints
     * @return array
     */
    protected function loadRelation(array $models, $name, Closure $constraints)
    {
        // In this part, if the relation name is 'pivot',
        // therefore there are relations in a pivot to be eager loaded.
        if ($name === 'pivot') {
            $this->loadPivotRelations($models);
            return $models;
        }

        return parent::loadRelation($models, $name, $constraints);
    }
}

<?php

class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * Eager load pivot relations.
     *
     * @param  array $models
     * @return void
     */
    protected function loadPivotRelations($models)
    {
        $query = head($models)->pivot->newQuery()->with('unit');
        $pivots = array_pluck($models, 'pivot');
        $pivots = head($pivots)->newCollection($pivots);

        $pivots->load($this->getPivotRelations());
    }

    /**
     * Get the pivot relations to be eager loaded.
     *
     * @return array
     */
    protected function getPivotRelations()
    {
        $relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
            return $relation != 'pivot' && str_contains($relation, 'pivot');
        });

        return array_map(function ($relation) {
            return substr($relation, strlen('pivot.'));
        }, $relations);
    }

    /**
     * Override. Eager load relations of pivot models.
     * Eagerly load the relationship on a set of models.
     *
     * @param  array     $models
     * @param  string    $name
     * @param  \Closure  $constraints
     * @return array
     */
    protected function loadRelation(array $models, $name, Closure $constraints)
    {
        // In this part, if the relation name is 'pivot',
        // therefore there are relations in a pivot to be eager loaded.
        if ($name === 'pivot') {
            $this->loadPivotRelations($models);
            return $models;
        }

        return parent::loadRelation($models, $name, $constraints);
    }
}

Fix condition, make sure not to include non-pivot relations


<?php
/**
 * bootstrap.php
 *
 * @package   Teto\SQL
 * @author    USAMI Kenta <tadsan@zonu.me>
 * @copyright 2016 USAMI Kenta
 * @license   https://github.com/BaguettePHP/TetoSQL/blob/master/LICENSE MPL-2.0
 */
require_once dirname(__DIR__) . '/vendor/autoload.php';

error_reporting(E_ALL | E_STRICT);

Add error_reporting(E_ALL | E_STRICT) in test


<?php
namespace Command\Zray;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;

class Enable extends Zray
{
    protected function configure()
    {
        $this->setName('zray:enable')
             ->setDescription('Enable Xdebug');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $files = \Helper\Ini::findIniFiles($this->_ini_files);

        foreach($files as $file) {
            `sudo sed -i 's#^; zend_extension=#zend_extension=#' $file`;
        }

        $this->getApplication()->find('server:restart')->run(new ArrayInput(array('command' => 'server:restart', 'service' => array('apache'))), new NullOutput());

        $output->writeln('Zend Server Z-Ray has been enabled');
    }
}

<?php
namespace Command\Zray;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;

class Enable extends Zray
{
    protected function configure()
    {
        $this->setName('zray:enable')
             ->setDescription('Enable Zend Server Z-Ray');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $files = \Helper\Ini::findIniFiles($this->_ini_files);

        foreach($files as $file) {
            `sudo sed -i 's#^; zend_extension=#zend_extension=#' $file`;
        }

        $this->getApplication()->find('server:restart')->run(new ArrayInput(array('command' => 'server:restart', 'service' => array('apache'))), new NullOutput());

        $output->writeln('Zend Server Z-Ray has been enabled');
    }
}

Fix typo in command description

Fix typo in command description


<?php

namespace Innomatic\Composer;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;

abstract class LegacyInstaller extends LibraryInstaller
{
    protected $innomaticLegacyDir;

    public function __construct(IOInterface $io, Composer $composer, $type = '')
    {
        parent::__construct($io, $composer, $type);
        $options = $composer->getPackage()->getExtra();
        $this->innomaticLegacyDir = isset($options['innomatic-legacy-dir']) ? rtrim($options['innomatic-legacy-dir'], '/') : '.';
    }

    public function getInstallPath(PackageInterface $package)
    {
        if ($this->io->isVerbose()) {
            $this->io->write("Innomatic legacy directory is '$this->innomaticLegacyDir/'");
        }

        return $this->innomaticLegacyDir;
    }
}

<?php

namespace Innomatic\Composer;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;

abstract class LegacyInstaller extends LibraryInstaller
{
    protected $innomaticLegacyDir;

    public function __construct(IOInterface $io, Composer $composer, $type = '')
    {
        parent::__construct($io, $composer, $type);
        $options = $composer->getPackage()->getExtra();
        $this->innomaticLegacyDir = isset($options['innomatic-legacy-dir']) ? rtrim($options['innomatic-legacy-dir'], '/') : 'innomatic_legacy';
    }

    public function getInstallPath(PackageInterface $package)
    {
        if ($this->io->isVerbose()) {
            $this->io->write("Innomatic legacy directory is '$this->innomaticLegacyDir/'");
        }

        return $this->innomaticLegacyDir;
    }
}

Set default Innomatic legacy directory

Set default Innomatic legacy directory


<?php

App::import('Lib', 'HuradHook');
$HuradHook = new HuradHook();
Configure::write('HuradHook.obj', $HuradHook);
require APPLIBS . 'filters.php';

App::uses('Functions', 'Lib');
App::uses('Formatting', 'Lib');
App::uses('HrNav', 'Lib');
App::uses('HrPlugin', 'Lib');
App::uses('Hurad', 'Lib');
App::uses('HuradWidget', 'Lib');
/**
 * Plugins
 */
$pluginBootstraps = Configure::read('Plugin.bootstraps');
$plugins = array_filter(explode(',', $pluginBootstraps));
foreach ($plugins as $plugin) {
    $pluginName = Inflector::camelize($plugin);
    if (!file_exists(APP . 'Plugin' . DS . $pluginName)) {
        CakeLog::write(LOG_ERR, 'Plugin not found during bootstrap: ' . $pluginName);
        continue;
    }
    $bootstrapFile = APP . 'Plugin' . DS . $pluginName . DS . 'Config' . DS . 'bootstrap.php';
    $bootstrap = file_exists($bootstrapFile);
    $routesFile = APP . 'Plugin' . DS . $pluginName . DS . 'Config' . DS . 'routes.php';
    $routes = file_exists($routesFile);
    $option = array(
        $pluginName => array(
            'bootstrap' => $bootstrap,
            'routes' => $routes,
        )
    );
    HrPlugin::load($option);
}

$theme_bootstrap = APP . 'View' . DS . 'Themed' . DS . Configure::read('template') . DS . 'Config' . DS . 'bootstrap.php';
if (is_file($theme_bootstrap)) {
    include $theme_bootstrap;
}

<?php

App::import('Lib', 'HuradHook');
$HuradHook = new HuradHook();
Configure::write('HuradHook.obj', $HuradHook);
require APPLIBS . 'filters.php';

App::uses('Functions', 'Lib');
App::uses('Formatting', 'Lib');
App::uses('HrNav', 'Lib');
App::uses('HuradPlugin', 'Lib');
App::uses('Hurad', 'Lib');
App::uses('HuradWidget', 'Lib');

/**
 * Load all active plugins
 */
HuradPlugin::loadAll();

/**
 * Include current theme bootstrap file.
 */
$theme_bootstrap = APP . 'View' . DS . 'Themed' . DS . Configure::read('template') . DS . 'Config' . DS . 'bootstrap.php';
if (is_file($theme_bootstrap) && file_exists($theme_bootstrap)) {
    include $theme_bootstrap;
}

Add HuradPlugin::loadAll() and use HuradPlugin Lib


<?php
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';

if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
  die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');

set('default_stage', 'production');

set('keep_releases', 2);

set('writable_use_sudo', false); // Using sudo in writable commands?

set('shared_files', [
    'config/db.php'
]);

task('deploy:configure_composer', function () {
  $stage = env('app.stage');
  if($stage == 'dev') {
    env('composer_options', 'install --verbose --no-progress --no-interaction');
  }
})->desc('Configure composer');

// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');

after('deploy:shared', 'deploy:configure');
before('deploy:vendors', 'deploy:configure_composer');

<?php
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';

if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
  die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');

set('default_stage', 'production');

set('keep_releases', 2);

set('writable_use_sudo', false); // Using sudo in writable commands?

set('shared_files', [
    'config/db.php'
]);

task('deploy:configure_composer', function () {
  $stage = env('app.stage');
  if($stage == 'dev') {
    env('composer_options', 'install --verbose --no-progress --no-interaction');
  }
})->desc('Configure composer');

// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');

after('deploy:shared', 'deploy:configure');
before('inplace:vendors', 'deploy:configure_composer');
before('deploy:vendors', 'deploy:configure_composer');

Fix composer for inplace in dev mode

Fix composer for inplace in dev mode


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver'  => 'pusher',
            'key'     => env('PUSHER_APP_KEY'),
            'secret'  => env('PUSHER_APP_SECRET'),
            'app_id'  => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
            ],
        ],

        'redis' => [
            'driver'     => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "ably", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver'  => 'pusher',
            'key'     => env('PUSHER_APP_KEY'),
            'secret'  => env('PUSHER_APP_SECRET'),
            'app_id'  => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
            ],
        ],

        'redis' => [
            'driver'     => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

Add "ably" in comment as a broadcast connection

https://github.com/laravel/laravel/pull/5531


<?php
namespace BryanCrowe;

class Growl
{
    public function __construct() {}

    public function growl($message = null, $options = []) {}

    public function createCommand()
    {
        switch (PHP_OS) {
            case 'Darwin':
                if (exec('which growlnotify')) {
                    $command = [
                        'pkg' => 'growlnotify',
                        'msg' => '-m'
                    ];
                } else {
                    $command = [
                        'pkg' => 'terminal-notifier',
                        'msg' => '-message'
                    ];
                }
            break;
            case 'Linux':
                if (exec('which growl')) {
                    $command = [
                        'pkg' => 'growl',
                        'msg' => '-m'
                    ];
                } else {
                    $command = [
                        'pkg' => 'notify-send',
                        'msg' => ''
                    ];
                }
            break;
            case 'WINNT':
                $command = [
                    'pkg' => 'growlnotify',
                    'msg' => ''
                ];
            break;

            return $command;
        }
    }
}

<?php
namespace BryanCrowe;

class Growl
{
    public function __construct() {}

    public function growl($message = null, $options = []) {}

    public function createCommand()
    {
        switch (PHP_OS) {
            case 'Darwin':
                if (exec('which growlnotify')) {
                    return [
                        'pkg' => 'growlnotify',
                        'msg' => '-m'
                    ];
                } else {
                    return [
                        'pkg' => 'terminal-notifier',
                        'msg' => '-message'
                    ];
                }
            break;
            case 'Linux':
                if (exec('which growl')) {
                    return [
                        'pkg' => 'growl',
                        'msg' => '-m'
                    ];
                } else {
                    return [
                        'pkg' => 'notify-send',
                        'msg' => ''
                    ];
                }
            break;
            case 'WINNT':
                return [
                    'pkg' => 'growlnotify',
                    'msg' => ''
                ];
            break;
        }
    }
}

Return the command array in createCommand


Fix the doc-explorer-back button overflow.


<?php

namespace WyriHaximus\FlyPie;

use League\Flysystem\AdapterInterface;

trait FilesystemsTrait
{
    /**
     * Proxy to the FilesystemRegistry.
     *
     * @param string $alias Alias name requested.
     *
     * @return AdapterInterface
     */
    public function filesystem($alias)
    {
        return FilesystemRegistry::retrieve($alias);
    }
}

<?php

namespace WyriHaximus\FlyPie;

use League\Flysystem\FilesystemInterface;

trait FilesystemsTrait
{
    /**
     * Proxy to the FilesystemRegistry.
     *
     * @param string $alias Alias name requested.
     *
     * @return FilesystemInterface
     */
    public function filesystem($alias)
    {
        return FilesystemRegistry::retrieve($alias);
    }
}

Change the phpdoc return type to the correct one

Hi!

I believe an error did sneak into the code here - correct me if I'm wrong.

I'm not sure whether this would require a major bump...


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */
namespace WellCommerce\Bundle\DictionaryBundle\Repository;

use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class DictionaryRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class DictionaryRepository extends AbstractEntityRepository implements DictionaryRepositoryInterface
{
    /**
     * @var array
     */
    private $domains = ['admin', 'front', 'flashes', 'validators'];

    /**
     * Returns possible translation domains
     *
     * @return array
     */
    public function getTranslationDomains()
    {
        $domains = [];
        foreach ($this->domains as $domain) {
            $domains[$domain] = $domain;
        }

        return $domains;
    }

    /**
     * {@inheritdoc}
     */
    public function getDictionaryTranslations()
    {
        $qb = parent::getQueryBuilder()
            ->leftJoin('WellCommerce\Bundle\DictionaryBundle\Entity\DictionaryTranslation',
                'dictionary_translation',
                'WITH',
                'dictionary.id = dictionary_translation.translatable')
            ->groupBy('dictionary.identifier, dictionary_translation.locale')
            ->select('dictionary.identifier,dictionary_translation.locale,dictionary_translation.translation');

        $query = $qb->getQuery();

        return $query->getArrayResult();
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */
namespace WellCommerce\Bundle\DictionaryBundle\Repository;

use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class DictionaryRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class DictionaryRepository extends AbstractEntityRepository implements DictionaryRepositoryInterface
{
}

Return types in repositories & dataset

Return types in repositories & dataset


<?php
/**
 * @package     Opengraph
 * @author      Axel Etcheverry <axel@etcheverry.biz>
 * @copyright   Copyright (c) 2011 Axel Etcheverry (http://www.axel-etcheverry.com)
 * Displays     MIT
 * @license     http://creativecommons.org/licenses/MIT/deed.fr    MIT
 */

/**
 * @namespace
 */
namespace Opengraph;

class Writer extends Opengraph
{
    /**
     * @var \ArrayObject
     */
    protected static $storage;

    /**
     * @var Integer
     */
    //protected static $position;

    /**
     * Append meta
     *
     * @param String $property
     * @param String $content
     * @return \Opengraph\Opengraph
     */
    public function append($property, $content)
    {
        return $this->addMeta($property, $content, self::APPEND);
    }

    /**
     * Prepend meta
     *
     * @param String $property
     * @param String $content
     * @return \Opengraph\Opengraph
     */
    public function prepend($property, $content)
    {
        return $this->addMeta($property, $content, self::PREPEND);
    }

    /**
     * Render all meta tags
     *
     * @return String
     */
    public function render()
    {
        $html = '';
        foreach(self::$storage as $meta) {
            $html .= "\t" . $meta->render() . PHP_EOL;
        }

        return $html;
    }
}

<?php
/**
 * @package     Opengraph
 * @author      Axel Etcheverry <axel@etcheverry.biz>
 * @copyright   Copyright (c) 2011 Axel Etcheverry (http://www.axel-etcheverry.com)
 * Displays     MIT
 * @license     http://creativecommons.org/licenses/MIT/deed.fr    MIT
 */

/**
 * @namespace
 */
namespace Opengraph;

class Writer extends Opengraph
{
    /**
     * @var \ArrayObject
     */
    protected static $storage;

    /**
     * @var Integer
     */
    //protected static $position;

    /**
     * Append meta
     *
     * @param String $property
     * @param String $content
     * @return \Opengraph\Opengraph
     */
    public function append($property, $content)
    {
        return $this->addMeta($property, $content, self::APPEND);
    }

    /**
     * Prepend meta
     *
     * @param String $property
     * @param String $content
     * @return \Opengraph\Opengraph
     */
    public function prepend($property, $content)
    {
        return $this->addMeta($property, $content, self::PREPEND);
    }

    /**
     * Render all meta tags
     *
     * @return String
     */
    public function render($indent = "\t")
    {
        $html = '';
        foreach(self::$storage as $meta) {
            $html .= $indent . $meta->render() . PHP_EOL;
        }

        return $html;
    }
}

Make tab spacing on render optional

Make tab spacing on render optional

Added a very simple optional variable when using `render()` to allow alternate line indentations (or none).


<?php

namespace Mini\Model\TypeCrawler;

use \Mini\Model\TypeCrawler\Storage\StorageFactory;

//TODO disable crawlers if the type is disabled in the DB.
class TypeCrawlerController {
    /** @var array */
    private $crawlers;
    /** @var StorageFactory */
    private $storage;

    function __construct(StorageFactory $storageFactory) {
        $this->crawlers = array();
        $this->storage = $storageFactory;

        $this->registerCrawler('ModBot');
        $this->registerCrawler('Pajbot');
        $this->registerCrawler('DeepBot');
        $this->registerCrawler('FrankerFaceZ.php')
    }

    private function getClassName(string $crawler): string {
        return '\\Mini\\Model\\TypeCrawler\\'.$crawler;
    }

    public function registerCrawler(string $crawler) {
        $crawler = $this->getClassName($crawler);
        $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type));
    }

    public function crawl(int $type): array {
        foreach($this->crawlers as $c) {
            if($c::$type == $type) {
                $crawler = $c;
                break;
            }
        }
        return $crawler->crawl();
    }

    public function triggerCrawl(): array {
        $ret = array();
        foreach($this->crawlers as $crawler) {
            try {
                $crawlResult = $crawler->crawl();
            } catch(Exception $e) {
                continue;
            }
            $ret = array_merge($ret, $crawlResult);
        }
        return $ret;
    }
}

<?php

namespace Mini\Model\TypeCrawler;

use \Mini\Model\TypeCrawler\Storage\StorageFactory;

//TODO disable crawlers if the type is disabled in the DB.
class TypeCrawlerController {
    /** @var array */
    private $crawlers;
    /** @var StorageFactory */
    private $storage;

    function __construct(StorageFactory $storageFactory) {
        $this->crawlers = array();
        $this->storage = $storageFactory;

        $this->registerCrawler('ModBot');
        $this->registerCrawler('Pajbot');
        $this->registerCrawler('DeepBot');
        $this->registerCrawler('FrankerFaceZ.php');
    }

    private function getClassName(string $crawler): string {
        return '\\Mini\\Model\\TypeCrawler\\'.$crawler;
    }

    public function registerCrawler(string $crawler) {
        $crawler = $this->getClassName($crawler);
        $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type));
    }

    public function crawl(int $type): array {
        foreach($this->crawlers as $c) {
            if($c::$type == $type) {
                $crawler = $c;
                break;
            }
        }
        return $crawler->crawl();
    }

    public function triggerCrawl(): array {
        $ret = array();
        foreach($this->crawlers as $crawler) {
            try {
                $crawlResult = $crawler->crawl();
            } catch(Exception $e) {
                continue;
            }
            $ret = array_merge($ret, $crawlResult);
        }
        return $ret;
    }
}

fix: Add missing semicolon in crawler controller


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

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('posts', function (Blueprint $table) {
            $table->boolean('is_spam')->default(0);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('posts', function (Blueprint $table) {
            $table->dropColumn('is_spam');
        });
    }
];

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

use Flarum\Database\Migration;

return Migration::addColumns('posts', [
    'is_spam' => ['boolean', 'default' => 0]
]);

Use new shortcuts for migrations

Use new shortcuts for migrations


Use new shortcuts for migrations

Use new shortcuts for migrations


<?php

namespace App\Api\Controllers\User;

use App\Api\Controllers\ApiController;

class UserDetailsController extends ApiController
{
    /**
     * Retrieve the currently authenticated user.
     *
     * @return User
     */
    protected function retrieve()
    {
        if (!$user = \JWTAuth::authenticate()) {
            $response = $this->apiErrorResponse('User not found');

            return $response;
        }

        $response = $this->apiResponse($user->all()->toArray());

        return $response;
    }
}

<?php

namespace App\Api\Controllers\User;

use App\Api\Controllers\ApiController;

class UserDetailsController extends ApiController
{
    /**
     * Retrieve the currently authenticated user.
     *
     * @return User
     */
    protected function retrieve()
    {
        if (!$user = \JWTAuth::authenticate()) {
            $response = $this->apiErrorResponse('User not found');

            return $response;
        }

        $response = $this->apiResponse($user->toArray());

        return $response;
    }
}

Update GET /me to return only logged in users details


<?php

/**
 * @file
 * Contains linclark\MicrodataPhpTest
 */

namespace linclark\MicrodataPHP;

/**
 * Tests the MicrodataPHP functionality.
 */
class MicrodataPhpTest extends \PHPUnit_Framework_TestCase {

  /**
   * Tests parsing a sample html document.
   */
  public function testParseMicroData() {
    $config = array('html' => file_get_contents(__DIR__ . '/../data/person.html'));
    $microdata = new MicrodataPhp($config);
    $data = $microdata->obj();

    $name = $data->items[0]->properties['name'][0];

    $this->assertEquals($name, "Jane Doe", "The name matches.");
  }

  /**
   * @expectedException \InvalidArgumentException
   */
  public function testConstructorNoUrlOrHtml() {
    $config = array();
    new MicrodataPhp($config);
  }
}

<?php

/**
 * @file
 * Contains linclark\MicrodataPhpTest
 */

namespace linclark\MicrodataPHP;

/**
 * Tests the MicrodataPHP functionality.
 */
class MicrodataPhpTest extends \PHPUnit_Framework_TestCase {

  /**
   * Tests parsing a sample html document.
   */
  public function testParseMicroData() {
    $config = $this->getConfig('person.html');
    $microdata = new MicrodataPhp($config);
    $data = $microdata->obj();

    $name = $data->items[0]->properties['name'][0];

    $this->assertEquals($name, "Jane Doe", "The name matches.");
  }

  /**
   * @expectedException \InvalidArgumentException
   */
  public function testConstructorNoUrlOrHtml() {
    $config = array();
    new MicrodataPhp($config);
  }

  protected function getConfig($file) {
    return array('html' => file_get_contents(__DIR__  . '/../data/' . $file));
  }
}

Move config HTML generation to separate helper function.