<?php
namespace Intercom;

use InvalidArgumentException;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class IntercomBasicAuthClient extends Client
{
    /**
     * Creates a Basic Auth Client with the supplied configuration options
     *
     * @param array $config
     * @return Client|IntercomBasicAuthClient
     */
    public static function factory($config = [])
    {
        $default = [
            'service_description' => __DIR__ . '/Service/config/intercom.json',
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/vnd.intercom.3+json'
            ]
        ];

        $required = [
            'app_id',
            'api_key',
            'headers',
            'service_description'
        ];

        $config = Collection::fromConfig($config, $default, $required);
        $client = new self();

        $client->setDefaultOption('headers', $config->get('headers'));

        $client->setDefaultOption('auth', [
            $config->get('app_id'),
            $config->get('api_key'),
            'Basic'
        ]);

        $client->setDescription(static::getServiceDescriptionFromFile($config->get('service_description')));

        return $client;
    }

    /**
     * Loads the service description from the service description file
     *
     * @param string $description_file The service description file
     * @return ServiceDescription
     * @throws InvalidArgumentException If the description file doesn't exist or cannot be read
     */
    public function getServiceDescriptionFromFile($description_file) {
        if (!file_exists($description_file) || !is_readable($description_file)) {
            throw new InvalidArgumentException('Unable to read API definition schema');
        }

        return ServiceDescription::factory($description_file);
    }
}

<?php
namespace Intercom;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;

class IntercomBasicAuthClient extends IntercomAbstractClient
{
    /** @var array The required config variables for this type of client */
    private static $required = ['app_id', 'api_key', 'headers', 'service_description'];

    /**
     * Creates a Basic Auth Client with the supplied configuration options
     *
     * @param array $config
     * @return Client|IntercomBasicAuthClient
     */
    public static function factory($config = [])
    {
        $default = [
            'service_description' => __DIR__ . '/Service/config/intercom.json',
            'headers' => [
                'Content-Type' => self::DEFAULT_CONTENT_TYPE,
                'Accept' => self::DEFAULT_ACCEPT_HEADER
            ]
        ];

        $config = Collection::fromConfig($config, $default, static::$required);
        $client = new self();

        $client->setDefaultOption('headers', $config->get('headers'));

        $client->setDefaultOption('auth', [
            $config->get('app_id'),
            $config->get('api_key'),
            'Basic'
        ]);

        $client->setDescription(static::getServiceDescriptionFromFile($config->get('service_description')));

        return $client;
    }
}

Refactor BasicAuth to extend the abstract client


<?php
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2002 University of Utah and the Flux Group.
# All rights reserved.
#
require("defs.php3");

#
# Anyone can run this page. No login is needed.
#
PAGEHEADER("Download the latest CD image");

?>
If you have a CD-R drive you can burn your own installation disk.

The latest CD image is netbed-0.1.iso.
<?php
#
# Standard Footer.
#
PAGEFOOTER();

<?php
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2002 University of Utah and the Flux Group.
# All rights reserved.
#
require("defs.php3");

#
# Anyone can run this page. No login is needed.
#
PAGEHEADER("Download the latest CD image");

?>
If you have a CD-R drive you can burn your own installation disk.

The latest CD image is netbed-0.2.iso.
<?php
#
# Standard Footer.
#
PAGEFOOTER();

Switch to new 0.2 netbed CDROM.

Switch to new 0.2 netbed CDROM.


<?php

namespace Trexology\Pointable\Models;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    /**
     * @var string
     */
    protected $table = 'point_transactions';

    /**
     * @var array
     */
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function pointable()
    {
        return $this->morphTo();
    }

    /**
     * @param Model $pointable
     *
     * @return static
     */
     public function getCurrentPoints(Model $pointable)
     {
         $currentPoint = Transaction::
         where('pointable_id', $pointable->id)
         ->where('pointable_type', get_class($pointable))
         ->orderBy('created_at', 'desc')
         ->lists('current')->first();

         if (!$currentPoint) {
           $currentPoint = 0.0;
         }

         return $currentPoint;
     }

    /**
     * @param Model $pointable
     * @param $amount
     * @param $message
     * @param $data
     *
     * @return static
     */
    public function addTransaction(Model $pointable, $amount, $message, $data = null)
    {
        $transaction = new static();
        $transaction->amount = $amount;

        $transaction->current = $this->getCurrentPoints($pointable) + $amount;

        $transaction->message = $message;
        if ($data) {
          $transaction->fill($data);
        }
        // $transaction->save();
        $pointable->transactions()->save($transaction);

        return $transaction;
    }
}

<?php

namespace Trexology\Pointable\Models;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    /**
     * @var string
     */
    protected $table = 'point_transactions';

    /**
     * @var array
     */
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function pointable()
    {
        return $this->morphTo();
    }

    /**
     * @param Model $pointable
     *
     * @return static
     */
     public function getCurrentPoints(Model $pointable)
     {
         $currentPoint = Transaction::
         where('pointable_id', $pointable->id)
         ->where('pointable_type', $pointable->getMorphClass())
         ->orderBy('created_at', 'desc')
         ->lists('current')->first();

         if (!$currentPoint) {
           $currentPoint = 0.0;
         }

         return $currentPoint;
     }

    /**
     * @param Model $pointable
     * @param $amount
     * @param $message
     * @param $data
     *
     * @return static
     */
    public function addTransaction(Model $pointable, $amount, $message, $data = null)
    {
        $transaction = new static();
        $transaction->amount = $amount;

        $transaction->current = $this->getCurrentPoints($pointable) + $amount;

        $transaction->message = $message;
        if ($data) {
          $transaction->fill($data);
        }
        // $transaction->save();
        $pointable->transactions()->save($transaction);

        return $transaction;
    }
}

Use Eloquent::getMorphClass() instead of get_class() for Morph Map support.


<?php

namespace Agento;

class Message {
	protected $identifier;
	protected $probability;

	public function __construct($identifier, $probability) {
		$this->identifier = $identifier;
		$this->probability = $probability;
	}

	protected static function encodeFloat($number) {
		if (is_float($number)) {
			// Note that %f is locale specific
			$encoded = sprintf('%F', $number);

			// Remove excess traling zeroes
			$encoded = preg_replace('/(\.[0-9]+?)0*$/', '$1', $encoded);
		} else {
			$encoded = 'null';
		}

		return $encoded;
	}

	public function getBaseObject($type, $tags) {
		$obj = ['t' => $type, 'i' => $this->identifier, 'p' => $this->probability];

		if (count($tags) > 0) {
			$obj['T'] = $tags;
		}

		return $obj;
	}
}

?>

<?php

namespace Agento;

class Message {
	protected $identifier;
	protected $probability;

	public function __construct($identifier, $probability) {
		$this->identifier = $identifier;
		$this->probability = $probability;
	}

	protected static function encodeFloat($number) {
		if (is_float($number) || is_int($number)) {
			// Note that %f is locale specific
			$encoded = sprintf('%F', $number);

			// Remove excess traling zeroes
			$encoded = preg_replace('/(\.[0-9]+?)0*$/', '$1', $encoded);
		} else {
			$encoded = 'null';
		}

		return $encoded;
	}

	public function getBaseObject($type, $tags) {
		$obj = ['t' => $type, 'i' => $this->identifier, 'p' => $this->probability];

		if (count($tags) > 0) {
			$obj['T'] = $tags;
		}

		return $obj;
	}
}

?>

Allow integers to be converted into floats


<?php
/*
 * This file is part of Yolk - Gamer Network's PHP Framework.
 *
 * Copyright (c) 2015 Gamer Network Ltd.
 *
 * Distributed under the MIT License, a copy of which is available in the
 * LICENSE file that was bundled with this package, or online at:
 * https://github.com/gamernetwork/yolk-orm
 */

namespace yolk\contracts\orm;

interface Entity extends Mappable {

	/**
	 * Returns the EntitySchema containing the properties and rules for the mappable object.
	 * Providing this as a static method enables us to extract the property definitions of an
	 * object without having to actually create an instance of it.
	 * @return EntitySchema
	 */
	public static function getSchema();

	/**
	 * Determines if the entity needs to be validated.
	 * @return boolean
	 */
	public function needsValidation();

	/**
	 * Determines if the entity is valid, i.e. has been validated and has no errors.
	 * @return boolean
	 */
	public function isValid();

	/**
	 * Validate the state of the entity.
	 * @return array an array of errors
	 */
	public function validate();

	public function getErrors();

	public function setError( $property, $error = false );

}

// EOF

<?php
/*
 * This file is part of Yolk - Gamer Network's PHP Framework.
 *
 * Copyright (c) 2015 Gamer Network Ltd.
 *
 * Distributed under the MIT License, a copy of which is available in the
 * LICENSE file that was bundled with this package, or online at:
 * https://github.com/gamernetwork/yolk-orm
 */

namespace yolk\contracts\orm;

interface Entity extends Mappable {

	/**
	 * Returns the EntitySchema containing the properties and rules for the mappable object.
	 * Providing this as a static method enables us to extract the property definitions of an
	 * object without having to actually create an instance of it.
	 * @return EntitySchema
	 */
	public static function getSchema();

	/**
	 * Determines if the entity needs to be validated.
	 * @return boolean
	 */
	public function needsValidation();

	/**
	 * Determines if the entity is valid, i.e. has been validated and has no errors.
	 * @return boolean
	 */
	public function isValid();

	public function getErrors();

	public function setError( $property, $error = false );

}

// EOF

Make validate() protected and incorporate into isValid()


@extends('app')

@section('aimeos_styles')
    <link type="text/css" rel="stylesheet" href="{{ asset('packages/aimeos/shop/themes/elegance/common.css') }}" />
    <link type="text/css" rel="stylesheet" href="{{ asset('packages/aimeos/shop/themes/elegance/aimeos.css') }}" />
@stop

@section('aimeos_scripts')
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/jquery-ui.custom.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/aimeos.js') }}"></script>
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/elegance/aimeos.js') }}"></script>
@stop

@extends('app')

@section('aimeos_styles')
    <link type="text/css" rel="stylesheet" href="{{ asset('packages/aimeos/shop/themes/elegance/common.css') }}" />
    <link type="text/css" rel="stylesheet" href="{{ asset('packages/aimeos/shop/themes/elegance/aimeos.css') }}" />
@stop

@section('aimeos_scripts')
	<script type="text/javascript" src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/jquery-ui.custom.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/aimeos.js') }}"></script>
    <script type="text/javascript" src="{{ asset('packages/aimeos/shop/themes/elegance/aimeos.js') }}"></script>
@stop

Add polyfill.js to iron out missing features in browsers


<?php

namespace App\Model;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Endpoint extends Model
{
    protected $fillable = [
        'url',
        'name',
        'description',
    ];

    protected $casts = [
        'system' => 'array',
    ];

    protected $dates = [
        'endpoint_fetched',
    ];

    protected $hidden = [
        'id',
        'created_at',
        'updated_at',
        'endpoint_fetched',
    ];

    protected $appends = [
        'fetched',
    ];

    public function bodies()
    {
        return $this->hasMany(EndpointBody::class, 'endpoint_id', 'id');
    }

    public function getFetchedAttribute()
    {
        /** @var Carbon $fetched */
        $fetched = $this->endpoint_fetched;

        return $fetched->toIso8601String();
    }
}

<?php

namespace App\Model;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Endpoint extends Model
{
    protected $fillable = [
        'url',
        'name',
        'description',
    ];

    protected $casts = [
        'system' => 'array',
    ];

    protected $dates = [
        'endpoint_fetched',
    ];

    protected $hidden = [
        'id',
        'created_at',
        'updated_at',
        'endpoint_fetched',
    ];

    protected $appends = [
        'fetched'
    ];

    public function bodies()
    {
        return $this->hasMany(EndpointBody::class, 'endpoint_id', 'id');
    }

    public function getFetchedAttribute()
    {
        /** @var Carbon $fetched */
        $fetched = $this->endpoint_fetched;
        if (!is_null($fetched)) {
            return $fetched->toIso8601String();
        }

        return null;
    }
}

Make sure the fetch date is only returned as date if there's a date


<form role="search" method="get" class="search-form form-inline" action="<?= esc_url(home_url('/')); ?>">
  <?php _e('Search for:', 'sage'); ?>

    <input type="search" value="<?= get_search_query(); ?>" name="s" class="search-field form-control" placeholder="<?php _e('Search', 'sage'); ?> <?php bloginfo('name'); ?>" required>

      <button type="submit" class="search-submit btn btn-default"><?php _e('Search', 'sage'); ?></button>

</form>

<?php
function hy_search_page_url() {
  if(get_option('show_on_front') === 'page') {
    return get_permalink(get_option('page_for_posts'));
  } else {
    return home_url('/');
  }
}
?>
<form role="search" method="get" class="search-form form-inline" action="<?= esc_url(hy_search_page_url()); ?>">
  <?php _e('Search for:', 'sage'); ?>

    <input type="search" value="<?= get_search_query(); ?>" name="s" class="search-field form-control" placeholder="<?php _e('Search', 'sage'); ?> <?php bloginfo('name'); ?>" required>

      <button type="submit" class="search-submit btn btn-default"><?php _e('Search', 'sage'); ?></button>

</form>

Use posts page for search, if set

Use posts page for search, if set

WordPress allows setting the "posts" page to be a page other than the
front page, something we use to host the blog at /blog.

Add a switch in the search form template which detects if this setting
is configured, and if so changes the search action to point to the posts
page rather than the home page.


<?php

class RandomTest extends \PHPUnit\Framework\TestCase
{
    public function testBytes()
    {
        $len = 10;

        $m = \Dcrypt\Random::bytes($len);

        $this->assertTrue(strlen($m) === $len);
    }

    public function testShuffle()
    {
        $array = ['a', 'b', 'c', 'd'];

        $array = \Dcrypt\Random::shuffle($array, 'seed string can be any length because it is hashed before use');

        $this->assertEquals('b', array_shift($array));
        $this->assertEquals('a', array_shift($array));
        $this->assertEquals('c', array_shift($array));
        $this->assertEquals('d', array_shift($array));
    }
}

<?php

class RandomTest extends \PHPUnit\Framework\TestCase
{
    public function testBytes()
    {
        $len = 10;

        $m = \Dcrypt\Random::bytes($len);

        $this->assertTrue(strlen($m) === $len);
    }

    public function testShuffle()
    {
        $array = array('a', 'b', 'c', 'd');

        $array = \Dcrypt\Random::shuffle($array, 'seed string can be any length because it is hashed before use');

        $this->assertEquals('b', array_shift($array));
        $this->assertEquals('a', array_shift($array));
        $this->assertEquals('c', array_shift($array));
        $this->assertEquals('d', array_shift($array));
    }
}

Fix array declaration for old php

Fix array declaration for old php


<?php

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

require_once(__DIR__ . '/../../../yiisoft/yii2/Yii.php');
require_once(__DIR__ . '/../../../autoload.php');

<?php

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require_once(__DIR__ . '/../vendor/autoload.php');

Fix vendor path for tests

Fix vendor path for tests


<?php

class CheckDigitTest extends PHPUnit_Framework_TestCase
{

    public function testIsbn10()
    {
        $this->assertEquals('8', Isbn\CheckDigit::make10('888183718'));
        $this->assertEquals('8', Isbn\CheckDigit::make10('8881837188'));
    }

    public function testIsbn13()
    {
        $this->assertEquals('1', Isbn\CheckDigit::make13('978888952719'));
        $this->assertEquals('1', Isbn\CheckDigit::make13('9788889527191'));
    }

    public function testIsbn()
    {
        $this->assertEquals('8', Isbn\CheckDigit::make('888183718'));
        $this->assertEquals('1', Isbn\CheckDigit::make('978888952719'));
    }

}

<?php

class CheckDigitTest extends PHPUnit_Framework_TestCase
{

    public function testIsbn10()
    {
        $this->assertEquals('8', Isbn\CheckDigit::make10('888183718'));
        $this->assertEquals('8', Isbn\CheckDigit::make10('8881837188'));
    }

    public function testIsbn13()
    {
        $this->assertEquals('1', Isbn\CheckDigit::make13('978888952719'));
        $this->assertEquals('1', Isbn\CheckDigit::make13('9788889527191'));
    }

    public function testIsbn()
    {
        $this->assertEquals('8', Isbn\CheckDigit::make('888183718'));
        $this->assertEquals('1', Isbn\CheckDigit::make('978888952719'));
        $this->assertFalse(Isbn\CheckDigit::make('97888895271921'));
    }

}

Move to 100% of Testing Code Coverage for Isbn::CheckDigit


<?php

/**
 * Here is where you can register web routes for your application. These
 * routes are loaded by the RouteServiceProvider within a group which
 * contains the "web" middleware group. Now create something great!
 *
 * @var \Illuminate\Routing\Router $router
 * @see \Aurora\Providers\RouteServiceProvider
 */

// Homepage
$router->get('/', 'HomeController@home');

// Authentication
$router->get('auth/login', 'Auth\AuthController@getLogin');
$router->get('auth/logout', 'Auth\AuthController@getLogout');

// Users
$router->resource('users', 'UsersController', ['except' => ['create', 'store']]);
$router->get('search', ['as' => 'user.search', 'uses' => 'UsersController@search']);

// Superusers
$router->resource('superusers', 'SuperusersController', ['only' => ['index']]);

// Clients
$router->resource('clients', 'ClientController');

<?php

/**
 * Here is where you can register web routes for your application. These
 * routes are loaded by the RouteServiceProvider within a group which
 * contains the "web" middleware group. Now create something great!
 *
 * @var \Illuminate\Routing\Router $router
 * @see \Aurora\Providers\RouteServiceProvider
 */

// Homepage
$router->get('/', 'HomeController@home')->name('login');

// Authentication
$router->get('auth/login', 'Auth\AuthController@getLogin');
$router->get('auth/logout', 'Auth\AuthController@getLogout');

// Users
$router->resource('users', 'UsersController', ['except' => ['create', 'store']]);
$router->get('search', ['as' => 'user.search', 'uses' => 'UsersController@search']);

// Superusers
$router->resource('superusers', 'SuperusersController', ['only' => ['index']]);

// Clients
$router->resource('clients', 'ClientController');

Add named 'login' route for auth middleware.


<?php
class FooBar
{
    public function test()
    {
        echo 'foo bar';
    }
}

<?php
class FooBar
{
    public function test()
    {
        echo 'foobar';
    }
}

Remove space between foo and bar

[BUGFIX] Remove space between foo and bar


<?php

namespace GlideModule;

use Interop\Container\ContainerInterface;
use Interop\Container\ServiceProvider\ServiceProvider;
use League\Glide\Server;
use League\Glide\ServerFactory;

class GlideServiceProvider implements ServiceProvider
{
    public static function getServices()
    {
        return [
            Server::class => 'createGlide',
            'glide.options' => 'getOptions',
        ];
    }

    public static function createGlide(ContainerInterface $container)
    {
        return ServerFactory::create($container->get('glide.options'));
    }

    public static function getOptions()
    {
        // Options are empty by default
        return [];
    }
}

<?php

namespace GlideModule;

use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use Interop\Container\ContainerInterface;
use Interop\Container\ServiceProvider\ServiceProvider;
use League\Glide\Responses\PsrResponseFactory;
use League\Glide\Server;
use League\Glide\ServerFactory;

class GlideServiceProvider implements ServiceProvider
{
    public static function getServices()
    {
        return [
            Server::class => 'createGlide',
            'glide.options' => 'getOptions',
        ];
    }

    public static function createGlide(ContainerInterface $container)
    {
        $options = $container->get('glide.options');

        $server = ServerFactory::create($options);

        // We override the response factory to return PSR-7 response by default
        $responseFactory = new PsrResponseFactory(new Response(), function ($stream) {
            return new Stream($stream);
        });
        $server->setResponseFactory($responseFactory);

        return $server;
    }

    public static function getOptions()
    {
        // Options are empty by default
        return [];
    }
}

Return PSR-7 response by default

Return PSR-7 response by default


#!/usr/bin/env php
<?php

require_once __DIR__ . '/../bootstrap.php';

use Hodor\Command\Arguments as Arguments;
use Hodor\Config\LoaderFacade as Config;
use Hodor\JobQueue\QueueFactory as QueueFactory;

$args = new Arguments();
$config_file = $args->getConfigFile();
$queue_name = $args->getQueueName();

$config = Config::loadFromFile($config_file);
$queue_factory = new QueueFactory($config);
$buffer_worker = $queue_factory->getBufferQueue($queue_name);

$buffer_worker->processBuffer();

#!/usr/bin/env php
<?php

require_once __DIR__ . '/../bootstrap.php';

use Hodor\Command\Arguments as Arguments;
use Hodor\Config\LoaderFacade as Config;
use Hodor\JobQueue\QueueFactory as QueueFactory;

$args = new Arguments();
$config_file = $args->getConfigFile();

$config = Config::loadFromFile($config_file);
$queue_factory = new QueueFactory($config);
$buffer_worker = $queue_factory->getBufferQueue('default');

$buffer_worker->processBuffer();

Revert "feat(queue): add buffer queue name factory"

This reverts commit 7570be26b320e796da1225dc34d8c180f78f58bb.

The commit message and date for this commit was wrong.


<?php

namespace Knot\Http\Controllers;

use Illuminate\Http\Request;
use Knot\Models\User;
use Doorman;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['only' => [
            'user',
        ]]);
    }

    /**
     * Return the authenticated user.
     *
     * @return \Illuminate\Http\Response
     */
    public function user()
    {
        return auth()->user();
    }

    /**
     * Register a new user.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'first_name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required',
            'code' => 'required|doorman:email',
        ]);
        try {
            Doorman::redeem($request->input('code'), $request->input('email'));

            return User::create($request->all());
        } catch (\DoormanException $e) {
            return response()->json(['error' => $e->getMessage()], 422);
        }
    }
}

<?php

namespace Knot\Http\Controllers;

use Illuminate\Http\Request;
use Knot\Models\User;
use Doorman;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['only' => [
            'user',
        ]]);
    }

    /**
     * Return the authenticated user.
     *
     * @return \Illuminate\Http\Response
     */
    public function user()
    {
        return auth()->user();
    }

    /**
     * Register a new user.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'first_name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed',
        ]);

        return User::create($request->all());
    }
}

Remove invite code check on user registration


<?php
namespace CodeGen;
use Twig_Loader_String;
use Twig_Environment;
use Closure;

class Utils
{
    static $stringloader = null;
    static $twig;

    static public function renderStringTemplate($templateContent, array $args = array())
    {
        if (!self::$stringloader) {
            self::$stringloader = new Twig_Loader_String();
        }
        if (!self::$twig) {
            self::$twig = new Twig_Environment(self::$stringloader);
        }
        if (is_callable($args)) {
            $args = call_user_func($args);
        } elseif ($args instanceof Closure) {
            $args = $args();
        }
        return self::$twig->render($templateContent, $args);
    }

    static public function evalCallback($cb)
    {
        return is_callable($cb) ? $cb() : $cb;
    }

    static public function indent($indent = 1, $spaces = 4)
    {
        return str_repeat(' ', $spaces * $indent);
    }
}

<?php
namespace CodeGen;
use Twig_Loader_String;
use Twig_Environment;
use Closure;

class Utils
{
    static $stringloader = null;

    static $twig;

    static public function renderStringTemplate($templateContent, array $args = array(), Twig_Environment $env = null)
    {
        if (!$env) {
            $env = new Twig_Environment;
        }
        $template = $twig->createTemplate($templateContent);

        if (is_callable($args)) {
            $args = call_user_func($args);
        } elseif ($args instanceof Closure) {
            $args = $args();
        }
        return $template->render($args);
    }

    static public function evalCallback($cb)
    {
        return is_callable($cb) ? $cb() : $cb;
    }

    static public function indent($indent = 1, $spaces = 4)
    {
        return str_repeat(' ', $spaces * $indent);
    }
}

Rewrite render string method to support newer Twig engine


<?php
namespace Hoopak;

use Hoopak\Annotation;

class Trace
{
    /**
     * Create a Trace.
     */
    public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
    {
        $this->name = $name;

        if ($traceId) {
            $this->traceId = $traceId;
        } else {
            $this->traceId = $this->_id();
        }

        if ($spanId) {
            $this->spanId = $spanId;
        } else {
            $this->spanId = $this->_id();
        }

        $this->parentSpanId = $parentSpanId;

        $this->_tracers = $tracers;

        $this->_endpoint = null;
    }

    /**
     * Record an annotation
     */
    public function record($annotation)
    {
        if (!$annotation->endpoint && $this->_endpoint) {
            $annotation->endpoint = $this->_endpoint;
        }

        foreach ($this->_tracers as $tracer) {
            $tracer->record($this, $annotation);
        }

    }

    /**
     * Create a child of this trace
     */
    public function child($name)
    {
        $trace = new self($name, $this->traceId, null, $this->spanId);
        $trace->setEndpoint($this->_endpoint);
        return $trace;
    }

    /**
     * Set the endpoint
     */
    public function setEndpoint($endpoint)
    {
        $this->_endpoint = $endpoint;
    }

    private static function _id()
    {
        return rand(0, pow(2,56)-1);
    }

}

<?php
namespace Hoopak;

use Hoopak\Annotation;

class Trace
{
    /**
     * Create a Trace.
     */
    public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
    {
        $this->name = $name;

        if ($traceId) {
            $this->traceId = $traceId;
        } else {
            $this->traceId = $this->_id();
        }

        if ($spanId) {
            $this->spanId = $spanId;
        } else {
            $this->spanId = $this->_id();
        }

        $this->parentSpanId = $parentSpanId;

        $this->_tracers = $tracers;

        $this->_endpoint = null;
    }

    /**
     * Record an annotation
     */
    public function record($annotation)
    {
        if (!$annotation->endpoint && $this->_endpoint) {
            $annotation->endpoint = $this->_endpoint;
        }

        foreach ($this->_tracers as $tracer) {
            $tracer->record($this, $annotation);
        }

    }

    /**
     * Create a child of this trace
     */
    public function child($name)
    {
        $trace = new self($name, $this->traceId, null, $this->spanId);
        $trace->_tracers = $this->_tracers;
        $trace->setEndpoint($this->_endpoint);
        return $trace;
    }

    /**
     * Set the endpoint
     */
    public function setEndpoint($endpoint)
    {
        $this->_endpoint = $endpoint;
    }

    private static function _id()
    {
        return rand(0, pow(2,56)-1);
    }

}

Copy over the tracers as well

Copy over the tracers as well


<?php
namespace WPCore;

use WPCore\admin\WPpostSaveable;

class WPcustomPost implements WPpostSaveable
{
    protected $postId;
    protected $post;
    protected $meta = array();
    protected $metakey = 'wpcmeta';

    static public function create($postId)
    {
        return new self($postId);
    }

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

    public function setPost(\WP_Post $post)
    {
        $this->post = $post;
        return $this;
    }

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

    public function get($key)
    {
        if (isset($this->meta[$key])) {
            return $this->meta[$key];
        }
        return null;
    }

    public function set($key, $value)
    {
        $this->meta[$key] = $value;

        return $this;
    }

    public function fetch()
    {
        $this->meta = get_post_meta($this->postId, $this->metakey, true);
        if (empty($this->meta)) {
            $this->meta = array();
        } else {
            $this->meta = unserialize($this->meta);
        }
        return true;
    }

    public function save()
    {
        return update_post_meta($this->postId, $this->metakey, serialize($this->meta));
    }
}

<?php
namespace WPCore;

use WPCore\admin\WPpostSaveable;

class WPcustomPost implements WPpostSaveable
{
    protected $postId;
    protected $post;
    protected $meta = array();
    protected $metakey = 'wpcmeta';

    public static function getInstance($id)
    {
        $post = new self($id);
        $post->setPost(\WP_Post::get_instance($id));
        $post->fetch();
        return $post;
    }

    static public function create($postId)
    {
        return new self($postId);
    }

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

    public function setPost(\WP_Post $post)
    {
        $this->post = $post;
        return $this;
    }

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

    public function get($key)
    {
        if (isset($this->meta[$key])) {
            return $this->meta[$key];
        }
        return null;
    }

    public function set($key, $value)
    {
        $this->meta[$key] = $value;

        return $this;
    }

    public function fetch()
    {
        $this->meta = get_post_meta($this->postId, $this->metakey, true);
        if (empty($this->meta)) {
            $this->meta = array();
        } else {
            $this->meta = unserialize($this->meta);
        }
        return true;
    }

    public function save()
    {
        return update_post_meta($this->postId, $this->metakey, serialize($this->meta));
    }
}

Add static method to extract post from post id


<?php

return [
    'using' => [
        'csrf'             => true,
        'framework'        => 'bootstrap',
        'custom-framework' => function () {
            return new Path\To\My\Framework();
        },
    ],
    /*
     * @param String
     * @return Collection
     */
    'resolved_relationship' => function ($class_name) {
        return $class_name::limit(15)->get();
    },
];

<?php

return [
    'using' => [
        'csrf' => true,
        'framework' => 'bootstrap',
        'custom-framework' => function () {
            return new Kregel\FormModel\Frameworks\Plain;
        },
    ],
    /*
     * @param String
     * @return Collection
     */
    'resolved_relationship' => function ($class_name, $desired_relations) {
        try {
            $relations = $class_name::with($desired_relations)->
            limit(50)->get()->flatMap(function ($e) use ($desired_relations) {
                if (!empty($e->$desired_relations)) {
                    return ($e->$desired_relations->pluck(method_exists($e->$desired_relations, 'getFormModel') ? $e->$desired_relations->getFormModel() : 'name'));
                }
            })->unique();
        } catch (\Exception $e) {
            $relations = $class_name::orderBy($desired_relations . '_id')->groupBy($desired_relations.'_id')->get()->map(function ($el) use ($desired_relations){
                if(!empty($el->{$desired_relations . '_id'}))
                    return $el->{$desired_relations . '_id'};
                return $el->name;
            });
        }
        return $relations;
    },
];

Fix some models not resolving issue

Fix some models not resolving issue


<?php namespace Illuminate\Foundation\Console;

use Illuminate\Support\Str;
use Illuminate\Console\Command;

class KeyGenerateCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'key:generate';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = "Set the application key";

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$key = $this->getRandomKey();

		foreach ([base_path('.env'), base_path('.env.example')] as $path)
		{
			if (file_exists($path))
			{
				file_put_contents($path, str_replace(
					$this->laravel['config']['app.key'], $key, file_get_contents($path)
				));
			}
		}

		$this->laravel['config']['app.key'] = $key;

		$this->info("Application key [$key] set successfully.");
	}

	/**
	 * Generate a random key for the application.
	 *
	 * @return string
	 */
	protected function getRandomKey()
	{
		return Str::random(32);
	}

}

<?php namespace Illuminate\Foundation\Console;

use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class KeyGenerateCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'key:generate';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = "Set the application key";

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$key = $this->getRandomKey();

		if ($this->option('show'))
		{
			return $this->line('<comment>'.$key.'</comment>');
		}

		foreach ([base_path('.env'), base_path('.env.example')] as $path)
		{
			if (file_exists($path))
			{
				file_put_contents($path, str_replace(
					$this->laravel['config']['app.key'], $key, file_get_contents($path)
				));
			}
		}

		$this->laravel['config']['app.key'] = $key;

		$this->info("Application key [$key] set successfully.");
	}

	/**
	 * Generate a random key for the application.
	 *
	 * @return string
	 */
	protected function getRandomKey()
	{
		return Str::random(32);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(
			array('show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'),
		);
	}

}

Add --show option to key:generate.

Add --show option to key:generate.


<?=form_open_multipart()?>

    1. CSV File

    This should be a *.csv file which contains 3 columns: old URL, new URL, type of redirect (301 or 302).

    <input type="file" name="upload" style="border: 1px solid #CCC;padding: 1rem; width: 100%;margin-bottom: 1rem">

    2. Action

    Define how to process the redirects.

    <select name="action" class="select2">
        <option value="APPEND">Append - add new items in the CSV to the database</option>
        <option value="REPLACE">Replace - replace the items in the database with those in the CSV</option>
        <option value="REMOVE">Remove - remove items in the CSV from the database</option>
    </select>

    <button type="submit" class="btn btn-primary">
        Upload
    </button>

<?=form_close()?>

<?=form_open_multipart()?>

    1. CSV File

    This should be a *.csv file which contains 3 columns: old URL, new URL, type of redirect (301 or 302).

    <input type="file" name="upload" style="border: 1px solid #CCC;padding: 1rem; width: 100%;margin-bottom: 1rem">

    2. Action

    Define how to process the redirects.

    <select name="action" class="select2">
        <option value="APPEND">Append - add new items in the CSV to the database</option>
        <option value="REPLACE">Replace - replace the items in the database with those in the CSV</option>
        <option value="REMOVE">Remove - remove items in the CSV from the database</option>
    </select>

    <button type="submit" class="btn btn-primary">
        Save Changes
    </button>

<?=form_close()?>

Support for floating admin controls

Support for floating admin controls


<?php

declare(strict_types=1);

namespace Albert221\Validation;

use PHPUnit\Framework\TestCase;

class VerdictTest extends TestCase
{
    public function testCreate()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = Verdict::create(true, $ruleMock);

        $this->assertEquals(
            new Verdict(true, $ruleMock, $ruleMock->getField()),
            $verdict
        );
    }

    public function testPasses()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = new Verdict(true, $ruleMock, $ruleMock->getField());
        $this->assertTrue($verdict->passes());

        $verdict = new Verdict(false, $ruleMock, $ruleMock->getField());
        $this->assertFalse($verdict->passes());
    }

    /**
     * @return Rule Mock of Rule
     */
    private function getRuleMock(): Rule
    {
        return $this
            ->getMockBuilder(Rule::class)
            ->disableOriginalConstructor()
            ->setMethods(['getField', 'verdict'])
            ->getMock();
    }
}

<?php

declare(strict_types=1);

namespace Albert221\Validation;

use PHPUnit\Framework\TestCase;

class VerdictTest extends TestCase
{
    public function testPassing()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = Verdict::passing($ruleMock);

        $this->assertEquals(
            new Verdict(true, $ruleMock, $ruleMock->getField()),
            $verdict
        );
    }
    public function testFailing()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = Verdict::failing($ruleMock);

        $this->assertEquals(
            new Verdict(false, $ruleMock, $ruleMock->getField()),
            $verdict
        );
    }

    public function testCreate()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = Verdict::create(true, $ruleMock);

        $this->assertEquals(
            new Verdict(true, $ruleMock, $ruleMock->getField()),
            $verdict
        );
    }

    public function testPasses()
    {
        $ruleMock = $this->getRuleMock();

        $verdict = new Verdict(true, $ruleMock, $ruleMock->getField());
        $this->assertTrue($verdict->passes());

        $verdict = new Verdict(false, $ruleMock, $ruleMock->getField());
        $this->assertFalse($verdict->passes());
    }

    /**
     * @return Rule Mock of Rule
     */
    private function getRuleMock(): Rule
    {
        return $this
            ->getMockBuilder(Rule::class)
            ->disableOriginalConstructor()
            ->setMethods(['getField', 'verdict'])
            ->getMock();
    }
}

Add missing tests for Verdict

Add missing tests for Verdict


<?php

namespace Bramus\Monolog\Formatter;

use Bramus\Monolog\Formatter\ColorSchemes\ColorSchemeInterface;

/**
 * A Colored Line Formatter for Monolog
 */
class ColoredLineFormatter extends \Monolog\Formatter\LineFormatter
{
    /**
     * The Color Scheme to use
     * @var ColorSchemeInterface
     */
    private $colorScheme = null;

    /**
     * Gets The Color Scheme
     * @return ColorSchemeInterface
     */
    public function getColorScheme()
    {
        if (!$this->colorScheme) {
            $this->colorScheme = new ColorSchemes\DefaultScheme();
        }

        return $this->colorScheme;
    }

    /**
     * Sets The Color Scheme
     * @param array
     */
    public function setColorScheme(ColorSchemeInterface $colorScheme)
    {
        $this->colorScheme = $colorScheme;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        // Get the Color Scheme
        $colorScheme = $this->getColorScheme();

        // Let the parent class to the formatting, yet wrap it in the color linked to the level
        return $colorScheme->getColorizeString($record['level']).trim(parent::format($record)).$colorScheme->getResetString()."\n";
    }
}

<?php

namespace Bramus\Monolog\Formatter;

use Bramus\Monolog\Formatter\ColorSchemes\ColorSchemeInterface;

/**
 * A Colored Line Formatter for Monolog
 */
class ColoredLineFormatter extends \Monolog\Formatter\LineFormatter
{
    /**
     * The Color Scheme to use
     * @var ColorSchemeInterface
     */
    private $colorScheme = null;

    /**
     * @param string $format                     The format of the message
     * @param string $dateFormat                 The format of the timestamp: one supported by DateTime::format
     * @param bool   $allowInlineLineBreaks      Whether to allow inline line breaks in log entries
     * @param bool   $ignoreEmptyContextAndExtra
     */
    public function __construct($colorScheme = null, $format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)
    {
        // Store the Color Scheme
        if ($colorScheme instanceof ColorSchemeInterface) $this->setColorScheme($colorScheme);

        // Call Parent Constructor
        parent::__construct($format, $dateFormat, $allowInlineLineBreaks, $ignoreEmptyContextAndExtra);
    }

    /**
     * Gets The Color Scheme
     * @return ColorSchemeInterface
     */
    public function getColorScheme()
    {
        if (!$this->colorScheme) {
            $this->colorScheme = new ColorSchemes\DefaultScheme();
        }

        return $this->colorScheme;
    }

    /**
     * Sets The Color Scheme
     * @param array
     */
    public function setColorScheme(ColorSchemeInterface $colorScheme)
    {
        $this->colorScheme = $colorScheme;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        // Get the Color Scheme
        $colorScheme = $this->getColorScheme();

        // Let the parent class to the formatting, yet wrap it in the color linked to the level
        return $colorScheme->getColorizeString($record['level']).trim(parent::format($record)).$colorScheme->getResetString()."\n";
    }
}

Allow setting the color scheme via the constructor


<?php

namespace Storo\Command;

use Storo\Math\Fibonacci;

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

class FibonacciCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('storo:fibonacci')
            ->setDescription('Prints `howMany` fibonacci series.')
            ->addArgument(
                'howMany',
                InputArgument::OPTIONAL,
                '',
                10
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $howMany = $input->getArgument('howMany', 10);

        $fibonacci = new Fibonacci();

        $output->write("<info>Result: </info>");
        for ($i=1; $i <= $howMany; $i++) {
            $result = $fibonacci->recursive($i);
            $output->write($result . ' ');
        }
        $output->write("\n");
    }
}

<?php

namespace Storo\Command;

use Storo\Math\Fibonacci;

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

class FibonacciCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('storo:fibonacci')
            ->setDescription('Prints `howMany` fibonacci series.')
            ->addArgument(
                'howMany',
                InputArgument::OPTIONAL,
                '',
                10
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $howMany = $input->getArgument('howMany', 10);

        $fibonacci = new Fibonacci();

        $result = $fibonacci->recursive($howMany, $list);
        $list = implode(', ', $list);

        $output->writeln("<info>Result:</info> {$list}.");
    }
}

Use reference list to print fibonacci series in command.


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Authenticated Controller
 *
 * Provides a base class for all controllers that must check user login
 * status.
 *
 * @package    Bonfire\Core\Controllers
 * @category   Controllers
 * @author     Bonfire Dev Team
 * @link       http://guides.cibonfire.com/helpers/file_helpers.html
 *
 */
class Authenticated_Controller extends Base_Controller
{

    protected $require_authentication   = true;

	//--------------------------------------------------------------------

	/**
	 * Class constructor setup login restriction and load various libraries
	 *
	 */
	public function __construct()
	{
        $this->autoload['helpers'] = 'form';
        $this->autoload['libraries'][]  = 'Template';
        $this->autoload['libraries'][]  = 'Assets';
        $this->autoload['libraries'][]  = 'form_validation';

		parent::__construct();

		$this->form_validation->set_error_delimiters('', '');

	}//end construct()

	//--------------------------------------------------------------------

}

/* End of file Authenticated_Controller.php */
/* Location: ./application/core/Authenticated_Controller.php */

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Authenticated Controller
 *
 * Provides a base class for all controllers that must check user login
 * status.
 *
 * @package    Bonfire\Core\Controllers
 * @category   Controllers
 * @author     Bonfire Dev Team
 * @link       http://guides.cibonfire.com/helpers/file_helpers.html
 *
 */
class Authenticated_Controller extends Base_Controller
{

    protected $require_authentication   = true;

	//--------------------------------------------------------------------

	/**
	 * Class constructor setup login restriction and load various libraries
	 *
	 */
	public function __construct()
	{
        $this->autoload['helpers'][]    = 'form';
        $this->autoload['libraries'][]  = 'Template';
        $this->autoload['libraries'][]  = 'Assets';
        $this->autoload['libraries'][]  = 'form_validation';

		parent::__construct();

		$this->form_validation->set_error_delimiters('', '');

	}//end construct()

	//--------------------------------------------------------------------

}

/* End of file Authenticated_Controller.php */
/* Location: ./application/core/Authenticated_Controller.php */

Fix typo in latest change for Base Controller Autoload.


<?php
$website_name = (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name');
?>
<!DOCTYPE html>

	<meta charset="utf-8">
	<title><?php echo $website_name; ?></title>
	<base href="<?php echo base_url(); ?>" />
	<link rel="shortcut icon" href="<?php echo base_url('favicon.ico'); ?>" />
	<?php echo $head?>
	<?php echo $css?>
	<?php echo $js?>

		<?php echo $this->load->view('header'); ?>

			<?php if (isset($page_title)): ?>

<?php echo $page_title; ?>

			<?php endif; ?>
			<?php echo $messages?>
			<?php echo $content?>

		<?php echo $this->load->view('footer'); ?>

<!DOCTYPE html>

	<meta charset="utf-8">
	<title><?php echo (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name'); ?></title>
	<base href="<?php echo base_url(); ?>" />
	<link rel="shortcut icon" href="<?php echo base_url('favicon.ico'); ?>" />
	<?php echo $head?>
	<?php echo $css?>
	<?php echo $js?>

		<?php echo $this->load->view('header'); ?>

			<?php if (isset($page_menu)): ?>
			<?php echo $page_menu; ?>
			<?php endif; ?>
			<?php if (isset($page_title)): ?>

<?php echo $page_title; ?>

			<?php endif; ?>
			<?php echo $messages?>
			<?php echo $content?>

		<?php echo $this->load->view('footer'); ?>

Add template section for page menu.

Add template section for page menu.


<?php
namespace app\commands;

use app\models\Language;
use budyaga\users\models\User;
use yii\console\Controller;
use yii\db\Expression;

class ArticleController extends Controller
{
    public function actionSeed($count = 1)
    {
        for ($i=0; $i<$count; $i++) {
			$faker =\Faker\Factory::create();
			$article = new \app\models\Article;
			$article->title_original=$faker->text(80);
			$article->title_translate=$faker->text(80);
			$article->user_id='2';
			$article->lang_original_id='2';
			$article->lang_translate_id='1';
			$article->save();
			var_export($article->errors);
		}
		echo (" created"." ".$count." "."articles ");
	}
}

<?php
namespace app\commands;

use app\models\Language;
use budyaga\users\models\User;
use yii\console\Controller;
use yii\db\Expression;

class ArticleController extends Controller
{
    public function actionSeed($count = 1)
    {
        for ($i=0; $i<$count; $i++) {
			$faker =\Faker\Factory::create();
			$article = new \app\models\Article;
			$article->title_original=$faker->text(80);
			$article->title_translate=$faker->text(80);
			$article->user_id='2';
			$article->lang_original_id='2';
			$article->lang_translate_id='1';
			$article->save();
			var_export($article->errors);
		}
		echo (" created"." ".$count." "."articles ");
	}

	/**
	 * Функция обновления всего индекса в ElasticSearch
	 *
	 */
	public function updateElastic()
	{

	}
	/**
	 * Функция удаления всего индекса в ElasticSearch
	 *
	 */
	public function deleteElastic()
	{

	}
}

[new] Add function updateElastic, deleteElastic
Добавлен каркас функция для обновления и удаления записей всего индекса ElasticSearch


<?php

namespace JWX\JWT\Parameter;

/**
 * Critical parameter
 *
 * @link https://tools.ietf.org/html/rfc7515#section-4.1.11
 */
class CriticalParameter extends RegisteredJWTParameter
{
	/**
	 * Constructor
	 *
	 * @param string[] $names
	 */
	public function __construct(...$names) {
		parent::__construct(self::PARAM_CRITICAL, $names);
	}

	public static function fromJSONValue($value) {
		if (!is_array($value)) {
			throw new \UnexpectedValueException("Array expected");
		}
		return new static(...$value);
	}
}

<?php

namespace JWX\JWT\Parameter;

/**
 * Critical parameter
 *
 * @link https://tools.ietf.org/html/rfc7515#section-4.1.11
 */
class CriticalParameter extends RegisteredJWTParameter
{
	/**
	 * Constructor
	 *
	 * @param string[] $names
	 */
	public function __construct(...$names) {
		parent::__construct(self::PARAM_CRITICAL, $names);
	}

	public static function fromJSONValue($value) {
		if (!is_array($value)) {
			throw new \UnexpectedValueException("Array expected");
		}
		return new static(...$value);
	}

	/**
	 * Get self with parameter name added
	 *
	 * @param string $name
	 * @return self
	 */
	public function withParamName($name) {
		$obj = clone $this;
		$obj->_value[] = $name;
		$obj->_value = array_values(array_unique($obj->_value));
		return $obj;
	}

	/**
	 * Check whether given parameter name is critical
	 *
	 * @param string $name
	 * @return bool
	 */
	public function has($name) {
		return false !== array_search($name, $this->_value);
	}
}

Add methods to critical parameter

Add methods to critical parameter


<?php namespace Stolz\HtmlTidy;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Path to the default config file.
	 *
	 * @var string
	 */
	protected $configFile = __DIR__ . '/config.php';

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

	/**
	 * Register bindings in the container.
	 *
	 * @return void
	 */
	public function register()
	{
		// Merge user's configuration
		$this->mergeConfigFrom($this->configFile, 'tidy');

		// Bind 'stolz.tidy' shared component to the IoC container
		$this->app->singleton('stolz.tidy', function ($app) {
			return new Tidy($app['config']['tidy']);
		});
	}

	/**
	 * Perform post-registration booting of services.
	 *
	 * @return void
	 */
	public function boot()
	{
		// Register paths to be published by 'vendor:publish' artisan command
		$this->publishes([
			$this->configFile => config_path('tidy.php'),
		]);
	}
}

<?php namespace Stolz\HtmlTidy;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

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

	/**
	 * Register bindings in the container.
	 *
	 * @return void
	 */
	public function register()
	{
		// Merge user's configuration
		$this->mergeConfigFrom(__DIR__ . '/config.php', 'tidy');

		// Bind 'stolz.tidy' shared component to the IoC container
		$this->app->singleton('stolz.tidy', function ($app) {
			return new Tidy($app['config']['tidy']);
		});
	}

	/**
	 * Perform post-registration booting of services.
	 *
	 * @return void
	 */
	public function boot()
	{
		// Register paths to be published by 'vendor:publish' artisan command
		$this->publishes([
			__DIR__ . '/config.php' => config_path('tidy.php'),
		]);
	}
}

Fix for PHP < 5.6

Fix for PHP < 5.6


<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class BlockquoteParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '/
                ^
                [ ]{0,3}        # up to 3 leading spaces
                \>              # block quote marker
                [ ]?            # an optional space
                [^\n]*          # until end of line
                (               # and repeat multiple times...
                    \n
                    [ ]{0,3}
                    \>
                    [ ]?
                    [^\n]*
                )*
                $
            /mx',
            function (Text $content) use ($target) {
                // Remove block quote marker plus surrounding whitespace on each line
                $content->replace('/^[ ]{0,3}\>[ ]?/m', '');

                $blockquote = new Blockquote();
                $target->acceptBlockquote($blockquote);

                $this->first->parseBlock($content, $blockquote);
            },
            function (Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class BlockquoteParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '/
                ^
                [ ]{0,3}        # up to 3 leading spaces
                \>              # block quote marker
                [ ]?            # an optional space
                [^\n]*          # until end of line
                (?:                 # lazy continuation
                    \n
                    [^\-*=\ ].*
                )*
                $
            /mx',
            function (Text $content) use ($target) {
                // Remove block quote marker plus surrounding whitespace on each line
                $content->replace('/^[ ]{0,3}\>[ ]?/m', '');

                $blockquote = new Blockquote();
                $target->acceptBlockquote($blockquote);

                $this->first->parseBlock($content, $blockquote);
            },
            function (Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

Implement lazy continuation rule for block quotes.


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

namespace ZendTest\Navigation\TestAsset;

use \Zend\Navigation\Service\AbstractNavigationFactory;

class FileNavigationFactory extends AbstractNavigationFactory
{
    protected function getName()
    {
        return 'file';
    }
}

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

namespace ZendTest\Navigation\TestAsset;

use Zend\Navigation\Service\AbstractNavigationFactory;

class FileNavigationFactory extends AbstractNavigationFactory
{
    protected function getName()
    {
        return 'file';
    }
}

Remove global prefix in use statements

Remove global prefix in use statements


<?php

namespace R3O\Hive\Contracts\Factories;

interface GenericArbiter
{
    public function create($attributes = []);

    public function update($attributes = []);
}

<?php

namespace R3O\Hive\Contracts\Factories;

use R3O\Hive\Contracts\Instances\GenericInstance as GenericInstanceContract;

interface GenericArbiter
{
    public function create($attributes = []);

    public function update(GenericInstanceContract $instance, $attributes = []);
}

Add instance reference to update method.


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

use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class ReviewRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ReviewRepository extends AbstractEntityRepository implements ReviewRepositoryInterface
{
    public function getDataSetQueryBuilder()
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('review.id');
        $queryBuilder->leftJoin('review.product', 'product_info');
        $queryBuilder->leftJoin('product_info.translations', 'product_translation');

        return $queryBuilder;
    }
}

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

use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class ReviewRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ReviewRepository extends AbstractEntityRepository implements ReviewRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDataSetQueryBuilder() : QueryBuilder
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('review.id');
        $queryBuilder->leftJoin('review.product', 'product_info');
        $queryBuilder->leftJoin('product_info.translations', 'product_translation');

        return $queryBuilder;
    }
}

Return types in repositories & dataset

Return types in repositories & dataset


<?php
include 'autoload.php';

class singletonTest extends PHPUnit_Framework_TestCase {

	private $voucherInstance;

	public function testGetVoucher() {
	    $this->voucherInstance = new VoucherCheck();
	    $this->assertEquals($this->voucherInstance, new VoucherCheck());
	}
	public function testSignIn() {
	    $this->voucherInstance = new VoucherCheck();
	    $this->assertEquals(null, $this->voucherInstance->signIn());
	}
}

<?php
include 'autoload.php';

class singletonTest extends PHPUnit_Framework_TestCase {

	/**
	 * Voucher instance
	 *
	 * @var VoucherCheck $voucherInstance
	 */
	private $voucherInstance;

	public function testGetVoucher() {
	    $this->voucherInstance = new VoucherCheck();
	    $this->assertEquals($this->voucherInstance, new VoucherCheck());
	}
	public function testSignIn() {
	    $this->voucherInstance = new VoucherCheck();
	    $this->assertEquals(null, $this->voucherInstance->signIn());
	}
}

Add docblock to singleton test

Add docblock to singleton test


<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{
    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        $error = null;
        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        // Add the following lines
        if ($session->has('_security.target_path')) {
            if (false !== strpos($session->get('_security.target_path'), $this->generateUrl('fos_oauth_server_authorize'))) {
                $session->set('_fos_oauth_server.ensure_logout', true);
            }
        }

        return $this->render('AppBundle:Security:login.html.twig', array(
            // last username entered by the user
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
            'error_type'    => $error?get_class($error):null,
        ));
    }
}

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{
    public function loginAction(Request $request)
    {
        $session = $request->getSession();

        $error = null;
        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        // Add the following lines
        if ($session->has('_security.target_path')) {
            if (false !== strpos($session->get('_security.target_path'), $this->generateUrl('fos_oauth_server_authorize'))) {
                $session->set('_fos_oauth_server.ensure_logout', true);
            }
        }

        return $this->render('AppBundle:Security:login.html.twig', array(
            // last username entered by the user
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
            'error_type'    => $error?get_class($error):null,
        ));
    }
}

Remove call to deprecated Controller::getRequest()


<?php

return array(

    'default' => 'default',

    'path' => base_path('themes'),

    'cache' => [
    	'enabled' => true,
    	'lifetime' => 86400,
    ]

);

<?php

return array(

    'default' => 'default',

    'path' => base_path('themes'),

    'cache' => [
    	'enabled' => true,
    	'key' => 'pingpong.themes',
    	'lifetime' => 86400,
    ]

);

Allow to update cache key

Allow to update cache key


<?php
/**
 * Created by PhpStorm.
 * User: Giansalex
 * Date: 16/07/2017
 * Time: 22:54
 */

declare(strict_types=1);

namespace Tests\Greenter\Xml\Builder;

use Greenter\Data\Generator\InvoiceFullStore;
use Greenter\Data\Generator\InvoiceStore;
use Greenter\Model\Sale\Invoice;
use PHPUnit\Framework\TestCase;

/**
 * Class FeInvoiceBuilderTest
 * @package Tests\Greenter\Xml\Builder
 */
class FeInvoiceBuilderTest extends TestCase
{
    use FeBuilderTrait;
    use XsdValidatorTrait;

    public function testCreateXmlInvoice()
    {
        $invoice = $this->createDocument(InvoiceFullStore::class);

        $xml = $this->build($invoice);

        $this->assertNotEmpty($xml);
        $this->assertSchema($xml);
    }

    public function testInvoiceFilename()
    {
        /**@var $invoice Invoice*/
        $invoice = $this->createDocument(InvoiceStore::class);
        $filename = $invoice->getName();

        $this->assertEquals($this->getFilename($invoice), $filename);
    }

    private function getFileName(Invoice $invoice)
    {
        $parts = [
            $invoice->getCompany()->getRuc(),
            $invoice->getTipoDoc(),
            $invoice->getSerie(),
            $invoice->getCorrelativo(),
        ];

        return join('-', $parts);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Giansalex
 * Date: 16/07/2017
 * Time: 22:54
 */

declare(strict_types=1);

namespace Tests\Greenter\Xml\Builder;

use Greenter\Data\Generator\BoletaStore;
use Greenter\Data\Generator\InvoiceFullStore;
use Greenter\Data\Generator\InvoiceStore;
use Greenter\Model\Sale\Invoice;
use PHPUnit\Framework\TestCase;

/**
 * Class FeInvoiceBuilderTest
 * @package Tests\Greenter\Xml\Builder
 */
class FeInvoiceBuilderTest extends TestCase
{
    use FeBuilderTrait;
    use XsdValidatorTrait;

    public function testCreateXmlInvoice()
    {
        $invoice = $this->createDocument(InvoiceFullStore::class);

        $xml = $this->build($invoice);

        $this->assertNotEmpty($xml);
        $this->assertSchema($xml);
    }

    public function testInvoiceFilename()
    {
        /**@var $invoice Invoice*/
        $invoice = $this->createDocument(InvoiceStore::class);
        $filename = $invoice->getName();

        $this->assertEquals($this->getFilename($invoice), $filename);
    }

    public function testCreateXmlBoleta()
    {
        $invoice = $this->createDocument(BoletaStore::class);

        $xml = $this->build($invoice);

        $this->assertNotEmpty($xml);
        $this->assertSchema($xml);
    }

    private function getFileName(Invoice $invoice)
    {
        $parts = [
            $invoice->getCompany()->getRuc(),
            $invoice->getTipoDoc(),
            $invoice->getSerie(),
            $invoice->getCorrelativo(),
        ];

        return join('-', $parts);
    }
}

Add boleta xml generator tests

Add boleta xml generator tests


<?php

/**
 * This file is part of the <name> project.
 *
 * (c) <yourname> <youremail>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Application\Sonata\CommentBundle\Entity;

use FOS\CommentBundle\Model\SignedCommentInterface;
use Sonata\CommentBundle\Entity\BaseComment as BaseComment;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @author <yourname> <youremail>
 */
class Comment extends BaseComment implements SignedCommentInterface
{
    /**
     * @var integer $id
     */
    protected $id;

    /**
     * @var UserInterface
     */
    protected $author;

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

    /**
     * {@inheritdoc}
     */
    public function setAuthor(UserInterface $author)
    {
        $this->author = $author;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthorName()
    {
        return $this->getAuthor() ? $this->getAuthor()->getUsername() : 'Anonymous';
    }
}

<?php

/**
 * This file is part of the <name> project.
 *
 * (c) <yourname> <youremail>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Application\Sonata\CommentBundle\Entity;

use Sonata\CommentBundle\Entity\BaseComment as BaseComment;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @author <yourname> <youremail>
 */
class Comment extends BaseComment
{
    /**
     * @var integer $id
     */
    protected $id;

    /**
     * @var UserInterface
     */
    protected $author;

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

Update comments to do not use signed interface


<?php

namespace Becklyn\AssetsBundle\File;

use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;

class FileTypeRegistry
{
    /**
     * @var array<string,FileType>
     */
    private $extensions = [];

    /**
     * @var GenericFile
     */
    private $genericFileType;

    /**
     *
     * @param array $fileTypes
     */
    public function __construct (array $fileTypes)
    {
        $this->extensions = [
            "js" => new JavaScriptFile(),
            "css" => new CssFile(),
            "svg" => new SvgFile(),
        ];
        $this->genericFileType = new GenericFile();
    }

    /**
     * @param Asset $asset
     * @return FileType
     */
    public function getFileType (Asset $asset) : FileType
    {
        return $this->extensions[$asset->getFileType()] ?? $this->genericFileType;
    }

    /**
     * Returns whether the given asset should be imported deferred
     *
     * @param Asset $asset
     * @return bool
     */
    public function importDeferred (Asset $asset) : bool
    {
        $fileType = $this->getFileType($asset);
        return $fileType->importDeferred();
    }
}

<?php

namespace Becklyn\AssetsBundle\File;

use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;

class FileTypeRegistry
{
    /**
     * The file types mapped by file extension
     *
     * @var array<string,FileType>
     */
    private $fileTypes = [];

    /**
     * @var GenericFile
     */
    private $genericFileType;

    /**
     *
     * @param array $fileTypes
     */
    public function __construct (array $fileTypes, GenericFile $genericFileType)
    {
        $this->fileTypes = $fileTypes;
        $this->genericFileType = $genericFileType;
    }

    /**
     * @param Asset $asset
     * @return FileType
     */
    public function getFileType (Asset $asset) : FileType
    {
        return $this->fileTypes[$asset->getFileType()] ?? $this->genericFileType;
    }

    /**
     * Returns whether the given asset should be imported deferred
     *
     * @param Asset $asset
     * @return bool
     */
    public function importDeferred (Asset $asset) : bool
    {
        $fileType = $this->getFileType($asset);
        return $fileType->importDeferred();
    }
}

Refactor file type registry to use services


<?php

namespace Knplabs\Bundle\MarkdownBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class KnplabsMarkdownBundle extends BaseBundle
{
    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

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

<?php

namespace Knplabs\Bundle\MarkdownBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class KnplabsMarkdownBundle extends BaseBundle
{
}

Remove useless code from the bundle class


<?php

/*
 * This file is part of Psy Shell.
 *
 * (c) 2012-2018 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Test\CodeCleaner;

use Psy\CodeCleaner\NoReturnValue;
use Psy\Test\ParserTestCase;

class NoReturnValueTest extends ParserTestCase
{
    public function testCreate()
    {
        $code = [NoReturnValue::create()];
        $this->assertSame('new \\Psy\CodeCleaner\\NoReturnValue()', $this->prettyPrint($code));
    }
}

<?php

/*
 * This file is part of Psy Shell.
 *
 * (c) 2012-2018 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Test\CodeCleaner;

use PhpParser\Node\Stmt\Expression;
use Psy\CodeCleaner\NoReturnValue;
use Psy\Test\ParserTestCase;

class NoReturnValueTest extends ParserTestCase
{
    public function testCreate()
    {
        $stmt = NoReturnValue::create();
        if (class_exists('PhpParser\Node\Stmt\Expression')) {
            $stmt = new Expression($stmt);
        }

        $this->assertSame(
            $this->prettyPrint($this->parse('new \\Psy\CodeCleaner\\NoReturnValue()')),
            $this->prettyPrint([$stmt])
        );
    }
}

Update noreturnvalue test for PhpParser 3.x.


<?php

namespace Ident\Test\Doctrine;

use Doctrine\DBAL\Types\Type;

/**
 * Class AbstractUuidTypeTest
 */
abstract class AbstractUuidTypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var mixed
     */
    private $signature;

    /**
     * @var \Ident\IdentifiesObjects
     */
    private $identifier;

    private $platform;

    /**
     * @var \Doctrine\DBAL\Types\Type
     */
    private $type;

    abstract public function instanceProvider();

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        list($typeClass, $idClass, $this->signature) = $this->instanceProvider();
        $this->identifier = $idClass::fromSignature($this->signature);

        $typeName = constant($typeClass . '::NAME');

        try {
            Type::getType($typeName);
        } catch (\Exception $e) {
            Type::addType($typeName, $typeClass);
        }

        $this->type = Type::getType($typeName);

        $this->platform = $this->getMockBuilder('Doctrine\DBAL\Platforms\AbstractPlatform')
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
    }

    /**
     * @test
     */
    public function shouldGenerateFromIdentifier()
    {
        $signature = $this->type->convertToDatabaseValue($this->identifier, $this->platform);
        $this->assertEquals($this->signature, $signature);
    }

    /**
     * @test
     */
    public function shouldGenerateFromSignature()
    {
        $identifier = $this->type->convertToPHPValue($this->signature, $this->platform);
        $this->assertEquals($this->identifier, $identifier);
    }
}

<?php

namespace Ident\Test\Doctrine;

use Doctrine\DBAL\Types\Type;

/**
 * Class AbstractUuidTypeTest
 */
abstract class AbstractUuidTypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var mixed
     */
    private $signature;

    /**
     * @var \Ident\IdentifiesObjects
     */
    private $identifier;

    private $platform;

    /**
     * @var \Doctrine\DBAL\Types\Type
     */
    private $type;

    abstract public function instanceProvider();

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        list($typeClass, $idClass, $this->signature) = $this->instanceProvider();
        $this->identifier = $idClass::fromSignature($this->signature);

        $typeName = constant($typeClass . '::NAME');

        if (!Type::hasType($typeName)) {
            Type::addType($typeName, $typeClass);
        }

        $this->type = Type::getType($typeName);

        $this->platform = $this->getMockBuilder('Doctrine\DBAL\Platforms\AbstractPlatform')
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
    }

    /**
     * @test
     */
    public function shouldGenerateFromIdentifier()
    {
        $signature = $this->type->convertToDatabaseValue($this->identifier, $this->platform);
        $this->assertEquals($this->signature, $signature);
    }

    /**
     * @test
     */
    public function shouldGenerateFromSignature()
    {
        $identifier = $this->type->convertToPHPValue($this->signature, $this->platform);
        $this->assertEquals($this->identifier, $identifier);
    }
}

Use Type::hasType to check for existing type


<?php

namespace Gedmo\SoftDeleteable\Traits;

/**
 * SoftDeletable Trait, usable with PHP >= 5.4
 *
 * @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
 * @link http://www.gediminasm.org
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
trait SoftDeleteableEntity
{
    /**
     * @ORM\Column(type="datetime")
     */
    protected $deletedAt;

    /**
     * Sets deletedAt.
     *
     * @param \Datetime|null $deletedAt
     * @return $this
     */
    public function setDeletedAt(\DateTime $deletedAt = null)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * Returns deletedAt.
     *
     * @return DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }
}

<?php

namespace Gedmo\SoftDeleteable\Traits;

/**
 * SoftDeletable Trait, usable with PHP >= 5.4
 *
 * @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
 * @link http://www.gediminasm.org
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
trait SoftDeleteableEntity
{
    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $deletedAt;

    /**
     * Sets deletedAt.
     *
     * @param \Datetime|null $deletedAt
     * @return $this
     */
    public function setDeletedAt(\DateTime $deletedAt = null)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * Returns deletedAt.
     *
     * @return DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }
}

Allow deletedAt to be nullable

Allow deletedAt to be nullable


<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->index('is_locked');
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropIndex(['is_locked']);
        });
    }
];

<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->index('is_locked');

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->dropIndex(['is_locked']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


Hi {{ $assignment->user->preferred_first_name }},

@if(!$assignment->tar_received && $assignment->travel->tar_required)
You still need to submit a Travel Authority Request for {{ $assignment->travel->name }}. Please visit {{ route('docusign.travel') }} to fill out and sign it.
@endif

@if(!$assignment->is_paid)
You{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? ' also': '' }} still need to make a ${{ intval($assignment->travel->fee_amount) }} payment{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? '' : ' for '.$assignment->travel->name }}.

You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($assignment->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments.

If you would prefer to pay by cash or check, make arrangements with {{ $assignment->travel->primaryContact->full_name }}.

Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it!
@endif

For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $assignment->travel->primaryContact->full_name }}.

----

To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.

Remove extra whitespace in reminder email


<?php

namespace App\Http\Middleware;

use Closure;

class PreventBackHistory
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
    }
}

<?php

namespace App\Http\Middleware;

use Closure;

class PreventBackHistory
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $headers = [
            'Cache-Control'      => 'nocache, no-store, max-age=0, must-revalidate',
            'Pragma'     => 'no-cache',
            'Expires' => 'Sun, 02 Jan 1990 00:00:00 GMT'
        ];
        $response = $next($request);
        foreach($headers as $key => $value) {
            $response->headers->set($key, $value);
        }

        return $response;
    }
}

Set headers in a different manner in the middleware


<?php
/*
 * Copyright 2014 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */

// Original source: http://stackoverflow.com/a/9526005/953022
class CustomAutoloader{
	public function __construct()
	{
		spl_autoload_register(array($this, 'loader'));
	}

	public function loader($className)
	{
		$base_paths = array(
			APPPATH,
			APPPATH."/third_party/mockery/library/",
		);

		foreach ($base_paths as $base_path) {
			$path = $base_path.str_replace('\\', DIRECTORY_SEPARATOR, $className).'.php';
			if (file_exists($path)) {
				require $path;
				return;
			}
		}
	}
}

<?php
/*
 * Copyright 2014 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */

// Original source: http://stackoverflow.com/a/9526005/953022
class CustomAutoloader{
	public function __construct()
	{
		spl_autoload_register(array($this, 'loader'));
	}

	public function loader($className)
	{
		$namespaces = array(
			'' => [
				["path" => APPPATH],
				["path" => APPPATH."/third_party/mockery/library/"]
			],
		);

		foreach ($namespaces as $namespace => $search_items) {
			if ($namespace === '' || strpos($className, $namespace) === 0) {
				foreach ($search_items as $search_item) {
					$nameToLoad = str_replace($namespace, '', $className);
					$path = $search_item['path'].str_replace('\\', DIRECTORY_SEPARATOR, $nameToLoad).'.php';
					if (file_exists($path)) {
						require $path;
						return;
					}
				}
			}
		}
	}
}

Autoloader: Support PSR-4 style namespace/directory mapping

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>


<?php

namespace Benrowe\Formatter;

/**
 * Formatter Provider interface
 *
 * Provide a standard format interface for Providers to adher to
 *
 * @package Benrowe\Formatter
 */
interface FormatterProvider
{
    /**
     * Describes the formats that this formatter provides
     *
     * @return string[]
     */
    public function formats();

    /**
     * Checks if the format exists
     *
     * @param  string  $format
     * @return boolean
     */
    public function hasFormat($format);

    /**
     * Format the corresponding value to the format provided
     *
     * @param  mixed $value
     * @param  array $params
     * @return mixed
     */
    public function format($value, array $params = []);
}

<?php

namespace Benrowe\Formatter;

/**
 * Formatter Provider interface
 *
 * Provide a standard format interface for Providers to adher to
 *
 * @package Benrowe\Formatter
 */
interface FormatterProvider
{
    /**
     * Describes the formats that this formatter provides
     *
     * @return string[]
     */
    public function formats();

    /**
     * Checks if the format exists
     *
     * @param  string  $format
     * @return boolean
     */
    public function hasFormat($format);

    /**
     * Format the corresponding value to the format provided
     *
     * @param  mixed $value
     * @param  string|array $format either the format as a string, or an array,
     *                              where the first element is the format type
     * @return mixed
     */
    public function format($value, $format = null);
}

Update FormatProvider::format() signature so it doesnt force an array


<?php
return function() {
    $randomWord = function() {
        $word = '';
        $length = rand(1, 20);
        for ($i = 0; $i < $length; $i++) {
            $word .= chr(rand(97, 122));
        }

        return $word;
    };

    return [
        'randomWord' => $randomWord,
        'randomSentence' => function() use ($randomWord) {
            $words = [];
            $length = rand(5, 20);
            for ($i = 0; $i < $length; $i++) {
                $word = $randomWord();
                if (rand(0, 5) === ',') {
                    $word .= ',';
                }

                $words[] = $word;
            }

            $punctuation = '.!?';
            return implode(' ', $words) . $punctuation[rand(0, strlen($punctuation) - 1)];
        },
    ]
};

<?php
return function() {
    $randomWord = function() {
        $word = '';
        $length = rand(1, 20);
        for ($i = 0; $i < $length; $i++) {
            $word .= chr(rand(97, 122));
        }

        return $word;
    };

    return [
        'randomWord' => $randomWord,
        'randomSentence' => function() use ($randomWord) {
            $words = [];
            $length = rand(5, 20);
            for ($i = 0; $i < $length; $i++) {
                $word = $randomWord();
                if (rand(0, 5) === 0) {
                    $word .= ',';
                }

                $words[] = $word;
            }

            $punctuation = '.!?';
            return implode(' ', $words) . $punctuation[rand(0, strlen($punctuation) - 1)];
        },
    ]
};

Fix bug in sentence generator.

Fix bug in sentence generator.

No commas were ever going to be added.


<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Router\Helper;

use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;

/**
 *
 * Generic Url Helper class
 *
 * @package Aura.Router
 *
 */
class Url
{
    /**
     *
     * The Generator object used by the RouteContainer
     *
     * @var Generator
     *
     */
    protected $generator;

    /**
     *
     * Constructor.
     *
     * @param Generator $generator The generator object to use
     *
     */
    public function __construct(Generator $generator)
    {
        $this->generator = $generator;
    }

    /**
     *
     * Returns the Generator
     *
     * @param string|null $name The name of the route to lookup.
     *
     * @param array $data The data to pass into the route
     *
     * @return Generator|string|false The generator object, or the results of {Aura\Router\Generator::generate()}
     *                                when $name is null
     *
     * @throws RouteNotFound When the route cannot be found, thrown by {Aura\Router\Generator::generate()}
     *
     */
    public function __invoke($name = null, array $data = [])
    {
        return $name === null
            ? $this->generator
            : $this->generator->generate($name, $data);
    }
}

<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/mit-license.php MIT
 *
 */
namespace Aura\Router\Helper;

use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;

/**
 *
 * Generic Url Helper class
 *
 * @package Aura.Router
 *
 */
class Url
{
    /**
     *
     * The Generator object used by the RouteContainer
     *
     * @var Generator
     *
     */
    protected $generator;

    /**
     *
     * Constructor.
     *
     * @param Generator $generator The generator object to use
     *
     */
    public function __construct(Generator $generator)
    {
        $this->generator = $generator;
    }

    /**
     *
     * Returns the Generator
     *
     * @param string|null $name The name of the route to lookup.
     *
     * @param array $data The data to pass into the route
     *
     * @return Generator|string|false The generator object, or the results of {Aura\Router\Generator::generate()}
     *                                when $name is null
     *
     * @throws RouteNotFound When the route cannot be found, thrown by {Aura\Router\Generator::generate()}
     *
     */
    public function __invoke($name = null, array $data = [])
    {
        return $name === null
            ? $this->generator
            : $this->generator->generate($name, $data);
    }
}

Change license to MIT to match the project


<?php

namespace Codeception\Module;

/**
 * Class WebHelper - ddefine custom functions for WebGuy.
 */
class WebHelper extends \Codeception\Module
{
}

<?php

namespace Codeception\Module;

/**
 * Class WebHelper - define custom functions for WebGuy.
 */
class WebHelper extends \Codeception\Module
{
}

Correct typo in class description.

Correct typo in class description.


	{{ $label }}
    @if (isset($options) && is_array($options))
        <?php if (isset($value)): $val = $value; elseif (is_bool(Form::getValueAttribute($name))): $val = (int) Form::getValueAttribute($name); else: $val = null; endif; ?>
        {!! Form::select($name, $options, $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
    @elseif (isset($type))
        {!! Form::select($name, [
            '1' => trans(sprintf('mconsole::forms.options.%s.enabled', $type)),
            '0' => trans(sprintf('mconsole::forms.options.%s.disabled', $type)),
        ], (isset($value)) ? $value : is_bool(Form::getValueAttribute($name)) ? (int) Form::getValueAttribute($name) : null, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
    @endif

	{{ $label }}
    <?php if (isset($value)): $val = $value; elseif (is_bool(Form::getValueAttribute($name))): $val = (int) Form::getValueAttribute($name); else: $val = null; endif; ?>
    @if (isset($options) && is_array($options))
        {!! Form::select($name, $options, $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
    @elseif (isset($type))
        {!! Form::select($name, [
            '1' => trans(sprintf('mconsole::forms.options.%s.enabled', $type)),
            '0' => trans(sprintf('mconsole::forms.options.%s.disabled', $type)),
        ], $val, ['class' => sprintf('form-control %s', isset($class) ? $class : null)]) !!}
    @endif

Fix select form component values

Fix select form component values


<?php

/*
 * This file is part of the broadway/broadway package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (file_exists($file = __DIR__ . '/../vendor/autoload.php')) {
    $loader = require_once $file;
    $loader->add('Broadway', __DIR__);
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

<?php

/*
 * This file is part of the broadway/broadway package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (file_exists($file = __DIR__ . '/../vendor/autoload.php')) {
    $loader = require $file;
    $loader->add('Broadway', __DIR__);
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

Use require instead of require_once when retrieving loader


<?php

class Documentation {
    private $_filename;

    public function __construct($filename) {
        $this->_filename = $filename;
    }

    public function __toString() {
        return '<form action="http://www.chippanfire.com/cpf_media/software/' . $this->_filename . '" method="GET">'
            . '<button type="submit" class="btn btn-success">Download Documentation</button>'
            . '</form>';
    }

}

<?php

class Documentation {
    private $_filename;

    public function __construct($filename) {
        $this->_filename = $filename;
    }

    public function __toString() {
        return '<form action="assets/downloads/documentation/' . $this->_filename . '" method="GET">'
            . '<button type="submit" class="btn btn-success">Download Documentation</button>'
            . '</form>';
    }

}

Move documentation downloads into site/assets/downloads/documentation