{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('source')]) !!}

@if ($theme->getTheme()->hasCustomData())
    {!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('edit')]) !!}
@endif

{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('default')]) !!}

{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('delete')]) !!}

{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('source')]) !!}

@if ($theme->getTheme()->isActive() AND $theme->getTheme()->hasCustomData())
    {!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('edit')]) !!}
@endif

{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('default')]) !!}

{!! $this->makePartial('lists/list_button', ['record' => $theme, 'column' => $this->getColumn('delete')]) !!}

Enable "Customize" button for only the currently active theme

Signed-off-by: Sam Poyigi <ccc2dd82f84c4106203d3b58d5938b70cab9f94a@users.noreply.github.com>


<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class DropboxResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string
     */
    public function getId()
    {
        return $this->response['uid'] ?: null;
    }

    /**
     * Get resource owner name
     *
     * @return string
     */
    public function getName()
    {
        return $this->response['display_name'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class DropboxResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string
     */
    public function getId()
    {
        return $this->response['account_id'] ?: null;
    }

    /**
     * Get resource owner name
     *
     * @return string
     */
    public function getName()
    {
        return $this->response['name']['display_name'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

Migrate to Dropbox API v2

Migrate to Dropbox API v2


<?php

namespace App;

use Carbon\Carbon;

class UserRepository {

    public function getUser($request) {
        $user = $request->user;
        $expiresIn = Carbon::now();
        $expiresIn->addSecond($request->expiresIn);
        return User::updateOrCreate(['id' => $request->id], [
            'id' => $request->id,
            'username' => $user['username'],
            'email' => $user['email'],
            'refresh_token' => $request->refreshToken,
            'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY',
            'token' => $request->token,
            'expires_in' => $expiresIn->toDateTimeString()
        ]);
    }
}

<?php

namespace App;

use Carbon\Carbon;

class UserRepository {

    public function getUser($request) {
        $user = $request->user;
        $expiresIn = Carbon::now();
        $expiresIn->addSecond($request->expiresIn);
        return User::updateOrCreate(['id' => $request->id], [
            'id' => $request->id,
            'username' => $user['username'],
            'email' => $request->email,
            'refresh_token' => $request->refreshToken,
            'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY',
            'token' => $request->token,
            'expires_in' => $expiresIn->toDateTimeString()
        ]);
    }
}

Fix error when logging in

Fix error when logging in


<?php
/**
 * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
 */

namespace Api;

use Phalcon\DiInterface;
use Phalcony\Rest\Dispatcher;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
    public function registerAutoloaders(DiInterface $dependencyInjector = null)
    {
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'Api\Controller' => APPLICATION_PATH . '/modules/api/controllers/',
            'Api\Model' => APPLICATION_PATH . '/modules/api/models/',
        ));
        $loader->register();
    }

    public function registerServices(DiInterface $di = null)
    {
        $dispatcher = new Dispatcher();
        $dispatcher->setDI($di);
        $dispatcher->setDefaultNamespace('Api\Controller');
        $dispatcher->setExceptionPath(array(
            'namespace' => 'Api\Controller',
            'module' => 'api',
            'controller' => 'index',
            'action'     => 'exception'
        ));

        $router = $di->get('router');
        $router->add('/api/users/get/{id:[a-Z]{1,11}}/', array(
            'module' => 1,
            'controller' => 2,
            'action' => 'index',
            'params' => 3
        ));

        $di->set('dispatcher', $dispatcher);
    }
}

<?php
/**
 * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
 */

namespace Api;

use Phalcon\DiInterface;
use Phalcony\Rest\Dispatcher;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
    public function registerAutoloaders(DiInterface $dependencyInjector = null)
    {
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'Api\Controller' => APPLICATION_PATH . '/modules/api/controllers/',
            'Api\Model' => APPLICATION_PATH . '/modules/api/models/',
        ));
        $loader->register();
    }

    public function registerServices(DiInterface $di = null)
    {
        $dispatcher = new Dispatcher();
        $dispatcher->setDI($di);
        $dispatcher->setDefaultNamespace('Api\Controller');
        $dispatcher->setExceptionPath(array(
            'namespace' => 'Api\Controller',
            'module' => 'api',
            'controller' => 'index',
            'action'     => 'exception'
        ));

        $di->set('dispatcher', $dispatcher);
    }
}

Remove unused route in Api module

Remove unused route in Api module


<?php

use Sunlight\Email;

defined('_root') or exit;

return function ($email = "") {
    return Email::generate($email);
};

<?php

use Sunlight\Email;

defined('_root') or exit;

return function ($email = "") {
    return Email::link($email);
};

Fix the method name of the Email class

Fix the method name of the Email class


<?php declare(strict_types=1);

namespace Rector\NodeValueResolver\Tests;

use PhpParser\BuilderHelpers;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Scalar\String_;
use Rector\NodeValueResolver\NodeValueResolver;
use Rector\Tests\AbstractContainerAwareTestCase;

final class NodeValueResolverTest extends AbstractContainerAwareTestCase
{
    /**
     * @var NodeValueResolver
     */
    private $nodeValueResolver;

    protected function setUp(): void
    {
        $this->nodeValueResolver = $this->container->get(NodeValueResolver::class);
    }

    public function testArrayNode(): void
    {
        $arrayNode = new Array_([
            new ArrayItem(new String_('hi')),
            new ArrayItem(BuilderHelpers::normalizeValue(true)),
            new ArrayItem(BuilderHelpers::normalizeValue(false)),
        ]);

        $resolved = $this->nodeValueResolver->resolve($arrayNode);
        $this->assertSame(['hi', true, false], $resolved);
    }
}

<?php declare(strict_types=1);

namespace Rector\NodeValueResolver\Tests;

use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use Rector\NodeValueResolver\NodeValueResolver;
use Rector\Tests\AbstractContainerAwareTestCase;

final class NodeValueResolverTest extends AbstractContainerAwareTestCase
{
    /**
     * @var NodeValueResolver
     */
    private $nodeValueResolver;

    protected function setUp(): void
    {
        $this->nodeValueResolver = $this->container->get(NodeValueResolver::class);
    }

    public function testArrayNode(): void
    {
        $arrayNode = new Array_([
            new ArrayItem(new String_('hi')),
            new ArrayItem(new ConstFetch(new Name('true'))),
            new ArrayItem(new ConstFetch(new Name('FALSE'))),
        ]);

        $resolved = $this->nodeValueResolver->resolve($arrayNode);
        $this->assertSame(['hi', true, false], $resolved);
    }
}

Add test for uppercade keywords

Add test for uppercade keywords


<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\SchedulerBundle\Entity\Manager;

use ASF\CoreBundle\Entity\Manager\ASFEntityManager;

/**
 * Generic Entity Manager for this bundle
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
class ASFSchedulerManager extends ASFEntityManager implements ASFSchedulerManagerInterface {}

<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\SchedulerBundle\Entity\Manager;

use ASF\CoreBundle\Utils\Manager\ASFEntityManager;

/**
 * Generic Entity Manager for this bundle
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
class ASFSchedulerManager extends ASFEntityManager implements ASFSchedulerManagerInterface {}

Change use statement to ASFEntityManager


<?php

namespace Benwilkins\FCM;

use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * Class FcmChannel.
 */
class FcmChannel
{
    /**
     * @const The API URL for Firebase
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

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

    /**
     * @param Client $client
     */
    public function __construct(Client $client, $apiKey)
    {
        $this->client = $client;
        $this->apiKey = $apiKey;
    }

    /**
     * @param mixed $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        /** @var FcmMessage $message */
        $message = $notification->toFcm($notifiable);

        if (is_null($message->getTo())) {
            if (! $to = $notifiable->routeNotificationFor('fcm')) {
                return;
            }

            $message->to($to);
        }

        $response = $this->client->post(self::API_URI, [
            'headers' => [
                'Authorization' => 'key='.$this->apikey,
                'Content-Type'  => 'application/json',
            ],
            'body' => $message->formatData(),
        ]);

        return \GuzzleHttp\json_decode($response->getBody(), true);
    }
}

<?php

namespace Benwilkins\FCM;

use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * Class FcmChannel.
 */
class FcmChannel
{
    /**
     * @const The API URL for Firebase
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

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

    /**
     * @param Client $client
     */
    public function __construct(Client $client, $apiKey)
    {
        $this->client = $client;
        $this->apiKey = $apiKey;
    }

    /**
     * @param mixed $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        /** @var FcmMessage $message */
        $message = $notification->toFcm($notifiable);

        if (is_null($message->getTo())) {
            if (! $to = $notifiable->routeNotificationFor('fcm')) {
                return;
            }

            $message->to($to);
        }

        $response = $this->client->post(self::API_URI, [
            'headers' => [
                'Authorization' => 'key='.$this->apiKey,
                'Content-Type'  => 'application/json',
            ],
            'body' => $message->formatData(),
        ]);

        return \GuzzleHttp\json_decode($response->getBody(), true);
    }
}

Fix typo on apiKey Variable

Fix typo on apiKey Variable


<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class PdoAuthenticator implements AuthenticatorInterface
{
    private $options;

    public function __construct(array $options = array())
    {

        /* Default options. */
        $this->options = array(
            "table" => "users",
            "user" => "user",
            "hash" => "hash"
        );

        if ($options) {
            $this->options = array_merge($this->options, $options);
        }
    }

    public function authenticate($username, $pass)
    {
        $statement = $this->options["pdo"]->prepare(
            "SELECT *
             FROM {$this->options['table']}
             WHERE {$this->options['user']} = ?
             LIMIT 1"
        );

        $statement->execute(array($username));

        if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
            return password_verify($pass, $user[$this->options["hash"]]);
        }

        return false;
    }
}

<?php

/*
 * This file is part of Slim HTTP Basic Authentication middleware
 *
 * Copyright (c) 2013-2014 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-basic-auth
 *
 */

namespace Slim\Middleware\HttpBasicAuthentication;

class PdoAuthenticator implements AuthenticatorInterface
{
    private $options;

    public function __construct(array $options = array())
    {

        /* Default options. */
        $this->options = array(
            "table" => "users",
            "user" => "user",
            "hash" => "hash"
        );

        if ($options) {
            $this->options = array_merge($this->options, $options);
        }
    }

    public function authenticate($user, $pass)
    {
        $statement = $this->options["pdo"]->prepare(
            "SELECT *
             FROM {$this->options['table']}
             WHERE {$this->options['user']} = ?
             LIMIT 1"
        );

        $statement->execute(array($user));

        if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
            return password_verify($pass, $user[$this->options["hash"]]);
        }

        return false;
    }
}

Use user instead of username

Use user instead of username


<?php
namespace Criterion\Helper;

class Project extends \Criterion\Helper
{
    public static function fromRepo($repo)
    {
        $project = array();
        $project['repo'] = $repo;
        $project['github']['token'] = null;
        $project['email'] = null;
        $project['short_repo'] = Repo::short($project['repo']);
        $project['provider'] = Repo::provider($project['repo']);
        $project['last_run'] = new \MongoDate();
        $project['status'] = array(
            'code' => '2',
            'message' => 'New'
        );

        return $project;
    }

    public static function sshKeyFile($project)
    {
        $path = KEY_DIR . '/' . $project['_id'];

        if ( ! is_file($path))
        {
            file_put_contents($path, $project['ssh_key']['private']);
        }

        chmod($path, 0600);

        return $path;
    }
}

<?php
namespace Criterion\Helper;

class Project extends \Criterion\Helper
{
    public static function sshKeyFile($project)
    {
        $path = KEY_DIR . '/' . $project['_id'];

        if ( ! is_file($path))
        {
            file_put_contents($path, $project['ssh_key']['private']);
        }

        chmod($path, 0600);

        return $path;
    }
}

Remove fromRepo as its not needed anymore


<?php

namespace App;

class Slim extends \Slim\Slim
{
    public function mapRoute($args)
    {
        $callable = array_pop($args);
        if (is_string($callable) && strpos($callable, ':')) {
            $callable = $this->createControllerCallable($callable);
        }
        $args[] = $callable;

        return parent::mapRoute($args);
    }

    protected function createControllerCallable($name)
    {
        list($controllerName, $actionName) = explode(':', $name);

        // Create a callable that will find or create the controller instance
        // and then execute the action
        $app = $this;
        $callable = function () use ($app, $controllerName, $actionName) {

            // Try to fetch the controller instance from Slim's container
            if ($app->container->has($controllerName)) {
                $controller = $app->container->get($controllerName);
            } else {
                // not in container, assume it can be directly instantiated
                $controller = new $controllerName($app);
            }

            // Set the request and response if we can
            if (method_exists($controller, 'setRequest')) {
                $controller->setRequest($app->request);
            }
            if (method_exists($controller, 'setResponse')) {
                $controller->setResponse($app->response);
            }

            return call_user_func_array(array($controller, $actionName), func_get_args());
        };

        return $callable;
    }
}

<?php

namespace App;

class Slim extends \Slim\Slim
{
    public function mapRoute($args)
    {
        $callable = array_pop($args);
        if (is_string($callable) && strpos($callable, ':')) {
            $callable = $this->createControllerCallable($callable);
        }
        $args[] = $callable;

        return parent::mapRoute($args);
    }

    protected function createControllerCallable($name)
    {
        list($controllerName, $actionName) = explode(':', $name);

        // Create a callable that will find or create the controller instance
        // and then execute the action
        $app = $this;
        $callable = function () use ($app, $controllerName, $actionName) {

            // Try to fetch the controller instance from Slim's container
            if ($app->container->has($controllerName)) {
                $controller = $app->container->get($controllerName);
            } else {
                // not in container, assume it can be directly instantiated
                $controller = new $controllerName($app);
            }

            // Set the App, request and response into the controller if we can
            if (method_exists($controller, 'setApp')) {
                $controller->setApp($app);
            }
            if (method_exists($controller, 'setRequest')) {
                $controller->setRequest($app->request);
            }
            if (method_exists($controller, 'setResponse')) {
                $controller->setResponse($app->response);
            }

            return call_user_func_array(array($controller, $actionName), func_get_args());
        };

        return $callable;
    }
}

Set the application object into the controller too.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $alerts = DB::table('alerts')->get();
    return view('alerts.index')->with('alerts', $alerts);
  }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Alert;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $alerts = Alert::all();
    return view('alerts.index')->with('alerts', $alerts);
  }
}

Use Eqoquent to build query

Use Eqoquent to build query


<?php

namespace common\models\comments;

use yii\db\ActiveRecord;

abstract class Comment extends ActiveRecord
{
    public static function instantiate($row)
    {
        return new AdjacencyListComment();
    }

    public static function create($config = [])
    {
        return new AdjacencyListComment($config);
    }
}

<?php

namespace common\models\comments;

use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;

abstract class Comment extends ActiveRecord
{
    public static function instantiate($row)
    {
        return new AdjacencyListComment();
    }

    public static function create($config = [])
    {
        return new AdjacencyListComment($config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false],
        ];
    }

    public function rules()
    {
        return [
            ['text', 'filter', 'filter' => 'trim'],
            ['text', 'required'],
            ['text', 'string', 'min' => 10, 'max' => 10000],
        ];
    }
}

Add necessary behaviors and validation rules.


@extends('layouts.user.main')

@section('title')
    {{trans('layout.zagros')}}::{{trans('layout.prjs')}}
@stop

@section('projects-navbar')active @stop

@section('content')

Projects

        @if (Session::has('message'))

{{Session::get('message')}}

        @endif
        @forelse ($projects as $project)

                    url)}}">{{$project->name}}
                    @if (Auth::user()->admin)
                         project_id)}}">Edit
                    @endif

                {{$project->description}}

        @empty

{{trans('messages.no_project')}}

        @endforelse

@stop

@extends('layouts.user.main')

@section('title')
    {{trans('layout.zagros')}}::{{trans('layout.projects')}}
@stop

@section('projects-navbar')active @stop

@section('content')

Projects

        @if (Session::has('message'))

{{Session::get('message')}}

        @endif
        @forelse ($projects as $project)

                    url)}}">{{$project->name}}
                    @if (Auth::user()->admin)
                         project_id)}}">Edit
                    @endif

                {{$project->description}}

        @empty

{{trans('messages.no_project')}}

        @endforelse

@stop

Fix some bugs and better blueprint view

Fix some bugs and better blueprint view


<?php
// Mysql info
$host = "localhost";
$user = "root";
$pass = "vertrigo";
$db = "beeshort";

// Put the website URL here, with http:// or https://
$weburl = "http://localhost/";

// Other Configurations
$customurltip = "If you put CustomURL, your url will be website.com/CustomURL. Leave this blank if you want a random url code";
$pagetitle = "BeeShort - URL Shortener";
$specialchars = false;
?>

<?php
// Mysql info
$host = "localhost";
$user = "root";
$pass = "";
$db = "beeshort";

// Put the website URL here, with http:// or https://
$weburl = "http://localhost/";

// Other Configurations
$customurltip = "If you put CustomURL, your url will be website.com/CustomURL. Leave this blank if you want a random url code";
$pagetitle = "BeeShort - URL Shortener";
$specialchars = false;
?>

Change default password to nothing

Change default password to nothing


<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

Update Tasks - Date : 25/10/2016

Update Tasks - Date : 25/10/2016


<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {

	/**
 	 * Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
 	 * This command migrates extended models to the new namespace.
 	 */
	public function migrateGarpModels() {
		$modelDir = APPLICATION_PATH . '/modules/default/Model';
		$dirIterator = new DirectoryIterator($modelDir);
		foreach ($dirIterator as $finfo) {
			if ($finfo->isDot()) {
				continue;
			}
			$this->_modifyModelFile($finfo);
		}
	}

	protected function _modifyModelFile($finfo) {
		$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
		$contents = file_get_contents($path);
		if (strpos($contents, 'extends G_Model_') === false) {
			return;
		}
		$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
		return file_put_contents($path, $contents);
	}
}

<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {

	/**
 	 * Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
 	 * This command migrates extended models to the new namespace.
 	 */
	public function migrateGarpModels() {
		$modelDir = APPLICATION_PATH . '/modules/default/Model';
		$dirIterator = new DirectoryIterator($modelDir);
		foreach ($dirIterator as $finfo) {
			if ($finfo->isDot()) {
				continue;
			}
			$this->_modifyModelFile($finfo);
		}

		$this->_updateCropTemplateRefs();
	}

	// Change references to G_Model_CropTemplate
	protected function _updateCropTemplateRefs() {
		$iniPaths = ['/configs/content.ini', '/configs/acl.ini'];
		foreach ($iniPaths as $i => $path) {
			$content = file_get_contents(APPLICATION_PATH . $path);
			$content = str_replace('G_Model_CropTemplate', 'Garp_Model_Db_CropTemplate', $content);
			file_put_contents(APPLICATION_PATH . $path, $content);
		}
	}

	protected function _modifyModelFile($finfo) {
		$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
		$contents = file_get_contents($path);
		if (strpos($contents, 'extends G_Model_') === false) {
			return;
		}
		$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
		return file_put_contents($path, $contents);
	}
}

Migrate script now also updates CropTemplate


			User
			Email
			Phone

		@forelse($users as $user)

				id]) }}">{{ $user->displayName() }}
				{{ $user->email or '' }}
				{{ $user->prettyMobile() }}

		@empty
		@endforelse

            Name
            Contact Methods
            Last Visited

        @forelse($users as $user)

            id]) }}">{{ $user->display_name }}

                {{ $user->email_preview }}
                @if ($user->email_preview && $user->mobile_preview)
                     and
                @endif
                {{ $user->mobile_preview }}

                {{ $user->last_accessed_at ? $user->last_accessed_at->diffForHumans() : 'more than 2 years ago' }}

        @empty
        @endforelse

Update index for sensitive fields.

Update index for sensitive fields.


<?php namespace Modules\Menu\Database\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model {

	public $table = 'menu';

	public $timestamps = false;

	protected $fillable = ["text","link","position","parent_id","depth","left","right","public"];

	public function children()
	{
		return $this->whereParentId($this->id)->orderBy('position')->get();
	}

	public static function hierarchy($parent_id = 0)
	{
		$items = self::whereParent_id($parent_id)->orderBy('position')->get();

		foreach($items as $item)
		{
			$item->items = self::hierarchy($item->id);
		}

		return $items;
	}

}

<?php namespace Modules\Menu\Database\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model {

	public $table = 'menu';

	public $timestamps = false;

	protected $fillable = ["text","link","position","parent_id","depth","left","right","public"];

	public function children()
	{
		return $this->whereParentId($this->id)->orderBy('position')->get();
	}

	public static function hierarchy($parent_id = 0, $only_public = false)
	{

		$items = self::whereParent_id($parent_id)
		if ($only_public)
			$items = $items->wherePublic(1);

		$items = $items->orderBy('position')->get();

		foreach($items as $item)
		{
			$item->items = self::hierarchy($item->id, $only_public);
		}

		return $items;
	}

}

Add attribute only public for further usage in frontend


<?php

namespace Alchemy\Queue\Tests;

use Alchemy\Queue\Message;

class MessageTest extends \PHPUnit_Framework_TestCase
{

    public function testMessageHasBody()
    {
        $message = new Message('mock-body');

        $this->assertEquals('mock-body', $message->getBody());
    }

    public function testMessageHasDefaultCorrelationId()
    {
        $message = new Message('mock-body');

        $this->assertNotEmpty($message->getCorrelationId(), 'Message should have default correlation ID');
    }

    public function testMessageCorrelationIdCanBeOverridden()
    {
        $message = new Message('mock-body', 'mock-correlation-id');

        $this->assertEquals('mock-correlation-id', $message->getCorrelationId());
    }
}

<?php

namespace Alchemy\Queue\Tests;

use Alchemy\Queue\Message;

class MessageTest extends \PHPUnit_Framework_TestCase
{

    public function testMessageHasBody()
    {
        $message = new Message('mock-body');

        $this->assertEquals('mock-body', $message->getBody());
    }

    public function testMessageHasDefaultCorrelationId()
    {
        $message = new Message('mock-body');

        $this->assertNotEmpty($message->getCorrelationId(), 'Message should have default correlation ID');
    }

    public function testMessageCorrelationIdCanBeOverridden()
    {
        $message = new Message('mock-body', 'mock-correlation-id');

        $this->assertEquals('mock-correlation-id', $message->getCorrelationId());
    }

    public function testMessageCreatedFromArrayHasJsonEncodedBody()
    {
        $data = ['mock-key'=>'mock-value'];

        $message = Message::fromArray($data, 'mock-id');

        $this->assertEquals('mock-id', $message->getCorrelationId());
        $this->assertEquals($data, json_decode($message->getBody(), true));
    }
}

Test messages created from data arrays

Test messages created from data arrays


<?php

namespace Intracto\SecretSantaBundle\Entity;

use Doctrine\ORM\EntityRepository;

class PoolRepository extends EntityRepository
{
    public function findAllAdminPools($email)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->addSelect('pool.listurl')
            ->addSelect('pool.date')
            ->addSelect('pool.locale')
            ->from('IntractoSecretSantaBundle:Pool', 'pool')
            ->join('pool.entries', 'entries')
            ->andWhere('entries.poolAdmin = true')
            ->andWhere('entries.email = :email')
            ->andWhere('pool.date >= :date')
            ->setParameters([
                'email' => $email,
                'date' => new \DateTime('-1 week'),
            ]);

        return $qb->getQuery()->getResult();
    }
}

<?php

namespace Intracto\SecretSantaBundle\Entity;

use Doctrine\ORM\EntityRepository;

class PoolRepository extends EntityRepository
{
    public function findAllAdminPools($email)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->addSelect('pool.listurl')
            ->addSelect('pool.eventdate')
            ->addSelect('pool.locale')
            ->from('IntractoSecretSantaBundle:Pool', 'pool')
            ->join('pool.entries', 'entries')
            ->andWhere('entries.poolAdmin = true')
            ->andWhere('entries.email = :email')
            ->andWhere('pool.eventdate >= :date')
            ->setParameters([
                'email' => $email,
                'date' => new \DateTime('-1 week'),
            ]);

        return $qb->getQuery()->getResult();
    }
}

Fix error on requesting forgot-link mail


<?php

// Load composer dependencies
require 'vendor/autoload.php';
require 'src/coffee.php';

// Settings
$settings = require 'config.php';

// Create a new app
$app = new \Slim\App($settings);

// Get container
$container = $app->getContainer();

// Register component on container
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig('templates', [
        'cache' => $container->get('settings')['debug'] ? false : 'cache'
    ]);

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));

    // Add globals like this
    // $view->getEnvironment()->addGlobal('<key>', $container->get('settings')['<key>']);

    return $view;
};

// Routes here.

// Compile SCSS and CoffeeScript
if ($settings['debug']) {
    CoffeeCompiler::run('scripts/', 'static/');
    SassCompiler::run("styles/", "static/");
}

// Start the app
$app->run();

?>

<?php

// Load composer dependencies
require 'vendor/autoload.php';
require 'src/coffee.php';

// Settings
$settings = require 'config.php';

// Create a new app
$app = new \Slim\App($settings);

// Get container
$container = $app->getContainer();

// Register component on container
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig('templates', [
        'cache' => $container->get('settings')['debug'] ? false : 'cache'
    ]);

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));

    // Add globals like this
    // $view->getEnvironment()->addGlobal('<key>', $container->get('settings')['<key>']);

    return $view;
};

// Routes here.
$app->get('/', function($request, $response) {
    return $this->view->render($response, 'index.html', [
        'site_name' => 'SpaceDock'
    ]);
});

$app->get('/static/{filename}', function($request, $response, $args) {
    $file_path = join('/', array('static', $args['filename']));
    return $response->write(file_get_contents($file_path));
})->setName('static');

// Compile SCSS and CoffeeScript
if ($settings['debug']) {
    CoffeeCompiler::run('scripts/', 'static/');
    SassCompiler::run("styles/", "static/");
}

// Start the app
$app->run();

?>

Add static and default routes

Add static and default routes


<?php
/**
 * @file index.php
 * Friendica
 */

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

// We assume that the index.php is called by a frontend process
// The value is set to "true" by default in App
$a = new Friendica\App(__DIR__, false);

$a->runFrontend();

<?php
/**
 * @file index.php
 * Friendica
 */

if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
	die('Vendor path not found. Please execute "bin/composer.phar --no-dev install" on the command line in the web root.');
}

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

// We assume that the index.php is called by a frontend process
// The value is set to "true" by default in App
$a = new Friendica\App(__DIR__, false);

$a->runFrontend();

Check if the vendor path is missing and complain about it


<?php

namespace Yajra\Auditable;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param Model $model
     */
    public function creating(Model $model)
    {
        $createdBy = $model->getCreatedByColumn();
        $updatedBy = $model->getUpdatedByColumn();

        if (! $model->$createdBy) {
            $model->$createdBy = $this->getAuthenticatedUserId();
        }

        if (! $model->$updatedBy) {
            $model->$updatedBy = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : null;
    }

    /**
     * Model's updating event hook.
     *
     * @param Model $model
     */
    public function updating(Model $model)
    {
        $updatedBy = $model->getUpdatedByColumn();

        if (! $model->isDirty($updatedBy)) {
            $model->$updatedBy = $this->getAuthenticatedUserId();
        }
    }
}

<?php

namespace Yajra\Auditable;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param Model $model
     */
    public function creating(Model $model)
    {
        $createdBy = $model->getCreatedByColumn();
        $updatedBy = $model->getUpdatedByColumn();

        if (! $model->$createdBy) {
            $model->$createdBy = $this->getAuthenticatedUserId();
        }

        if (! $model->$updatedBy) {
            $model->$updatedBy = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : null;
    }

    /**
     * Model's updating event hook.
     *
     * @param Model $model
     */
    public function updating(Model $model)
    {
        $updatedBy = $model->getUpdatedByColumn();

        if (! $model->isDirty($updatedBy)) {
            $model->$updatedBy = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Set updatedBy column on save if value is not the same.
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     */
    public function saved(Model $model)
    {
        $updatedBy = $model->getUpdatedByColumn();

        if ($model->$updatedBy <> $this->getAuthenticatedUserId()) {
            $model->$updatedBy = $this->getAuthenticatedUserId();
            $model->save();
        }
    }
}

Fix touch event of relation, not updating updated_by.


<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;

	class Headers extends Base
	{
		private $headers;

		public function __construct($auto = false)
		{
			if ($auto === true)
			{
				$this->parse();
			}
		}

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

		public function __isset($name)
		{
			return isset($this->headers[$name]) ? true : false;
		}

		public function __call($name, $arguments)
		{
			if ($arguments == array())
			{
				return $this->headers[$name];
			}

			$this->headers[$name] = $arguments[0];
			return true;
		}

		private function fetchHeaders()
		{
			$headers = array();

			foreach ($_SERVER as $key => $value)
			{
				if (strpos($key, "HTTP_") === 0)
				{
					$bits = explode("_", $key);
					array_shift($bits);

					foreach ($bits as &$bit)
					{
						$bit = ucwords(strtolower($bit));
					}

					$headers[implode("-", $bits)] = $value;
				}
			}

			return $headers;
		}

		public function parse()
		{
            $this->headers = array_change_key_case($this->fetchHeaders(), CASE_LOWER);
		}
	}
?>

<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;

	class Headers extends Base
	{
		private $headers;

		public function __construct($auto = false)
		{
			if ($auto === true)
			{
				$this->parse();
			}
		}

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

		public function __isset($name)
		{
			return isset($this->headers[$name]) ? true : false;
		}

		public function __call($name, $arguments)
		{
			if ($name == "headers")
			{
				return $this->headers;
			}

			if ($arguments == array())
			{
				return $this->headers[$name];
			}

			$this->headers[$name] = $arguments[0];
			return true;
		}

		private function fetchHeaders()
		{
			$headers = array();

			foreach ($_SERVER as $key => $value)
			{
				if (strpos($key, "HTTP_") === 0)
				{
					$bits = explode("_", $key);
					array_shift($bits);

					foreach ($bits as &$bit)
					{
						$bit = ucwords(strtolower($bit));
					}

					$headers[implode("-", $bits)] = $value;
				}
			}

			return $headers;
		}

		public function parse()
		{
            $this->headers = array_change_key_case($this->fetchHeaders(), CASE_LOWER);
		}
	}
?>

Allow for returning full headers object

Allow for returning full headers object


<?php
namespace StrategyValidator\Strategy;

interface StrategyInterface {

    public function isValid($value);

}

<?php
namespace StrategyValidator\Strategy;

interface StrategyInterface {

    /**
    *
    * @param $value Value or content to be validated.
    * @return boolean
    */
    public function isValid($value);

}

Add docblock for specifying input and return type


<?php
declare(strict_types=1);

namespace Vision\DataStructures\Arrays\Mutator;

use Vision\DataStructures\Arrays\ArrayObject;

class SquareBracketNotation extends ArrayObject
{
    public function set(string $name, $value): SquareBracketNotation
    {
        $parts = explode('[', $this->prepareName($name));
        $data =& $this->data;

        foreach ($parts as $part) {
            $part = rtrim($part, ']');

            if (!isset($data[$part])) {
                $data[$part] = [];
            }

            if (!is_array($data[$part])) {
                return $this;
            }

            $data =& $data[$part];
        }

        $data = $value;
        return $this;
    }

    public function get(string $name)
    {
        $parts = explode('[', $this->prepareName($name));
        $data = $this->data;

        foreach ($parts as $part) {
            $part = rtrim($part, ']');
            if (isset($data[$part])) {
                $data = $data[$part];
            } else {
                return null;
            }
        }

        return $data;
    }

    protected function prepareName(string $name): string
    {
        if (strpos($name, '[]') !== false) {
            $name = str_replace('[]', '', $name);
        }

        return $name;
    }
}

<?php
declare(strict_types=1);

namespace Vision\DataStructures\Arrays\Mutator;

use Vision\DataStructures\Arrays\ArrayObject;

class SquareBracketNotation extends ArrayObject
{
    public function set(string $name, $value): SquareBracketNotation
    {
        $data =& $this->data;

        foreach ($this->extractPartsFromName($name) as $part) {
            $part = rtrim($part, ']');

            if (!isset($data[$part])) {
                $data[$part] = [];
            }

            if (!is_array($data[$part])) {
                return $this;
            }

            $data =& $data[$part];
        }

        $data = $value;
        return $this;
    }

    public function get(string $name)
    {
        $data = $this->data;

        foreach ($this->extractPartsFromName($name) as $part) {
            $part = rtrim($part, ']');
            if (isset($data[$part])) {
                $data = $data[$part];
            } else {
                return null;
            }
        }

        return $data;
    }

    private function extractPartsFromName(string $name): array
    {
        if (strpos($name, '[]') !== false) {
            $name = str_replace('[]', '', $name);
        }

        return explode('[', $name);
    }
}

Move redundant code into private method

Move redundant code into private method


<?php
namespace core;

use InvalidArgumentException;

class Config
{
    /** @var  array $settings */
    private static $settings;

    /**
     * @param string $name
     * @param null $default
     * @return string
     */
    public static function get($name, $default = null) {
        if (empty($name)) {
            Report::reportFatal('Nothing to get', InvalidArgumentException::class);
        }
        if (self::$settings === null) {
            parse_ini_file(PROPERTIES);
        }
        if (isset(self::$settings[ $name ])) {
            return (string)self::$settings[ $name ];
        } elseif ($default !== null) {
            return $default;
        }
        Report::reportFatal("Setting $name not found", InvalidArgumentException::class);

        return null;
    }
}

<?php
namespace core;

use InvalidArgumentException;

class Config
{
    /** @var  array $settings */
    private static $settings;

    /**
     * @param string $name
     * @param null $default
     * @return string
     */
    public static function get ( $name, $default = null ) {
        if ( empty( $name ) ) {
            Report::reportFatal ( 'Nothing to get', InvalidArgumentException::class );
        }
        if ( self::$settings === null ) {
            self::getSettings ();
        }
        if ( isset( self::$settings[ $name ] ) ) {
            return (string) self::$settings[ $name ];
        } elseif ( $default !== null ) {
            return $default;
        }
        var_dump(self::$settings);
        Report::reportFatal ( "Setting $name not found", InvalidArgumentException::class );

        return null;
    }

    private static function getSettings () {
        if ( function_exists ( 'parse_ini_file' ) ) {
            self::$settings = parse_ini_file ( PROPERTIES );
        } else {
            $content = preg_grep ( "/^[\w .]+=.*/", explode ( PHP_EOL, file_get_contents ( PROPERTIES ) ) );
            foreach ( $content as $row ) {
                $row                    = strstr ( $row . ";", ";", true );
                $key                    = trim ( strstr ( $row, "=", true ), " \n\r" );
                $value                  = trim ( strstr ( $row, "=", false ), " \"=\n\r" );
                self::$settings[ $key ] = $value;
            }
        }
    }
}

Check for disabled function parse_ini_file


<?php namespace GeneaLabs\LaravelGovernor\Policies;

use GeneaLabs\LaravelGovernor\Role;

class RolePolicy extends LaravelGovernorPolicy
{
    public function create($user, Role $role)
    {
        return $this->validatePermissions($user, 'create', 'announcement', $role->created_by);
    }

    public function edit($user, Role $role)
    {
        return $this->validatePermissions($user, 'edit', 'announcement', $role->created_by);
    }

    public function view($user, Role $role)
    {
        return $this->validatePermissions($user, 'view', 'announcement', $role->created_by);
    }

    public function inspect($user, Role $role)
    {
        return $this->validatePermissions($user, 'inspect', 'announcement', $role->created_by);
    }

    public function remove($user, Role $role)
    {
        return $this->validatePermissions($user, 'remove', 'announcement', $role->created_by);
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Policies;

use GeneaLabs\LaravelGovernor\Role;

class RolePolicy extends LaravelGovernorPolicy
{
    public function create($user, Role $role)
    {
        return $this->validatePermissions($user, 'create', 'role', $role->created_by);
    }

    public function edit($user, Role $role)
    {
        return $this->validatePermissions($user, 'edit', 'role', $role->created_by);
    }

    public function view($user, Role $role)
    {
        return $this->validatePermissions($user, 'view', 'role', $role->created_by);
    }

    public function inspect($user, Role $role)
    {
        return $this->validatePermissions($user, 'inspect', 'role', $role->created_by);
    }

    public function remove($user, Role $role)
    {
        return $this->validatePermissions($user, 'remove', 'role', $role->created_by);
    }
}

Fix incorrect entity assignment in Role policy


<?php

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

return [
    'up' => function (Builder $schema) {
        $schema->table('fof_upload_downloads', function (Blueprint $table) {
            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('set null');
        });
    },
    'down' => function (Builder $schema) {
        $schema->table('fof_upload_downloads', function (Blueprint $table) {
            $table->dropForeign(['post_id']); // Using array syntax will make Laravel "guess" the index name
        });
    },
];

<?php

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

return [
    'up' => function (Builder $schema) {
        // Set post_id null if the post does not exist.
        // Will prevent issues when applying foriegn key constraint.
        $connection = $schema->getConnection();
        $connection->table('fof_upload_downloads')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)->from('posts')->whereColumn('post_id', 'id');
            })
            ->update(['post_id' => null]);

        $schema->table('fof_upload_downloads', function (Blueprint $table) {
            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('set null');
        });
    },
    'down' => function (Builder $schema) {
        $schema->table('fof_upload_downloads', function (Blueprint $table) {
            $table->dropForeign(['post_id']); // Using array syntax will make Laravel "guess" the index name
        });
    },
];

Check if post exists before applying foriiegn key constraint


<?php
/**
 * The template for displaying the footer
 *
 * Contains footer content and the closing of the #main and #page div elements.
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */
?>

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

				<?php do_action( 'twentyfourteen_credits' ); ?>
				<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyfourteen' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentyfourteen' ), 'WordPress' ); ?>
                Licensed under

	<?php wp_footer(); ?>

Remove SSL warning on CC image

Remove SSL warning on CC image


<?php

date_default_timezone_set('UTC');

require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

require __DIR__.'/../app/config/dev.php';
require __DIR__.'/../app/app.php';
require __DIR__.'/../app/routes.php';

$app->run();

Remove trailing line at end of file

Remove trailing line at end of file


<?php

// If a feature image is set, get the id, so it can be injected as a css background property
if (has_post_thumbnail($post->ID) ) :

    $feat_img_id = get_post_thumbnail_id();
    $hero_img_alt = get_post_meta($feat_img_id, '_wp_attachment_image_alt', true); // get alt attribute

    /* Use ID to get the attachment object */
    $lg_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-large', true); // Large Hero
    $md_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-medium', true); // Medium Hero
    $sm_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-small', true); // Mobile Hero

    /* Grab the url from the attachment object */
    $hero_lg = $lg_hero_array[0]; // Large Hero
    $hero_md = $md_hero_array[0]; // Medium Hero
    $hero_sm = $sm_hero_array[0]; // Mobile Hero

    ?>

    <header id="featured-hero" role="banner"
            data-interchange="[<?php echo $hero_lg; ?>, default], [<?php echo $hero_sm; ?>, small], [<?php echo $hero_md; ?>, medium], [<?php echo $hero_lg; ?>, large]">
    </header>

<?php endif;

<?php

// If a feature image is set, get the id, so it can be injected as a css background property
if (has_post_thumbnail($post->ID) ) :

    $feat_img_id = get_post_thumbnail_id();
    $hero_img_alt = get_post_meta($feat_img_id, '_wp_attachment_image_alt', true); // get alt attribute

    /* Use ID to get the attachment object */
    $lg_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-large', true); // Large Hero
    $md_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-medium', true); // Medium Hero
    $sm_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-small', true); // Mobile Hero

    /* Grab the url from the attachment object */
    $hero_lg = $lg_hero_array[0]; // Large Hero
    $hero_md = $md_hero_array[0]; // Medium Hero
    $hero_sm = $sm_hero_array[0]; // Mobile Hero

    ?>

    <header id="featured-hero" role="banner"
            data-interchange="[<?php echo $hero_sm; ?>, small], [<?php echo $hero_md; ?>, medium], [<?php echo $hero_lg; ?>, large]">
    </header>

<?php endif;

Update featured image Interchange queries

Removed 'default' named media query which
does not exist in Foundation 6.

http://foundation.zurb.com/sites/docs/interchange.html#named-media-queries


<?php

require('../vendor/autoload.php');

$max_data_length = 20010;
// ^ Calculated like so: len("789cae03b53fe955bc6746e7ee0663" + (":o331HlIeYrw:999:999"*999))

if (!array_key_exists('REDIS_URL', $_ENV))
    $_ENV['REDIS_URL'] = "redis://h:@localhost:6379";

$redis = new Predis\Client([
    'host' => parse_url($_ENV['REDIS_URL'], PHP_URL_HOST),
    'port' => parse_url($_ENV['REDIS_URL'], PHP_URL_PORT),
    'password' => parse_url($_ENV['REDIS_URL'], PHP_URL_PASS),
]);

<?php

require('../vendor/autoload.php');

$max_data_length = 20010;
// ^ Calculated like so: len("789cae03b53fe955bc6746e7ee0663" + (":o331HlIeYrw:999:999"*999))

$redis_url = $_ENV['REDIS_URL'];
if (!isset($redis_url))
    $redis_url = "redis://h:@localhost:6379";

$redis = new Predis\Client([
    'host' => parse_url($redis_url, PHP_URL_HOST),
    'port' => parse_url($redis_url, PHP_URL_PORT),
    'password' => parse_url($redis_url, PHP_URL_PASS),
]);

Fix redis environment variable overwriting

On production environments, this command seems to fail


<?php

class CM_Usertext_Filter_MaxLengthTest extends CMTest_TestCase {

	public static function tearDownAfterClass() {
		CMTest_TH::clearEnv();
	}

	public function testProcess() {
		$filter = new CM_Usertext_Filter_MaxLength(10);
		$this->assertSame('Hello…', $filter->transform('Hello World', $this->_getRender()));

		$filter = new CM_Usertext_Filter_MaxLength(11);
		$this->assertSame('Hello World', $filter->transform('Hello World', $this->_getRender()));

		$filter = new CM_Usertext_Filter_MaxLength(12);
		$this->assertSame('Hello World', $filter->transform('Hello World', $this->_getRender()));
	}
}

<?php

class CM_Usertext_Filter_MaxLengthTest extends CMTest_TestCase {

	public static function tearDownAfterClass() {
		CMTest_TH::clearEnv();
	}

	public function testProcess() {
		$filter = new CM_Usertext_Filter_MaxLength(10);
		$this->assertSame('Hello…', $filter->transform('Hello World', $this->_getRender()));

		$filter = new CM_Usertext_Filter_MaxLength(11);
		$this->assertSame('Hello World', $filter->transform('Hello World', $this->_getRender()));

		$filter = new CM_Usertext_Filter_MaxLength(12);
		$this->assertSame('Hello World', $filter->transform('Hello World', $this->_getRender()));
	}

	public function testMultibyte() {
		$filter = new CM_Usertext_Filter_MaxLength(2);
		$this->assertSame('繁體…', $filter->transform('繁體字', $this->_getRender()));
	}
}

Add test about multibyte max length

Add test about multibyte max length


<?php

namespace Hodor\MessageQueue;

use Exception;
use Hodor\MessageQueue\Adapter\Testing\Config;
use Hodor\MessageQueue\Adapter\Testing\Factory;
use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass Hodor\MessageQueue\ProducerQueue
 */
class ProducerQueueTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::push
     */
    public function testMessageCanBeProduced()
    {
        $expected_value = "hi there, " . uniqid();
        $pusher = function ($message) use ($expected_value) {
            $this->assertSame($expected_value, $message);
        };

        $producer_queue = new ProducerQueue($pusher);
        $producer_queue->push($expected_value);
    }
}

<?php

namespace Hodor\MessageQueue;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass Hodor\MessageQueue\ProducerQueue
 */
class ProducerQueueTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::push
     */
    public function testMessageCanBeProduced()
    {
        $expected_value = "hi there, " . uniqid();
        $pusher = function ($message) use ($expected_value) {
            $this->assertSame($expected_value, $message);
        };

        $producer_queue = new ProducerQueue($pusher);
        $producer_queue->push($expected_value);
    }
}

Remove unused imports from ProducerQueue


<?php

use Widmogrod\Monad\Maybe\Just;
use Widmogrod\Primitive\Listt;

class MaybeMonoidTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideData
     */
    public function test_it_should_concat_only_just_values($data, $expected)
    {
        $makeMaybeMonoid = function ($val) {
            return \Widmogrod\Monad\Maybe\maybeNull($val)->map(Listt::of);
        };

        $names = array_values(array_map($makeMaybeMonoid, $data));

        list($firstName, $middleName, $lastName) = $names;

        $fullName = $firstName->concat($middleName)->concat($lastName);
        $fullNameFromReduce = array_reduce($names, \Widmogrod\Functional\concatM, \Widmogrod\Monad\Maybe\Nothing::mempty());

        $this->assertInstanceOf(Just::class, $fullName);
        $this->assertEquals($fullName->extract()->extract(), $expected);
        $this->assertEquals($fullNameFromReduce->extract()->extract(), $expected);
    }

    public function provideData()
    {
        return [
            [
                '$data'     => ['firstName' => 'First', 'middleName' => null, 'lastName' => 'Last'],
                '$expected' => ['First', 'Last']
            ],
            [
                '$data'     => ['firstName' => 'First', 'middleName' => 'Middle', 'lastName' => 'Last'],
                '$expected' => ['First', 'Middle', 'Last']
            ]
        ];
    }
}

<?php

use Widmogrod\Functional as f;
use Widmogrod\Monad\Maybe as m;
use Widmogrod\Primitive\Listt;

class MaybeMonoidTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideData
     */
    public function test_it_should_concat_only_just_values($data, $expected)
    {
        $makeMaybeMonoid = function ($val) {
            return m\maybeNull($val)->map(Listt::of);
        };

        $names = array_values(array_map($makeMaybeMonoid, $data));

        list($firstName, $middleName, $lastName) = $names;

        $fullName = $firstName->concat($middleName)->concat($lastName);
        $fullNameFromReduce = array_reduce($names, f\concatM, m\Nothing::mempty());

        $this->assertInstanceOf(Just::class, $fullName);
        $this->assertEquals($fullName->extract()->extract(), $expected);
        $this->assertEquals($fullNameFromReduce->extract()->extract(), $expected);
    }

    public function provideData()
    {
        return [
            [
                '$data'     => ['firstName' => 'First', 'middleName' => null, 'lastName' => 'Last'],
                '$expected' => ['First', 'Last']
            ],
            [
                '$data'     => ['firstName' => 'First', 'middleName' => 'Middle', 'lastName' => 'Last'],
                '$expected' => ['First', 'Middle', 'Last']
            ]
        ];
    }
}

Apply coding standard fixes for namespace imports


<?php

namespace Kibo\Phast\Filters\HTML;

use Kibo\Phast\ValueObjects\URL;

class CSSImagesOptimizationServiceHTMLFilter extends ImagesOptimizationServiceHTMLFilter {

    public function transformHTMLDOM(\DOMDocument $document) {
        $styleTags = $document->getElementsByTagName('style');
        /** @var \DOMElement $styleTag */
        foreach ($styleTags as $styleTag) {
            $styleTag->textContent = $this->rewriteStyle($styleTag->textContent);
        }

        $styleAttrs = (new \DOMXPath($document))->query('//@style');
        /** @var \DOMAttr $styleAttr */
        foreach ($styleAttrs as $styleAttr) {
            $styleAttr->value = htmlspecialchars($this->rewriteStyle($styleAttr->value));
        }
    }

    private function rewriteStyle($styleContent) {
        return preg_replace_callback(
            '~
                (
                    \b (?: image | background ):
                    [^;}]*
                    \b url \( [:\'"]?
                )
                (
                    [^\'")] +
                )
            ~xi',
            function ($matches) {
                $params = ['src' => (string) URL::fromString($matches[2])->withBase($this->baseUrl)];
                return $matches[1] . $this->makeSignedUrl($this->serviceUrl, $params, $this->signature);
            },
            $styleContent
        );
    }

}

<?php

namespace Kibo\Phast\Filters\HTML;

use Kibo\Phast\ValueObjects\URL;

class CSSImagesOptimizationServiceHTMLFilter extends ImagesOptimizationServiceHTMLFilter {

    public function transformHTMLDOM(\DOMDocument $document) {
        $styleTags = $document->getElementsByTagName('style');
        /** @var \DOMElement $styleTag */
        foreach ($styleTags as $styleTag) {
            $styleTag->textContent = $this->rewriteStyle($styleTag->textContent);
        }

        $styleAttrs = (new \DOMXPath($document))->query('//@style');
        /** @var \DOMAttr $styleAttr */
        foreach ($styleAttrs as $styleAttr) {
            $styleAttr->value = htmlspecialchars($this->rewriteStyle($styleAttr->value));
        }
    }

    private function rewriteStyle($styleContent) {
        return preg_replace_callback(
            '~
                (
                    \b (?: image | background ):
                    [^;}]*
                    \b url \( [\'"]?
                )
                (
                    [^\'")] +
                )
            ~xi',
            function ($matches) {
                $params = ['src' => (string) URL::fromString($matches[2])->withBase($this->baseUrl)];
                return $matches[1] . $this->makeSignedUrl($this->serviceUrl, $params, $this->signature);
            },
            $styleContent
        );
    }

}

Remove extraneous colon from url(...) regex


<?php

return [
    'route' => 'warden',
    'auth' => [
        /*
         * Set this to your own custom middleware, just please know that it
         * should ensure that the user is logged in.
         */
        'middleware' => Kregel\Warden\Http\Middleware\Authentication::class,
        'middleware_name' => 'custom-auth',
        /*
         * Name of a login route, it's recommended to have it named, but incase
         * that doesn't work we have the 'fail_over_route' config to choose.
         */
        'route' => 'login',
        /*
         * If the desired route does not exist then use the one below instead
         * If you plan to use this with Spark, edi the fail_over_route to
         * /login  instead of /auth/login
         */
        'fail_over_route' => '/auth/login',
    ],
    /*
     * Actual application configuration
     */
    'using' => [
        'fontawesome' => true,
        'csrf' => true,
    ],
    'views' => [
        'base-layout' => 'spark::layouts.app',
    ],
    /**
     * Just to make sure that there are fewer things to edit,
     * by default we use the auth.model configuration from
     * the default location to ensure this will work oob
     */
    'models' => [
        'user' => [
            // For model events themselves, please reference the
            // Eloquent events from the laravel docs website.
            // Can be seen here: https://laravel.com/docs/5.1/eloquent#events
            'model' => App\Models\User::class,
            'relations' => [
                'roles' => [
                    'update' => function($user){
                        \Log::info('A users roles has been updated');
                    },
                    'new' => function ($user){
                        \Log::info('A users role has been created');
                    },
                    'delete' => function ($user){
                        \Log::info('A users role has been deleted/removed');
                    }
                ]
            ]
        ],

    ],
];

<?php

return [
    'route' => 'warden',
    'auth' => [
        /*
         * Set this to your own custom middleware, just please know that it
         * should ensure that the user is logged in.
         */
        'middleware' => ['web', 'auth'],

        'middleware_api' => ['api'],

    ],
    'views' => [
        'base-layout' => 'spark::layouts.app',
    ],
    /**
     * Just to make sure that there are fewer things to edit,
     * by default we use the auth.model configuration from
     * the default location to ensure this will work oob
     */
    'models' => [
        'user' => [
            // For model events themselves, please reference the
            // Eloquent events from the laravel docs website.
            // Can be seen here: https://laravel.com/docs/master/eloquent#events
            'model' => App\Models\User::class,
            'relations' => [
                'roles' => [
                    'update' => function($user){
                        \Log::info('A users roles has been updated');
                    },
                    'new' => function ($user){
                        \Log::info('A users role has been created');
                    },
                    'delete' => function ($user){
                        \Log::info('A users role has been deleted/removed');
                    }
                ]
            ]
        ],

    ],
];

Remove unused middleware stuff and add model events


<?php

namespace Routify;

abstract class Method {
    const GET = "GET";
    const POST = "POST";
    const PUT = "PUT";
    const DELETE = "DELETE";
}

Refactor the project from SimpleRouter to Routify


<?php namespace Cviebrock\LaravelElasticsearch;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

/**
 * Class ServiceProvider
 *
 * @package Cviebrock\LaravelElasticsearch
 */
class LumenServiceProvider extends BaseServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $app = $this->app;

        $app->singleton('elasticsearch.factory', function($app) {
            return new Factory();
        });

        $app->singleton('elasticsearch', function($app) {
            return new LumenManager($app, $app['elasticsearch.factory']);
        });

        $this->withFacades();
    }

    protected function withFacades()
    {
        class_alias('\Cviebrock\LaravelElasticsearch\Facade', 'Elasticsearch');
    }
}

<?php namespace Cviebrock\LaravelElasticsearch;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

/**
 * Class ServiceProvider
 *
 * @package Cviebrock\LaravelElasticsearch
 */
class LumenServiceProvider extends BaseServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $app = $this->app;

        $app->singleton('elasticsearch.factory', function($app) {
            return new Factory();
        });

        $app->singleton('elasticsearch', function($app) {
            return new LumenManager($app, $app['elasticsearch.factory']);
        });

        $app->alias('elasticsearch', LumenManager::class);

        $this->withFacades();
    }

    protected function withFacades()
    {
        class_alias('\Cviebrock\LaravelElasticsearch\Facade', 'Elasticsearch');
    }
}

Support class injection of elasticsearch


<?php namespace Jigsaw\Jigsaw\Console;

use Illuminate\Contracts\View\Factory;
use Illuminate\Filesystem\Filesystem;
use Jigsaw\Jigsaw\Jigsaw;
use Jigsaw\Jigsaw\Template;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class BuildCommand extends \Symfony\Component\Console\Command\Command
{
    private $sourcePath;
    private $buildPath;
    private $jigsaw;

    public function __construct($jigsaw, $sourcePath, $buildPath)
    {
        $this->sourcePath = $sourcePath;
        $this->buildPath = $buildPath;
        $this->jigsaw = $jigsaw;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('build')->setDescription('Build your site.');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        return (int) $this->fire();
    }

    protected function fire()
    {
        $this->jigsaw->build($this->sourcePath, $this->buildPath);
    }
}

<?php namespace Jigsaw\Jigsaw\Console;

use Illuminate\Contracts\View\Factory;
use Illuminate\Filesystem\Filesystem;
use Jigsaw\Jigsaw\Jigsaw;
use Jigsaw\Jigsaw\Template;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class BuildCommand extends \Symfony\Component\Console\Command\Command
{
    private $sourcePath;
    private $buildPath;
    private $jigsaw;

    public function __construct($jigsaw, $sourcePath, $buildPath)
    {
        $this->sourcePath = $sourcePath;
        $this->buildPath = $buildPath;
        $this->jigsaw = $jigsaw;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('build')->setDescription('Build your site.');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        return (int) $this->fire();
    }

    protected function fire()
    {
        $this->jigsaw->build($this->sourcePath, $this->buildPath);
        $this->output->writeln('<info>Site built successfully!</info>');
    }

    private function info($string)
    {
        $this->output->writeln("<info>{$string}</info>");
    }

    private function error($string)
    {
        $this->output->writeln("<error>{$string}</error>");
    }

    private function comment($string)
    {
        $this->output->writeln("<comment>{$string}</comment>");
    }
}

Add success message on build

Add success message on build


<?php

namespace Pocs\View;

class ViewHelper
{
    /**
     * @param $bytes
     * @return string
     */
    public function sizeForHumans($bytes)
    {
        if ($bytes > 1048576) {
            return sprintf('%.2f MB', $bytes / 1048576);
        } else {
            if ($bytes > 1024) {
                return sprintf('%.2f kB', $bytes / 1024);
            } else {
                return sprintf('%d bytes', $bytes);
            }
        }
    }

    /**
     * @param $number
     * @return string
     */
    public function formatNumber($number)
    {
        if (class_exists('NumberFormatter')) {
            $a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
            echo $a->format($number);
        }

        return $number;
    }
}

<?php

namespace Pocs\View;

class ViewHelper
{
    /**
     * @param $bytes
     * @return string
     */
    public function sizeForHumans($bytes)
    {
        if ($bytes > 1048576) {
            return sprintf('%.2f MB', $bytes / 1048576);
        } else {
            if ($bytes > 1024) {
                return sprintf('%.2f kB', $bytes / 1024);
            } else {
                return sprintf('%d bytes', $bytes);
            }
        }
    }

    /**
     * @param $number
     * @return string
     */
    public function formatNumber($number)
    {
        if (class_exists('NumberFormatter')) {
            $a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
            return $a->format($number);
        }

        return $number;
    }
}

Replace the echo with return

Replace the echo with return


<?php

namespace Rogue\Http\Transformers;

use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;

class PhoenixGalleryTransformer extends TransformerAbstract
{
    /**
     * Transform resource data.
     *
     * @param \Rogue\Models\Photo $photo
     * @return array
     */
    public function transform(Post $post)
    {
        $signup = $post->signup;
        $result = [
            'id' => $post->postable_id,
            'status' => $post->status,
            'caption' => $post->content->caption,
            'uri' => $post->content->file_url,
            'media' => [
                'uri' => $post->content->file_url,
                'type' => 'image',
            ],
            'created_at' => $post->created_at->toIso8601String(),
            'reportback' => [
                'id' => $signup->id,
                'created_at' => $signup->created_at->toIso8601String(),
                'updated_at' => $signup->updated_at->toIso8601String(),
                'quantity' => $signup->quantity,
                'why_participated' => $signup->why_participated,
                'flagged' => 'false',
            ],
        ];

        return $result;
    }
}

<?php

namespace Rogue\Http\Transformers;

use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;

class PhoenixGalleryTransformer extends TransformerAbstract
{
    /**
     * Transform resource data.
     *
     * @param \Rogue\Models\Photo $photo
     * @return array
     */
    public function transform(Post $post)
    {
        $signup = $post->signup;
        $result = [
            'id' => $post->postable_id,
            'status' => $post->status,
            'caption' => $post->caption,
            'uri' => $post->file_url,
            'media' => [
                'uri' => $post->file_url,
                'type' => 'image',
            ],
            'created_at' => $post->created_at->toIso8601String(),
            'reportback' => [
                'id' => $signup->id,
                'created_at' => $signup->created_at->toIso8601String(),
                'updated_at' => $signup->updated_at->toIso8601String(),
                'quantity' => $signup->quantity,
                'why_participated' => $signup->why_participated,
                'flagged' => 'false',
            ],
        ];

        return $result;
    }
}

Update to use new schema

Update to use new schema


<?php

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

class MakeTeamNameNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->boolean('name')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->boolean('name')->nullable(false)->change();
        });
    }
}

<?php

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

class MakeTeamNameNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->text('name')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->text('name')->nullable(false)->change();
        });
    }
}

Fix typo in migration file

Fix typo in migration file


<?php

namespace App\Http\Transformers;

use App\Models\Collections\ArtworkCatalogue;

class ArtworkCatalogueTransformer extends CollectionsTransformer
{

    public $excludeDates = true;
    public $excludeIdsAndTitle = true;

    /**
     * Turn this item object into a generic array.
     *
     * @param  \App\Agent  $item
     * @return array
     */
    public function transformFields($item)
    {
        return [
            'is_preferred' => (bool) $item->preferred,
            'catalogue' => $item->catalogue,
            'number' => $item->number,
            'state_edition' => $item->state_edition,
        ];
    }

}

<?php

namespace App\Http\Transformers;

use App\Models\Collections\ArtworkCatalogue;

class ArtworkCatalogueTransformer extends CollectionsTransformer
{

    public $excludeDates = true;
    public $excludeIdsAndTitle = true;

}

Fix override of ArtworkCatalogue's transform

The model has an outbound structure that mimics the other pivot models,
but this outbound transformer was overwriting that output.


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

class AddTest extends WebTestCase
{
    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/content_blocks/index');

        // we should get redirected to authentication with a reference to blog index in our url
        self::assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fcontent_blocks%2Findex',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testFormIsDisplayed(): void
    {
        $client = static::createClient();
        $this->login($client);

        $client->request('GET', '/private/en/content_blocks/add');
        self::assertContains(
            'Title    <abbr data-toggle="tooltip" aria-label="Required field" title="Required field">*</abbr>',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Visible on site',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Add content block',
            $client->getResponse()->getContent()
        );
    }
}

<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

class AddTest extends WebTestCase
{
    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/content_blocks/index');

        // we should get redirected to authentication with a reference to blog index in our url
        self::assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fcontent_blocks%2Findex',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testFormIsDisplayed(): void
    {
        $client = static::createClient();
        $this->login($client);

        $client->request('GET', '/private/en/content_blocks/add');
        self::assertContains(
            'Title<abbr data-toggle="tooltip" aria-label="Required field" title="Required field">*</abbr>',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Visible on site',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Add content block',
            $client->getResponse()->getContent()
        );
    }
}

Fix test that took the spacing into account


<?php

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules([
        '@Symfony' => true,
        '@Symfony:risky' => true,
        'array_syntax' => [
            'syntax' => 'short'
        ],
        'combine_consecutive_unsets' => true,
        'heredoc_to_nowdoc' => true,
        'no_extra_blank_lines' => [
            'tokens' => [
                'break',
                'continue',
                'extra',
                'return',
                'throw',
                'use',
                'parenthesis_brace_block',
                'square_brace_block',
                'curly_brace_block'
            ],
        ],
        'no_unreachable_default_argument_value' => true,
        'no_useless_else' => true,
        'no_useless_return' => true,
        'ordered_class_elements' => true,
        'ordered_imports' => true,
        'php_unit_strict' => true,
        'phpdoc_order' => true,
        // 'psr_autoloading' => true,
        'strict_comparison' => true,
        'strict_param' => true,
        'concat_space' => [
            'spacing' => 'one'
        ],
    ])
    ->setFinder(
        PhpCsFixer\Finder::create()
            ->exclude([
                'node_modules',
                'vendor',
                'var',
                'web'
            ])
            ->in(__DIR__)
    )
    ->setCacheFile('.php-cs-fixer.cache')
;

<?php

$config = new PhpCsFixer\Config();
return $config
    ->setRiskyAllowed(true)
    ->setRules([
        '@Symfony' => true,
        '@Symfony:risky' => true,
        'array_syntax' => [
            'syntax' => 'short'
        ],
        'combine_consecutive_unsets' => true,
        'heredoc_to_nowdoc' => true,
        'no_extra_blank_lines' => [
            'tokens' => [
                'break',
                'continue',
                'extra',
                'return',
                'throw',
                'use',
                'parenthesis_brace_block',
                'square_brace_block',
                'curly_brace_block'
            ],
        ],
        'no_unreachable_default_argument_value' => true,
        'no_useless_else' => true,
        'no_useless_return' => true,
        'ordered_class_elements' => true,
        'ordered_imports' => true,
        'php_unit_strict' => true,
        'phpdoc_order' => true,
        // 'psr_autoloading' => true,
        'strict_comparison' => true,
        'strict_param' => true,
        'concat_space' => [
            'spacing' => 'one'
        ],
    ])
    ->setFinder(
        PhpCsFixer\Finder::create()
            ->exclude([
                'node_modules',
                'vendor',
                'var',
                'web'
            ])
            ->in(__DIR__)
    )
    ->setCacheFile('.php-cs-fixer.cache')
;

Use Config constructor instead of deprecated named one


<?php

$rules = [
    '@Symfony' => true,
    'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
    'phpdoc_to_comment' => false,
    'phpdoc_align' => false,
    'php_unit_method_casing' => false,
];

$finder = PhpCsFixer\Finder::create()
    ->in([
        __DIR__.'/src',
        __DIR__.'/tests',
    ])
    ->notPath('FormattingTestClass.php')
    ->notPath('function_names.php')
;

$config = new PhpCsFixer\Config();
$config
    ->setFinder($finder)
    ->setRiskyAllowed(true)
    ->setRules($rules)
    ->setUsingCache(true)
;

return $config;

<?php

$rules = [
    '@Symfony' => true,
    'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
    'phpdoc_to_comment' => false,
    'phpdoc_align' => false,
    'php_unit_method_casing' => false,
    'phpdoc_separation' => ['groups' => [['test', 'dataProvider', 'covers']]],
];

$finder = PhpCsFixer\Finder::create()
    ->in([
        __DIR__.'/src',
        __DIR__.'/tests',
    ])
    ->notPath('FormattingTestClass.php')
    ->notPath('function_names.php')
;

$config = new PhpCsFixer\Config();
$config
    ->setFinder($finder)
    ->setRiskyAllowed(true)
    ->setRules($rules)
    ->setUsingCache(true)
;

return $config;

Add php-cs-fixer config for test annotations


<?php

declare(strict_types=1);

namespace Tests;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use LaravelZero\Framework\Contracts\Providers\ComposerContract;

final class HttpComponentTest extends TestCase
{
    /** @test */
    public function it_installs_the_required_packages(): void
    {
        $composerMock = $this->createMock(ComposerContract::class);

        $composerMock->expects($this->exactly(2))
            ->method('require')
            ->withConsecutive(
                [$this->equalTo('guzzlehttp/guzzle "^6.3.1"')],
                [$this->equalTo('illuminate/http "^7.0"')]
            );

        $this->app->instance(ComposerContract::class, $composerMock);

        Artisan::call('app:install', ['component' => 'http']);
    }

    /** @test */
    public function it_can_use_the_http_client(): void
    {
        Http::fake();

        Http::withHeaders([
            'X-Faked' => 'enabled',
        ])->get('https://faked.test');

        Http::assertSent(function ($request) {
            return $request->hasHeader('X-Faked', 'enabled')
                && $request->url('https://faked.test');
        });
    }
}

<?php

declare(strict_types=1);

namespace Tests;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use LaravelZero\Framework\Contracts\Providers\ComposerContract;

final class HttpComponentTest extends TestCase
{
    /** @test */
    public function it_installs_the_required_packages(): void
    {
        $composerMock = $this->createMock(ComposerContract::class);

        $composerMock->expects($this->exactly(2))
            ->method('require')
            ->withConsecutive(
                [$this->equalTo('guzzlehttp/guzzle "^6.3.1"')],
                [$this->equalTo('illuminate/http "^7.0"')]
            );

        $this->app->instance(ComposerContract::class, $composerMock);

        Artisan::call('app:install', ['component' => 'http']);
    }

    /** @test */
    public function it_can_use_the_http_client(): void
    {
        Http::fake();

        $response = Http::withHeaders([
            'X-Faked' => 'enabled',
        ])->get('https://faked.test');

        Http::assertSent(function ($request) {
            return $request->hasHeader('X-Faked', 'enabled')
                && $request->url('https://faked.test');
        });

        $this->assertTrue($response->ok());
        $this->assertEmpty($response->body());
    }
}

Add assertions for the Http client response


<?php
class RelatedFileForm extends BaseForm
{
  public function configure()
  {
    $this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
    $this->widgetSchema['filenames']->setLabel("Add File") ;
    $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
    $this->validatorSchema['filenames'] = new sfValidatorFile(
      array(
          'required' => false,
          //'mime_type_guessers' => array('guessFromFileinfo'),
          'validated_file_class' => 'myValidatedFile'
      ));
    $this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
    array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
    array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
    array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
  ));
  }

}

<?php
class RelatedFileForm extends BaseForm
{
  public function configure()
  {
    $this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
    $this->widgetSchema['filenames']->setLabel("Add File") ;
    $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
    $this->validatorSchema['filenames'] = new sfValidatorFile(
      array(
          'required' => true,
          //'mime_type_guessers' => array('guessFromFileinfo'),
          'validated_file_class' => 'myValidatedFile'
      ));
    $this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
    array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
    array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
    array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
  ));
  }

}

Set required in files related

Set required in files related


<?php
namespace Wisembly\AmqpBundle\DataCollector;

use Exception;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;

/**
 * Collect all the data when sending a message through our publisher
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class AMQPDataCollector extends DataCollector
{
    private $messages = [];

    public function __construct()
    {
        $this->data = ['count' => 0,
                       'messages' => []];
    }

    public function collect(Request $request, Response $response, Exception $exception = null)
    {
        $this->data = ['messages' => $this->messages,
                       'count'    => count($this->messages)];
    }

    /**
     * Add some data to the collector
     *
     * @param string[] $data message to collect
     */
    public function addMessage(array $data)
    {
        $this->messages[] = $data;
    }

    public function getMessages()
    {
        return $this->data['messages'];
    }

    public function getCount()
    {
        return $this->data['count'];
    }

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

<?php
namespace Wisembly\AmqpBundle\DataCollector;

use Exception;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;

/**
 * Collect all the data when sending a message through our publisher
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class AMQPDataCollector extends DataCollector
{
    private $messages = [];

    public function __construct()
    {
        $this->data = ['count' => 0,
                       'messages' => []];
    }

    public function collect(Request $request, Response $response, Exception $exception = null)
    {
        $this->data = ['messages' => $this->messages,
                       'count'    => count($this->messages)];
    }

    public function reset()
    {
        $this->data = ['count' => 0,
                       'messages' => []];
    }

    /**
     * Add some data to the collector
     *
     * @param string[] $data message to collect
     */
    public function addMessage(array $data)
    {
        $this->messages[] = $data;
    }

    public function getMessages()
    {
        return $this->data['messages'];
    }

    public function getCount()
    {
        return $this->data['count'];
    }

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

Add reset method on the data collector (sf4)


<?php

declare(strict_types=1);

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

class CreateSessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('session.table'), function (Blueprint $table) {
            // Columns
            $table->string('id')->unique();
            $table->integer('user_id')->unsigned()->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->text('payload');
            $table->integer('last_activity');

            // Indexes
            $table->unique('id');
            $table->foreign('user_id')->references('id')->on(config('rinvex.fort.tables.users'))->onDelete('cascade')->onUpdate('cascade');
        });
    }

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

<?php

declare(strict_types=1);

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

class CreateSessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('session.table'), function (Blueprint $table) {
            // Columns
            $table->string('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->text('payload');
            $table->integer('last_activity');

            // Indexes
            $table->unique('id');
            $table->foreign('user_id')->references('id')->on(config('rinvex.fort.tables.users'))->onDelete('cascade')->onUpdate('cascade');
        });
    }

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

Fix duplicate unique index issue

Fix duplicate unique index issue


<?php

namespace WP_CLI\Fetchers;

use WP_User;

/**
 * Fetch a WordPress user based on one of its attributes.
 */
class User extends Base {

	/**
	 * The message to display when an item is not found.
	 *
	 * @var string
	 */
	protected $msg = "Invalid user ID, email or login: '%s'";

	/**
	 * Get a user object by one of its identifying attributes.
	 *
	 * @param string $arg The raw CLI argument.
	 * @return WP_User|false The item if found; false otherwise.
	 */
	public function get( $arg ) {

		if ( is_numeric( $arg ) ) {
			$users = get_users( [ 'include' => [ (int) $arg ] ] );
		} elseif ( is_email( $arg ) ) {
			$users = get_users(
				[
					'search'         => $arg,
					'search_columns' => 'user_email',
				]
			);
			// Logins can be emails.
			if ( ! $user ) {
				$users = get_users( [ 'login' => $arg ] );
			}
		} else {
			$users = get_users( [ 'login' => $arg ] );
		}

		return is_array( $users ) ? $users[0] : false;
	}
}

<?php

namespace WP_CLI\Fetchers;

use WP_User;

/**
 * Fetch a WordPress user based on one of its attributes.
 */
class User extends Base {

	/**
	 * The message to display when an item is not found.
	 *
	 * @var string
	 */
	protected $msg = "Invalid user ID, email or login: '%s'";

	/**
	 * Get a user object by one of its identifying attributes.
	 *
	 * @param string $arg The raw CLI argument.
	 * @return WP_User|false The item if found; false otherwise.
	 */
	public function get( $arg ) {

		if ( is_numeric( $arg ) ) {
			$users = get_users( [ 'include' => [ (int) $arg ] ] );
		} elseif ( is_email( $arg ) ) {
			$users = get_users(
				[
					'search'         => $arg,
					'search_columns' => [ 'user_email' ],
				]
			);
			// Logins can be emails.
			if ( ! $user ) {
				$users = get_users( [ 'login' => $arg ] );
			}
		} else {
			$users = get_users( [ 'login' => $arg ] );
		}

		return is_array( $users ) ? $users[0] : false;
	}
}

Use array for search columns

Use array for search columns


<?php

namespace Stripe;

class BankAccountTest extends TestCase
{
    public function testVerify()
    {
        self::authorizeFromEnv();

        $customer = self::createTestCustomer();

        $bankAccount = $customer->sources->create([
            'source' => [
                'object' => 'bank_account',
                'account_number' => '000123456789',
                'routing_number' => '110000000',
                'country' => 'US'
            ]
        ]);

        $this->assertSame($bankAccount->status, 'new');

        $bankAccount = $bankAccount->verify([
            'amounts' => [32, 45]
        ]);

        $this->assertSame($bankAccount->status, 'verified');
    }
}

<?php

namespace Stripe;

class BankAccountTest extends TestCase
{
    public function testVerify()
    {
        self::authorizeFromEnv();

        $customer = self::createTestCustomer();

        $bankAccount = $customer->sources->create(array(
            'source' => array(
                'object' => 'bank_account',
                'account_number' => '000123456789',
                'routing_number' => '110000000',
                'country' => 'US'
            )
        ));

        $this->assertSame($bankAccount->status, 'new');

        $bankAccount = $bankAccount->verify(array(
            'amounts' => array(32, 45)
        ));

        $this->assertSame($bankAccount->status, 'verified');
    }
}

Use verbose array syntax for PHP 5.3

Use verbose array syntax for PHP 5.3


<?php

use Flintstone\Cache\ArrayCache;

class ArrayCacheTest extends PHPUnit_Framework_TestCase
{
    public function testGetAndSet()
    {
        $cache = new ArrayCache();
        $cache->set('foo', 'bar');
        $this->assertTrue($cache->contains('foo'));
        $this->assertEquals('bar', $cache->get('foo'));
    }

    public function testDelete()
    {
        $cache = new ArrayCache();
        $cache->set('foo', 'bar');
        $cache->delete('foo');
        $this->assertFalse($cache->contains('foo'));
    }

    public function testFlush()
    {
        $cache = new ArrayCache();
        $cache->set('foo', 'bar');
        $cache->flush();
        $this->assertFalse($cache->contains('foo'));
    }
}

<?php

use Flintstone\Cache\ArrayCache;

class ArrayCacheTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var ArrayCache
     */
    private $cache;

    protected function setUp()
    {
        $this->cache = new ArrayCache();
    }

    public function testGetAndSet()
    {
        $this->cache->set('foo', 'bar');
        $this->assertTrue($this->cache->contains('foo'));
        $this->assertEquals('bar', $this->cache->get('foo'));
    }

    public function testDelete()
    {
        $this->cache->set('foo', 'bar');
        $this->cache->delete('foo');
        $this->assertFalse($this->cache->contains('foo'));
    }

    public function testFlush()
    {
        $this->cache->set('foo', 'bar');
        $this->cache->flush();
        $this->assertFalse($this->cache->contains('foo'));
    }
}

Use setUp method for cache

Use setUp method for cache