<?php
/**
 * Validation library.
 *
 * $Id$
 *
 * @package    Validation
 */
class Validation extends Validation_Core {

    // {{{ Properties

    // Names
    protected $names = array();

    // }}}
    // {{{ factory
    public static function factory($array = NULL)
    {
        $data = array_slice(Router::$arguments, 1);
        $data = (Router::$request_method === 'read' && is_array($data)) ? $data : $_POST;

        return new Validation( ! is_array($array) ? $data : $array);
    }
    // }}}
    // {{{ name
    /**
     * @chainable
     * @param     string   Field
     * @param     string   Field name
     */
    public function name($field, $name)
    {
        $this->names[$field] = $name;

        return $this;
    }
    // }}}
    // {{{ names
    public function & names()
    {
        return $this->names;
    }
    // }}}

} // End Validation

<?php
/**
 * Validation library.
 *
 * $Id$
 *
 * @package    Validation
 */
class Validation extends Validation_Core {

    // {{{ Properties

    // Names
    protected $names = array();

    // }}}
    // {{{ factory
    public static function factory($array = NULL)
    {
        $data = array_slice(Router::$arguments, 1);
        $data = (Router::$request_method === 'read' && is_array($data)) ? $data : $_POST;

        return new Validation( ! is_array($array) ? $data : $array);
    }
    // }}}
    // {{{ name
    /**
     * @chainable
     * @param     string   Field
     * @param     string   Field name
     */
    public function name($field, $name)
    {
        $this->names[$field] = $name;

        return $this;
    }
    // }}}
    // {{{ names
    public function & names()
    {
        return $this->names;
    }
    // }}}
    // {{{ min
    public function min($field, array $inputs)
    {
        $result = False;
        if ((int)$field >= (int)current($inputs)) {
            $result = True;
        }
        return $result;
    }
    // }}}
    // {{{ max
    public function max($field, array $inputs)
    {
        $result = False;
        if ((int)$field <= (int)current($inputs)) {
            $result = True;
        }
        return $result;
    }
    // }}}

} // End Validation

Add "min" and "max" to validations.

Add "min" and "max" to validations.


<?php

namespace Becklyn\RadBundle\Entity\Extension;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
trait EntityTimestamps
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="time_created", type="datetime")
     */
    private $timeCreated;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="time_modified", type="datetime", nullable=true)
     */
    private $timeModified;

    /**
     * @return \DateTime
     */
    public function getTimeCreated ()
    {
        return $this->timeCreated;
    }

    /**
     * @return \DateTime|null
     */
    public function getTimeModified ()
    {
        return $this->timeModified;
    }

    /**
     * @param \DateTime $timeModified
     */
    public function setTimeModified (\DateTime $timeModified)
    {
        $this->timeModified = $timeModified;
    }
}

<?php

namespace Becklyn\RadBundle\Entity\Extension;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
trait EntityTimestamps
{
    /**
     * @var \DateTime
     * @ORM\Column(name="time_created", type="datetime")
     */
    private $timeCreated;

    /**
     * @var \DateTime|null
     * @ORM\Column(name="time_modified", type="datetime", nullable=true)
     */
    private $timeModified;

    /**
     * @return \DateTime
     */
    public function getTimeCreated ()
    {
        return $this->timeCreated;
    }

    /**
     * @return \DateTime|null
     */
    public function getTimeModified ()
    {
        return $this->timeModified;
    }

    /**
     * @param \DateTime $timeModified
     */
    public function setTimeModified (\DateTime $timeModified)
    {
        $this->timeModified = $timeModified;
    }
}

Change CodeStyling for more consistency

Change CodeStyling for more consistency

- 2 empty lines after usestatement
- No empty line after variable typedefinition


<?php

namespace Faker\Provider\en_NZ;

class Internet extends \Faker\Provider\Internet
{
    /**
     * An array of common en_NZ (New Zeland) TLD's
     * @var array
     */
    protected static $tld = array(
        'com', 'co.nz', 'ac.nz', 'geek.nz', 'gen.nz', 'kiwi.nz', 'maori.nz', 'net.nz', 'org.nz', 'school.nz', 'govt.nz', 'iwi.nz', 'mil.nz', 'health.nz', 'parliment.nz'
    );
}

<?php

namespace Faker\Provider\en_NZ;

class Internet extends \Faker\Provider\Internet
{
    /**
     * An array of common en_NZ (New Zeland) TLD's
     * @var array
     */
    protected static $tld = array(
        'com', 'nz', 'ac.nz', 'co.nz', 'geek.nz', 'gen.nz', 'kiwi.nz', 'maori.nz', 'net.nz', 'org.nz', 'school.nz', 'cri.nz', 'govt.nz', 'health.nz', 'iwi.nz', 'mil.nz', 'parliament.nz',
    );
}

Add .nz 1st level, expand 2nd level domains

- Adds .nz
- Adds missing cri.nz
- Correct spelling of parliament.nz


<?php

namespace App\Catalog\Category;

use Moltin\SDK\Facade\Moltin as Moltin;
use Moltin\SDK\Facade\Product as Product;

class CategoryList
{
    private $response;

    public function __invoke(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface $response
    ) {
        $this->response = $response;
        // Authenticate credentials
        Moltin::Authenticate('ClientCredentials', [
            'client_id'     => getenv('MOLTIN_CLIENT_ID'),
            'client_secret' => getenv('MOLTIN_CLIENT_SECRET')
        ]);

        $products = Product::Listing();

        if (!empty($products)) {
            $this->response->write(
                sprintf(
                    'We have %d product(s)!',
                    count($products['result'])
                )
            );

            array_walk(
                $products['result'],
                [$this, 'displayProductDetails']
            );
        }

        return $this->response;
    }

    private function displayProductDetails($product)
    {
        $this->response->write($product['sku']);
    }
}

<?php

namespace App\Catalog\Category;

use Moltin\SDK\Facade\Moltin as Moltin;
use Moltin\SDK\Facade\Product as Product;

class CategoryList
{
    /**
     * @var \Psr\Http\Message\ResponseInterface
     */
    private $response;

    public function __invoke(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface $response
    ) {
        $this->response = $response;

        // Authenticate credentials
        Moltin::Authenticate('ClientCredentials', [
            'client_id'     => getenv('MOLTIN_CLIENT_ID'),
            'client_secret' => getenv('MOLTIN_CLIENT_SECRET')
        ]);

        $products = Product::Listing();

        if (!empty($products)) {
            $this->response->write(
                sprintf(
                    'We have %d product(s)!',
                    count($products['result'])
                )
            );

            array_walk(
                $products['result'],
                [$this, 'displayProductDetails']
            );
        }

        return $this->response;
    }

    private function displayProductDetails($product, $key)
    {
        $this->response->write('
');
        $this->response->write('ProductNumber: ' . $key . '
');
        $this->response->write(
            sprintf(
                'Sku: %s',
                $product['sku']
            )
        );
    }
}

Extend display product details to show product number in the list


<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

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

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('pass');

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->getKey();
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->pass;
	}

	/**
	 * Get the e-mail address where password reminders are sent.
	 *
	 * @return string
	 */
	public function getReminderEmail()
	{
		return $this->email;
	}

}

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

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

	/**
	 * Should deleted_at be used
	 *
	 * @var bool
	 */
	protected $softDeletes = true;

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('pass');

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->getKey();
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->pass;
	}

	/**
	 * Get the e-mail address where password reminders are sent.
	 *
	 * @return string
	 */
	public function getReminderEmail()
	{
		return $this->email;
	}

}

Allow soft deletion of users

Allow soft deletion of users


<?php

namespace Phug\Parser\Node;

use Phug\Parser\Node;
use Phug\Util\Partial\AttributeTrait;
use Phug\Util\Partial\NameTrait;

class VariableNode extends Node
{
    use NameTrait;
    use AttributeTrait;
}

<?php

namespace Phug\Parser\Node;

use Phug\Parser\Node;
use Phug\Util\Partial\NameTrait;

class VariableNode extends Node
{
    use NameTrait;
}

Remove Attribute trait from Variable node


<?php
	$job = new Job($id);
	if ($extra != '' && $extra == $job->GetAuth())
	{
		$later_edit = true;
		$_SESSION['later_edit'] = $extra;
	}
	else
	{
		$later_edit = false;
		$_SESSION['later_edit'] = '';
	}

	if ($_SESSION['referer'] != BASE_URL . 'post/')
	{
		if (!$_SESSION['later_edit'])
		{
			redirect_to(BASE_URL . 'job/' . $id . '/');
			exit;
		}
	}

	$jobs = $job->GetInfo();
	if (strstr($jobs['description'], '*'))
	{
		$jobs['description'] = $textile->TextileThis($jobs['description']);
	}
	else
	{
		//$jobs['description'] = nl2br($jobs['description']);
		$jobs['description'] = str_replace(array("\r\n", "\r", "\n"), "<br />", $jobs['description']);
	}
	$smarty->assign('job', $jobs);
	$html_title = stripslashes($jobs['title']) . ' la ' . stripslashes($jobs['company']) . ' / ' . SITE_NAME;
	$template = 'publish-verify.tpl';
?>

<?php
	$job = new Job($id);
	if ($extra != '' && $extra == $job->GetAuth())
	{
		$later_edit = true;
		$_SESSION['later_edit'] = $extra;
	}
	else
	{
		$later_edit = false;
		$_SESSION['later_edit'] = '';
	}

	if ($_SESSION['referer'] != BASE_URL . 'post/')
	{
		if (!$_SESSION['later_edit'])
		{
			redirect_to(BASE_URL . 'job/' . $id . '/');
			exit;
		}
	}

	$jobs = $job->GetInfo();
	if (strstr($jobs['description'], '*'))
	{
		$jobs['description'] = $textile->TextileThis($jobs['description']);
	}
	else
	{
		//$jobs['description'] = nl2br($jobs['description']);
		$jobs['description'] = str_replace(array("\r\n", "\r", "\n"), "<br />", $jobs['description']);
	}
	$smarty->assign('job', $jobs);
	$html_title = stripslashes($jobs['title']) . ' at ' . stripslashes($jobs['company']) . ' / ' . SITE_NAME;
	$template = 'publish-verify.tpl';
?>

Change la in pagetitle to at

Change la in pagetitle to at

git-svn-id: bc1bac543ec1b3c003370e43af937eeab92df7a4@180 bc0df05e-133d-0410-bb72-81d3b1e9bcfd


<?php

namespace Rudolf\Component\Helpers\Navigation;

class MenuItem
{
    private $data;

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

    public function setId($id)
    {
        $this->data['id'] = $id;
    }

    public function getId()
    {
        return isset($this->data['id']) ? $this->data['id'] : null;
    }

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

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

    public function getSlug()
    {
        switch ($this->data['item_type']) {
            case 'absolute':
                // $newItems[$key];
                break;
            case 'app':
            default:
                $this->data['slug'] = DIR.'/'.$this->data['slug'];
                break;
        }

        return $this->data['slug'];
    }

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

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

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

    public function getIco()
    {
        return isset($this->data['ico']) ? $this->data['ico'] : null;
    }
}

<?php

namespace Rudolf\Component\Helpers\Navigation;

class MenuItem
{
    private $data;

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

    public function setId($id)
    {
        $this->data['id'] = $id;
    }

    public function getId()
    {
        return isset($this->data['id']) ? $this->data['id'] : null;
    }

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

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

    public function getSlug()
    {
        $slug = $this->data['slug'];

        switch ($this->data['item_type']) {
            case 'absolute':
                // $newItems[$key];
                break;
            case 'app':
            default:
                $slug = DIR.'/'.$slug;
                break;
        }

        return $slug;
    }

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

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

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

    public function getIco()
    {
        return isset($this->data['ico']) ? $this->data['ico'] : null;
    }
}

Fix slug on many method calls

Fix slug on many method calls


<?php
/**
 * Created by PhpStorm.
 * User: evaisse
 * Date: 05/05/15
 * Time: 15:38
 */

namespace evaisse\SimpleHttpBundle\Serializer;

use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

class CustomGetSetNormalizer extends GetSetMethodNormalizer
{
    /**
     * {@inheritdoc}
     */
    public function normalize($object, string $format = null, array $context = array())
    {
        if ($object instanceof \Throwable) {
            return $this->normalizeThrowable($object);
        }
        return parent::normalize($object, $format, $context);
    }

    /**
     * @param \Throwable $e throwable to normalize
     * @return array normalized output
     */
    protected function normalizeThrowable(\Throwable $e)
    {
        $data = array(
            'class'   => get_class($e),
            'message' => $e->getMessage(),
            'code'    => $e->getCode(),
            'file'    => $e->getFile().':'.$e->getLine(),
            'trace'   => $e->getTraceAsString(),
        );

        if ($previous = $e->getPrevious()) {
            $data['previous'] = $this->normalizeThrowable($previous);
        }

        return $data;
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: evaisse
 * Date: 05/05/15
 * Time: 15:38
 */

namespace evaisse\SimpleHttpBundle\Serializer;

use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

class CustomGetSetNormalizer extends GetSetMethodNormalizer
{
    /**
     * {@inheritdoc}
     */
    public function normalize($object, $format = null, array $context = [])
    {
        if ($object instanceof \Throwable) {
            return $this->normalizeThrowable($object);
        }
        return parent::normalize($object, $format, $context);
    }

    /**
     * @param \Throwable $e throwable to normalize
     * @return array normalized output
     */
    protected function normalizeThrowable(\Throwable $e)
    {
        $data = array(
            'class'   => get_class($e),
            'message' => $e->getMessage(),
            'code'    => $e->getCode(),
            'file'    => $e->getFile().':'.$e->getLine(),
            'trace'   => $e->getTraceAsString(),
        );

        if ($previous = $e->getPrevious()) {
            $data['previous'] = $this->normalizeThrowable($previous);
        }

        return $data;
    }

}

Fix normalize signature for sf 4.4

Fix normalize signature for sf 4.4

https://github.com/symfony/serializer/blob/4.4/Normalizer/AbstractObjectNormalizer.php


<?php
namespace Neos\Utility;

/*
 * This file is part of the Neos.Utility.Pdo package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

/**
 * A helper class for handling PDO databases
 *
 */
abstract class PdoHelper
{
    /**
     * Pumps the SQL into the database. Use for DDL only.
     *
     * Important: key definitions with length specifiers (needed for MySQL) must
     * be given as "field"(xyz) - no space between double quote and parenthesis -
     * so they can be removed automatically.
     *
     * @param \PDO $databaseHandle
     * @param string $pdoDriver
     * @param string $pathAndFilename
     * @return void
     */
    public static function importSql(\PDO $databaseHandle, $pdoDriver, $pathAndFilename)
    {
        $sql = file($pathAndFilename, FILE_IGNORE_NEW_LINES & FILE_SKIP_EMPTY_LINES);
        // Remove MySQL style key length delimiters (yuck!) if we are not setting up a MySQL db
        if ($pdoDriver !== 'mysql') {
            $sql = preg_replace('/"\([0-9]+\)/', '"', $sql);
        }

        $statement = '';
        foreach ($sql as $line) {
            $statement .= ' ' . trim($line);
            if (substr($statement, -1) === ';') {
                $databaseHandle->exec($statement);
                $statement = '';
            }
        }
    }
}

<?php
namespace Neos\Utility;

/*
 * This file is part of the Neos.Utility.Pdo package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

/**
 * A helper class for handling PDO databases
 *
 */
abstract class PdoHelper
{
    /**
     * Pumps the SQL into the database. Use for DDL only.
     *
     * Important: key definitions with length specifiers (needed for MySQL) must
     * be given as "field"(xyz) - no space between double quote and parenthesis -
     * so they can be removed automatically.
     *
     * @param \PDO $databaseHandle
     * @param string $pdoDriver
     * @param string $pathAndFilename
     * @return void
     */
    public static function importSql(\PDO $databaseHandle, string $pdoDriver, string $pathAndFilename)
    {
        $sql = file($pathAndFilename, FILE_IGNORE_NEW_LINES & FILE_SKIP_EMPTY_LINES);
        // Remove MySQL style key length delimiters (yuck!) if we are not setting up a MySQL db
        if ($pdoDriver !== 'mysql') {
            $sql = preg_replace('/"\([0-9]+\)/', '"', $sql);
        }

        $statement = '';
        foreach ($sql as $line) {
            $statement .= ' ' . trim($line);
            if (substr($statement, -1) === ';') {
                $databaseHandle->exec($statement);
                $statement = '';
            }
        }
    }
}

TASK: Add PHP 7.0 scalar type hints to method arguments and return types


<?php

namespace Juy\CharacterSolver;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Http\Kernel;

class CharacterSolverServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @param \Illuminate\Contracts\Http\Kernel $kernel

     * @return void
     */
    public function boot(Kernel $kernel) {
        // Global middleware
        // Add a new middleware to end of the stack if it does not already exist.
        // https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Http/Kernel.php#L205
        $kernel->pushMiddleware(Middleware\CharacterSolver::class);
    }

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

Change a bracelet to new line

Change a bracelet to new line


<?php namespace GeneaLabs\LaravelCasts\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AssetInjection
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (is_a($response, RedirectResponse::class)) {
            return $response;
        }

        $content = $response->content();

        if (preg_match('/<form/', $content)) {
            return $response->setContent(str_replace(
                '',
                '',
                $content
            ));
        }

        return $response;
    }
}

<?php namespace GeneaLabs\LaravelCasts\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AssetInjection
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (! method_exists($response, 'content')) {
            return $response;
        }

        $content = $response->content();

        if (preg_match('/<form/', $content)) {
            return $response->setContent(str_replace(
                '',
                '',
                $content
            ));
        }

        return $response;
    }
}

Put in a better fix for the asset injection routine


<?php

use Jade\Compiler;

class BugCompiler extends Compiler {

    public function __construct() {

        $this->createStatements();
    }
}

class JadeCompilerExceptionsTest extends PHPUnit_Framework_TestCase {

    /**
     * @expectedException Exception
     */
    public function testHandleEmptyCode() {

        $compiler = new Compiler();
        $compiler->handleCode('');
    }

    /**
     * @expectedException Exception
     */
    public function testNonStringInHandleCode() {

        $compiler = new Compiler();
        $compiler->handleCode(array());
    }

    /**
     * @expectedException Exception
     */
    public function testMissingClosure() {

        $compiler = new Compiler();
        $compiler->handleCode('["foo"');
    }

    /**
     * @expectedException Exception
     */
    public function testCreateEmptyStatement() {

        new BugCompiler();
    }
}

<?php

use Jade\Compiler;

class StatementsBugCompiler extends Compiler {

    public function __construct() {

        $this->createStatements();
    }
}

class ApplyBugCompiler extends Compiler {

    public function __construct() {

        $this->apply('foo', array());
    }
}

class JadeCompilerExceptionsTest extends PHPUnit_Framework_TestCase {

    /**
     * @expectedException Exception
     */
    public function testHandleEmptyCode() {

        $compiler = new Compiler();
        $compiler->handleCode('');
    }

    /**
     * @expectedException Exception
     */
    public function testNonStringInHandleCode() {

        $compiler = new Compiler();
        $compiler->handleCode(array());
    }

    /**
     * @expectedException Exception
     */
    public function testMissingClosure() {

        $compiler = new Compiler();
        $compiler->handleCode('["foo"');
    }

    /**
     * @expectedException Exception
     */
    public function testCreateEmptyStatement() {

        new StatementsBugCompiler();
    }

    /**
     * @expectedException Exception
     */
    public function testBadMethodApply() {

        new ApplyBugCompiler();
    }
}

Test apply on a non-existing method

Test apply on a non-existing method


<?php

return array(
	'account' => array(
		'profile' => 'Редактировать профиль',
		'password' => 'Изменить пароль',
	),

	'extensions' => array(
		'list'      => 'Расширения',
		'configure' => 'Настройки расширения: :name',
	),

	'forgot-password' => 'Забыли пароль',

	'home' => array(
		'list' => 'Главная',
	),

	'login'   => 'Вход',
	'logout'  => 'Выход',

	'resources' => array(
		'list'      => 'Resources',
	),

	'settings' => array(
		'list' => 'Настройки',
	),

	'users' => array(
		'list'   => 'Пользователи',
		'create' => 'Добавить пользователя',
		'update' => 'Редактировать пользователя',
	),

);

<?php

return array(
	'account' => array(
		'profile' => 'Редактировать профиль',
		'password' => 'Изменить пароль',
	),

	'extensions' => array(
		'list'      => 'Расширения',
		'configure' => 'Настройки расширения: :name',
	),

	'forgot-password' => 'Забыли пароль',

	'home' => array(
		'list' => 'Главная',
	),

	'login'   => 'Вход',
	'logout'  => 'Выход',

	'resources' => array(
		'list'      => 'Pесурсы',
	),

	'settings' => array(
		'list' => 'Настройки',
	),

	'users' => array(
		'list'   => 'Пользователи',
		'create' => 'Добавить пользователя',
		'update' => 'Редактировать пользователя',
	),

);

Update Resources translation based on translate.google.com


<?php

/**
 *
 * @todo Add ownership to the apps. So a certain user can administrate his own apps
 */
class AuthAppModel extends spitfire\Model
{

	public function definitions(\spitfire\storage\database\Schema $schema) {
		$schema->appID  = new StringField(20);
		$schema->appSecret = new StringField(50);

		$schema->name   = new StringField(20);
		$schema->icon   = new FileField();

		$schema->appID->setUnique(true);
	}

	public function __toString() {
		return sprintf('App(%s)', $this->name);
	}

}

<?php

/**
 *
 * @todo Add ownership to the apps. So a certain user can administrate his own apps
 */
class AuthAppModel extends spitfire\Model
{

	public function definitions(\spitfire\storage\database\Schema $schema) {
		$schema->appID  = new StringField(20);
		$schema->appSecret = new StringField(50);

		$schema->name   = new StringField(20);
		$schema->icon   = new FileField();

		$schema->appID->setUnique(true);
	}

	public function __toString() {
		return sprintf('App (%s)', $this->name);
	}

}

Fix inconsistent space after model name between App & User models


<?php
/**
 * GitScrum v0.1.
 *
 * @author  Renato Marinho <renato.marinho@s2move.com>
 * @license http://opensource.org/licenses/GPL-3.0 GPLv3
 */
namespace GitScrum\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;

class IssueRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
        ];
    }

    protected function getValidatorInstance()
    {
        $data = $this->all();

        if (isset($data['slug_sprint'])) {
            $data['sprint_id'] = Sprint::where('slug', '=', $data['slug_sprint'])->first()->id;
            unset($data['slug_sprint']);
        }

        $this->getInputSource()->replace($data);

        return parent::getValidatorInstance();
    }
}

<?php
/**
 * GitScrum v0.1.
 *
 * @author  Renato Marinho <renato.marinho@s2move.com>
 * @license http://opensource.org/licenses/GPL-3.0 GPLv3
 */
namespace GitScrum\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;

class IssueRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
        ];
    }

    protected function getValidatorInstance()
    {
        $data = $this->all();

        if (isset($data['slug_sprint']) && !empty($data['slug_sprint'])) {
            $data['sprint_id'] = Sprint::where('slug', '=', $data['slug_sprint'])->first()->id;
            unset($data['slug_sprint']);
        }

        $this->getInputSource()->replace($data);

        return parent::getValidatorInstance();
    }
}

Check if array index has content

Check if array index has content


<?php

namespace estvoyage\statsd\value;

use
	estvoyage\value\world as value
;

abstract class type
{
	use value\string {
		__construct as private;
	}

	protected static
		$instances
	;

	protected static function buildType($value)
	{
		if (! isset(self::$instances[$value]))
		{
			self::$instances[$value] = new static($value);
		}

		return self::$instances[$value];
	}
}

<?php

namespace estvoyage\statsd\value;

use
	estvoyage\value\world as value
;

abstract class type
{
	use value\string {
		__construct as private;
	}

	private static
		$instances
	;

	protected static function buildType($value)
	{
		if (! isset(self::$instances[$value]))
		{
			self::$instances[$value] = new static($value);
		}

		return self::$instances[$value];
	}
}

Improve encapsulation using private instead of protected.


@extends('layouts.app')

@section('sidemenu')
    @include('layouts.menu')
@endsection

@section('content')

            Exhibitions

            @foreach($exhibitions as $exhibition)
                id }}">

                            @foreach($exhibition->titles as $title)
                                {{ $title->language }}:{{ $title->text }}

                            @endforeach
                            @if (sizeof($exhibition->titles)==0)

                                (untitled)

                            @endif

            @endforeach

Add new exhibition

            <form action="newSection" method="POST">
                <input type="submit" name="submit" value="Add new exhibition"/>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
            </form>

@endsection

@extends('layouts.app')

@section('sidemenu')
    @include('layouts.menu')
@endsection

@section('content')

            Exhibitions

            @foreach($exhibitions as $exhibition)
                id }}">

                            @foreach($exhibition->titles as $title)
                                {{ $title->language }}:{{ $title->text }}

                            @endforeach
                            @if (sizeof($exhibition->titles)==0)

                                (untitled)

                            @endif

            @endforeach

Add new exhibition

            <form action="{{ route('newSection') }}" method="POST">
                <input type="submit" name="submit" value="Add new exhibition"/>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
            </form>

@endsection

Fix weird bug when creating new exhibition


<?php
class MixevalQuestionType extends AppModel {
	var $name = 'MixevalQuestionType';
	var $displayField = 'type';
	var $validate = array(
		'type' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $hasMany = array(
		'MixevalQuestion' => array(
			'className' => 'MixevalQuestion',
			'foreignKey' => 'mixeval_question_type_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

}

Fix tab indent in MixevalQuestionType model.

It was using tab indent due to it being autogenerated by cake bake.


<?php

use SideKit\Config\ConfigKit;

return [

    /*
    * --------------------------------------------------------------------------
    * Application
    * --------------------------------------------------------------------------
    *
    * Base class for all application classes. Here we configure the attributes
    * that do not hold any object configuration such as "components" or
    * "modules". The configuration of those properties are within submodules of
    * the same name.
    */

    'id' => 'application-id-tests',

    'basePath' => ConfigKit::config()->getBasePath(),

    'vendorPath' => ConfigKit::config()->getVendorPath(),

    'runtimePath' => ConfigKit::config()->getRuntimePath(),

    'language' => ConfigKit::env()->get('APP_LANGUAGE'),
];

<?php

use SideKit\Config\ConfigKit;

return [

    /*
    * --------------------------------------------------------------------------
    * Application
    * --------------------------------------------------------------------------
    *
    * Base class for all application classes. Here we configure the attributes
    * that do not hold any object configuration such as "components" or
    * "modules". The configuration of those properties are within submodules of
    * the same name.
    */

    'id' => 'application-id-tests',

    'basePath' => ConfigKit::config()->getBasePath(),

    'vendorPath' => ConfigKit::config()->getVendorPath(),

    'runtimePath' => ConfigKit::config()->getRuntimePath(),

    'language' => ConfigKit::env()->get('APP_LANGUAGE'),

    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ]
];

Add bower alias inside test env to reflect correct bower path inside vendor directory


<?php

namespace Doctrine\DBAL\Migrations;

class MigrationsVersion
{
    private static $version = 'v1.5.0';

    public static function VERSION()
    {
        $gitversion = '@git-version@';

        if (self::isACustomPharBuild($gitversion)) {
            return $gitversion;
        }
        return self::$version;
    }

    /**
     * @param $gitversion
     * @return bool
     *
     * Check if doctrine migration is installed by composer or
     * in a modified (not tagged) phar version.
     */
    private static function isACustomPharBuild($gitversion)
    {
        return $gitversion !== '@' . 'git-version@';
    }
}

<?php

namespace Doctrine\DBAL\Migrations;

class MigrationsVersion
{
    private static $version = 'v1.6.2';

    public static function VERSION()
    {
        $gitversion = '@git-version@';

        if (self::isACustomPharBuild($gitversion)) {
            return $gitversion;
        }
        return self::$version;
    }

    /**
     * @param $gitversion
     * @return bool
     *
     * Check if doctrine migration is installed by composer or
     * in a modified (not tagged) phar version.
     */
    private static function isACustomPharBuild($gitversion)
    {
        return $gitversion !== '@' . 'git-version@';
    }
}

Update the version number of doctrine migrations


<?php

namespace BartFeenstra\DependencyRetriever\Retriever;

/**
 * Defines a dependency retriever.
 */
interface Retriever
{

    /**
     * The PCRE pattern that defines a valid dependency retriever name.
     */
    const VALID_NAME_PCRE_PATTERN = '/^[a-z0-9-_]*$/';

    /**
     * Gets the dependency retriever's name.
     *
     * @return string
     *   The value MUST match self::VALID_NAME_PCRE_PATTERN.
     */
    public function getName();

    /**
     * Checks whether a dependency can be retrieved.
     *
     * @param string $id
     *   The ID of the dependency to retrieve.
     *
     * @return bool
     *   Whether the dependency is known.
     */
    public function knowsDependency($id);

    /**
     * Retrieves a dependency.
     *
     * @param string $id
     *   The ID of the dependency to retrieve.
     *
     * @return mixed
     *   The dependency.
     */
    public function retrieveDependency($id);
}

<?php

namespace BartFeenstra\DependencyRetriever\Retriever;

/**
 * Defines a dependency retriever.
 */
interface Retriever
{

    /**
     * The PCRE pattern that defines a valid dependency retriever name.
     */
    const VALID_NAME_PCRE_PATTERN = '/^[a-z0-9-_]*$/';

    /**
     * Gets the dependency retriever's name.
     *
     * @return string
     *   The value MUST match self::VALID_NAME_PCRE_PATTERN.
     */
    public function getName();

    /**
     * Checks whether a dependency can be retrieved.
     *
     * @param string $id
     *   The ID of the dependency to retrieve.
     *
     * @return bool
     *   Whether the dependency is known.
     */
    public function knowsDependency($id);

    /**
     * Retrieves a dependency.
     *
     * @param string $id
     *   The ID of the dependency to retrieve.
     *
     * @return mixed
     *   The dependency.
     *
     * @throws \BartFeenstra\DependencyRetriever\Exception\MissingDependencyException
     *   Thrown if the requested dependency is unknown.
     */
    public function retrieveDependency($id);
}

Document that retrievers must throw an exception when requested to retrieve unknown dependencies.


<?php

use Illuminate\Database\Seeder;
use Northstar\Models\User;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Clear the database.
        DB::table('users')->delete();

        // Create a user with a predetermined ID to use when manually testing endpoints.
        User::create([
            '_id' => '5430e850dt8hbc541c37tt3d',
            'email' => 'test@dosomething.org',
            'mobile' => '5555550100',
            'password' => 'secret',
            'drupal_id' => '100001',
            'addr_street1' => '123',
            'addr_street2' => '456',
            'addr_city' => 'Paris',
            'addr_state' => 'Florida',
            'addr_zip' => '555555',
            'country' => 'US',
            'birthdate' => '12/17/91',
            'first_name' => 'First',
            'last_name' => 'Last',
            'parse_installation_ids' => 'parse-abc123',
        ]);

        // Then create a bunch of randomly-generated test data!
        factory(User::class, 250)->create();
    }
}

<?php

use Illuminate\Database\Seeder;
use Northstar\Models\User;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Clear the database.
        DB::table('users')->delete();

        // Create an example normal & admin user for local development.
        factory(User::class)->create([
            'email' => 'test@dosomething.org',
            'password' => 'secret',
        ]);

        factory(User::class, 'admin')->create([
            'email' => 'admin@dosomething.org',
            'password' => 'secret',
        ]);

        // Then create some randomly-generated test data!
        factory(User::class, 'admin', 4)->create();
        factory(User::class, 'staff', 50)->create();
        factory(User::class, 250)->create();
    }
}

Update seeder with better test users. Add a seeded admin user, and make some random seeded staff users.


<?php

namespace Kanboard\Formatter;

use Kanboard\Core\Filter\FormatterInterface;

/**
 * Class UserMentionFormatter
 *
 * @package Kanboard\Formatter
 * @author  Frederic Guillot
 */
class UserMentionFormatter extends BaseFormatter implements FormatterInterface
{
    protected $users = array();

    /**
     * Set users
     *
     * @param array $users
     * @return $this
     */
    public function withUsers(array $users) {
        $this->users = $users;
        return $this;
    }

    /**
     * Apply formatter
     *
     * @access public
     * @return array
     */
    public function format()
    {
        $result = array();

        foreach ($this->users as $user) {
            $html = $this->helper->avatar->small(
                $user['id'],
                $user['username'],
                $user['name'],
                $user['email'],
                $user['avatar_path'],
                'avatar-inline'
            );

            $html .= ' '.$this->helper->text->e($user['username']);

            if (! empty($user['name'])) {
                $html .= ' <small>'.$this->helper->text->e($user['name']).'</small>';
            }

            $result[] = array(
                'value' => $user['username'],
                'html' => $html,
            );
        }

        return $result;
    }
}

<?php

namespace Kanboard\Formatter;

use Kanboard\Core\Filter\FormatterInterface;

/**
 * Class UserMentionFormatter
 *
 * @package Kanboard\Formatter
 * @author  Frederic Guillot
 */
class UserMentionFormatter extends BaseFormatter implements FormatterInterface
{
    protected $users = array();

    /**
     * Set users
     *
     * @param array $users
     * @return $this
     */
    public function withUsers(array $users) {
        $this->users = $users;
        return $this;
    }

    /**
     * Apply formatter
     *
     * @access public
     * @return array
     */
    public function format()
    {
        $result = array();

        foreach ($this->users as $user) {
            $html = $this->helper->avatar->small(
                $user['id'],
                $user['username'],
                $user['name'],
                $user['email'],
                $user['avatar_path'],
                'avatar-inline'
            );

            $html .= ' '.$this->helper->text->e($user['username']);

            if (! empty($user['name'])) {
                $html .= ' <small aria-hidden="true">'.$this->helper->text->e($user['name']).'</small>';
            }

            $result[] = array(
                'value' => $user['username'],
                'html' => $html,
            );
        }

        return $result;
    }
}

Hide user name from screen readers The user name will be available to screen readers from the adjacent avatar's aria-label


<?php
$url = app('Flarum\Http\UrlGenerator');
?>

{{ $translator->trans('core.views.index.all_discussions_heading') }}

        @foreach ($document->data as $discussion)

                to('forum')->route('discussion', [
                    'id' => $discussion->id . '-' . $discussion->attributes->slug
                ]) }}">
                    {{ $discussion->attributes->title }}

        @endforeach

    @if (isset($document->links->next))
        to('forum')->route('index') }}?page={{ $page + 1 }}">{{ $translator->trans('core.views.index.next_page_button') }} »
    @endif

<?php
$url = app('Flarum\Http\UrlGenerator');
?>

{{ $translator->trans('core.views.index.all_discussions_heading') }}

        @foreach ($document->data as $discussion)

                to('forum')->route('discussion', [
                    'id' => $discussion->id . '-' . $discussion->attributes->slug
                ]) }}">
                    {{ $discussion->attributes->title }}

        @endforeach

    @if (isset($document->links->prev))
        to('forum')->route('index') }}?page={{ $page - 1 }}">« {{ $translator->trans('core.views.index.previous_page_button') }}
    @endif

    @if (isset($document->links->next))
        to('forum')->route('index') }}?page={{ $page + 1 }}">{{ $translator->trans('core.views.index.next_page_button') }} »
    @endif

Add pagination link for previous page

Add pagination link for previous page


<?php namespace Flarum\Core\Seeders;

use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::unguard();

        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
            $user = User::create([
                'username'     => $faker->userName,
                'email'        => $faker->safeEmail,
                'is_activated' => true,
                'password'     => 'password',
                'join_time'    => $faker->dateTimeThisYear
            ]);

            // Assign the users to the 'Member' group, and possibly some others.
            $user->groups()->attach(3);
            if (rand(1, 50) == 1) {
                $user->groups()->attach(4);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(5);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(1);
            }
        }
    }
}

<?php namespace Flarum\Core\Seeders;

use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::unguard();

        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
            $user = User::create([
                'username'     => str_replace('.', '_', $faker->userName),
                'email'        => $faker->safeEmail,
                'is_activated' => true,
                'password'     => 'password',
                'join_time'    => $faker->dateTimeThisYear
            ]);

            // Assign the users to the 'Member' group, and possibly some others.
            $user->groups()->attach(3);
            if (rand(1, 50) == 1) {
                $user->groups()->attach(4);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(5);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(1);
            }
        }
    }
}

Make sure generated usernames cannot break validation


<?php
/**
 * Created by PhpStorm.
 * User: visa
 * Date: 08/07/15
 * Time: 15.28
 */

namespace MailMan\Service;

class MailServiceAwareTrait
{
    protected $mailService;
    /**
     * @return null|MailInterface
     */
    public function getMailService()
    {
        return $this->mailService;
    }

    /**
     * @param MailInterface $mailService
     * @return $this
     */
    public function setMailService(MailInterface $mailService)
    {
        $this->mailService = $mailService;
        return $this;
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: visa
 * Date: 08/07/15
 * Time: 15.28
 */

namespace MailMan\Service;

trait MailServiceAwareTrait
{
    protected $mailService;
    /**
     * @return null|MailInterface
     */
    public function getMailService()
    {
        return $this->mailService;
    }

    /**
     * @param MailInterface $mailService
     * @return $this
     */
    public function setMailService(MailInterface $mailService)
    {
        $this->mailService = $mailService;
        return $this;
    }

}

Fix Interface and trait aware service

Fix Interface and trait aware service


<?php

namespace Kunstmaan\NodeBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Templating\EngineInterface;

class RenderContextListener
{
    /**
     * @var EngineInterface
     */
    protected $templating;

    /**
     * @param EngineInterface $templating
     */
    public function __construct(EngineInterface $templating)
    {
        $this->templating = $templating;
    }

    /**
     * @param GetResponseForControllerResultEvent $event
     */
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request    = $event->getRequest();
        $nodeTranslation = $request->attributes->get('_nodeTranslation');

        if ($nodeTranslation) {
            $entity          = $request->attributes->get('_entity');
            $url             = $request->attributes->get('url');
            $nodeMenu        = $request->attributes->get('_nodeMenu');
            $parameters      = $request->attributes->get('_renderContext');
            $renderContext = array(
                '_nodeTranslation' => $nodeTranslation,
                'slug' => $url,
                'page' => $entity,
                'resource' => $entity,
                'nodemenu' => $nodeMenu,
            );

            if (is_array($parameters)) {
                $parameters = array_merge($renderContext, $parameters);
            } else {
                $parameters = $renderContext;
            }

            // Sent the response here, another option is to let the symfony kernel.view listener handle it
            $event->setResponse($this->templating->renderResponse($entity->getDefaultView(), $parameters));
        }
    }
}

<?php

namespace Kunstmaan\NodeBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Templating\EngineInterface;

class RenderContextListener
{
    /**
     * @var EngineInterface
     */
    protected $templating;

    /**
     * @param EngineInterface $templating
     */
    public function __construct(EngineInterface $templating)
    {
        $this->templating = $templating;
    }

    /**
     * @param GetResponseForControllerResultEvent $event
     */
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request    = $event->getRequest();
        $nodeTranslation = $request->attributes->get('_nodeTranslation');

        if ($nodeTranslation) {
            $entity          = $request->attributes->get('_entity');
            $url             = $request->attributes->get('url');
            $nodeMenu        = $request->attributes->get('_nodeMenu');
            $parameters      = $request->attributes->get('_renderContext');

            $renderContext = array(
                '_nodeTranslation'  => $nodeTranslation,
                'slug'              => $url,
                'page'              => $entity,
                'resource'          => $entity,
                'nodemenu'          => $nodeMenu,
            );

            if (is_array($parameters) || $parameters instanceof \ArrayObject) {
                $parameters = array_merge($renderContext, (array)$parameters);
            } else {
                $parameters = $renderContext;
            }

            // Sent the response here, another option is to let the symfony kernel.view listener handle it
            $event->setResponse($this->templating->renderResponse($entity->getDefaultView(), $parameters));
        }
    }
}

Handle case when RenderContext is not an array but ArrayObject


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Profile Faker / Form / Processing
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

class GenerateProfileFormProcess extends Form
{
    /** @var string */
    private $sProfileType;

    /**
     * @param string $sProfileType The profile type to generate.
     */
    public function __construct($sProfileType)
    {
        $this->sProfileType = $sProfileType;
        $this->generate();
    }

    private function generate()
    {
        $oFakerFactory = new FakerFactory(
            $this->httpRequest->post('amount'),
            $this->httpRequest->post('locale')
        );

        switch ($this->sProfileType) {
            case ProfileType::MEMBER:
                $oFakerFactory->generateMembers();
                break;

            case ProfileType::AFFILIATE:
                $oFakerFactory->generateAffiliates();
                break;

            case ProfileType::SUBSCRIBER:
                $oFakerFactory->generateSubscribers();
                break;
        }
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Profile Faker / Form / Processing
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

class GenerateProfileFormProcess extends Form
{
    /** @var string */
    private $sProfileType;

    /**
     * @param string $sProfileType The profile type to generate.
     *
     * @throws Framework\Mvc\Request\WrongRequestMethodException
     */
    public function __construct($sProfileType)
    {
        $this->sProfileType = $sProfileType;
        $this->generate();

        \PFBC\Form::setSuccess(
            'form_generate_profiles',
            nt('%n% profile has been generated.', '%n% profiles have been generated.', $this->httpRequest->post('amount', 'int'))
        );
    }

    private function generate()
    {
        $oFakerFactory = new FakerFactory(
            $this->httpRequest->post('amount', 'int'),
            $this->httpRequest->post('locale')
        );

        switch ($this->sProfileType) {
            case ProfileType::MEMBER:
                $oFakerFactory->generateMembers();
                break;

            case ProfileType::AFFILIATE:
                $oFakerFactory->generateAffiliates();
                break;

            case ProfileType::SUBSCRIBER:
                $oFakerFactory->generateSubscribers();
                break;
        }
    }
}

Add form success message + cast amount profile to integer


<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */

class JSONDisplayHandler
{

	/**
	 * Produce JSON compliant content given a module object.\n
	 * @param ModuleObject $oModule the module object
	 * @return string
	 */
	public function toDoc($oModule)
	{
		$variables = $oModule->getVariables();
		$variables['error'] = $oModule->getError();
		$variables['message'] = $oModule->getMessage();

		if (Context::getRequestMethod() === 'XMLRPC')
		{
			$temp = array();
			foreach ($variables as $key => $value)
			{
				if (self::_isNumericArray($value))
				{
					$temp[$key] = array_values($value);
				}
				else
				{
					$temp[$key] = $value;
				}
			}
			$variables = $temp;
		}

		return json_encode($variables);
	}

	/**
	 * Check if an array only has numeric keys.
	 *
	 * @param array $array
	 * @return bool
	 */
	protected static function _isNumericArray($array)
	{
		if (!is_array($array) || !count($array))
		{
			return false;
		}
		foreach ($array as $key => $value)
		{
			if (intval($key) != $key)
			{
				return false;
			}
		}
		return true;
	}
}
/* End of file JSONDisplayHandler.class.php */
/* Location: ./classes/display/JSONDisplayHandler.class.php */

<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */

class JSONDisplayHandler
{

	/**
	 * Produce JSON compliant content given a module object.\n
	 * @param ModuleObject $oModule the module object
	 * @return string
	 */
	public function toDoc($oModule)
	{
		$variables = $oModule->getVariables();
		$variables['error'] = $oModule->getError();
		$variables['message'] = $oModule->getMessage();

		$temp = array();
		foreach ($variables as $key => $value)
		{
			if (self::_isNumericArray($value))
			{
				$temp[$key] = array_values($value);
			}
			else
			{
				$temp[$key] = $value;
			}
		}

		return json_encode($temp);
	}

	/**
	 * Check if an array only has numeric keys.
	 *
	 * @param array $array
	 * @return bool
	 */
	protected static function _isNumericArray($array)
	{
		if (!is_array($array) || !count($array))
		{
			return false;
		}
		foreach ($array as $key => $value)
		{
			if (intval($key) != $key)
			{
				return false;
			}
		}
		return true;
	}
}
/* End of file JSONDisplayHandler.class.php */
/* Location: ./classes/display/JSONDisplayHandler.class.php */

Apply numeric array conversion to every JSON request as well


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::get('home', 'HomeController@index');
Route::resource('/contact', 'HomeController@contact');

Route::resource('modelsensor', 'ModelSensorController');
Route::resource('modelmonitor', 'ModelMonitorController');
Route::resource('modelvehicle', 'ModelVehicleController');
Route::resource('modeltire', 'ModelTireController');
Route::resource('typevehicle', 'TypeVehicleController');
Route::resource('user', 'UserController');
Route::get('profile', 'UsersController@showProfile');

Route::bind(
    'users',
    function ($value, $route) {
        return App\User::whereId($value)->first();
    }
);

Route::controllers(
    [
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController'
    ]
);

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::get('home', 'HomeController@index');
Route::resource('/contact', 'HomeController@contact');

Route::resource('modelsensor', 'ModelSensorController');
Route::resource('modelmonitor', 'ModelMonitorController');
Route::resource('modelvehicle', 'ModelVehicleController');
Route::resource('modeltire', 'ModelTireController');
Route::resource('typevehicle', 'TypeVehicleController');
Route::resource('user', 'UserController');
Route::get('profile', 'UserController@showProfile');

Route::bind(
    'users',
    function ($value, $route) {
        return App\User::whereId($value)->first();
    }
);

Route::controllers(
    [
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController'
    ]
);

Fix user controller at route

Fix user controller at route


<?php

class Email {
	public $db = null;
	public $email = '';
	public $from = 'luke@lcahill.co.uk';
	public $subject = 'Note Keeper - please confirm your email.';
	public $message = '';
	public $userId = '';

	function __construct($email, $userId) {
		$this->email = $email;
		$this->userId = $userId;
		require_once '../db-connect.inc.php';
		$this->db = Database::ConnectDb();
	}

	function constructConfirmLink() {
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$confirm = md5($timestamp);

		$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
		$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));

		$url = $_SERVER['SERVER_NAME'];
		$link = 'http://' . $url . '/notes/includes/email-confirmation/confirm.php?hash=' . $this->userId . '&user=' . $this->userId;
		$this->message = 'Please follow this link to confirm your account ' . $link . '';
		$this->sendEmail();
	}

	function sendEmail() {
		mail($this->email, $this->subject, $this->message);
	}
}

?>

<?php

class Email {
	public $db = null;
	public $email = '';
	public $from = 'luke@lcahill.co.uk';
	public $subject = 'Note Keeper - please confirm your email.';
	public $message = '';
	public $userId = '';

	function __construct($email, $userId) {
		$this->email = $email;
		$this->userId = $userId;
		require_once '../db-connect.inc.php';
		$this->db = Database::ConnectDb();
	}

	function constructConfirmLink() {
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$confirm = md5($timestamp);

		$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
		$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));

		$url = $_SERVER['SERVER_NAME'];
		$link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId;
		$this->message = 'Please follow this link to confirm your account ' . $link . '';
		$this->sendEmail();
	}

	function sendEmail() {
		mail($this->email, $this->subject, $this->message);
	}
}

?>

Fix the incorrect URL being generated

Fix the incorrect URL being generated


<?php

namespace Stripe\Exception;

// TODO: remove this check once we drop support for PHP 5
if (interface_exists(\Throwable::class)) {
    /**
     * The base interface for all Stripe exceptions.
     *
     * @package Stripe\Exception
     */
    interface ExceptionInterface extends \Throwable
    {
    }
} else {
    /**
     * The base interface for all Stripe exceptions.
     *
     * @package Stripe\Exception
     */
    // phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
    interface ExceptionInterface
    {
    }
    // phpcs:enable
}

<?php

namespace Stripe\Exception;

// TODO: remove this check once we drop support for PHP 5
if (interface_exists(\Throwable::class, false)) {
    /**
     * The base interface for all Stripe exceptions.
     *
     * @package Stripe\Exception
     */
    interface ExceptionInterface extends \Throwable
    {
    }
} else {
    /**
     * The base interface for all Stripe exceptions.
     *
     * @package Stripe\Exception
     */
    // phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
    interface ExceptionInterface
    {
    }
    // phpcs:enable
}

Disable autoloader when checking for `Throwable`


<?php

namespace Unicodeveloper\Identify;

use Sinergi\BrowserDetector\Browser;

class Identify {

    public function __construct()
    {
        $this->browser = new Browser();
    }

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

<?php

namespace Unicodeveloper\Identify;

use Sinergi\BrowserDetector\Browser;
use Sinergi\BrowserDetector\Os;
use Sinergi\BrowserDetector\Language;

class Identify {

    /**
     * Store the browser object
     * @var object
     */
    protected $browser;

    /**
     * Store the os object
     * @var object
     */
    protected $os;

    /**
     * Store the language object
     * @var object
     */
    protected $language;

    /**
     *  Create an Instance of Browser and Os
     */
    public function __construct()
    {
        $this->os = new Os();
        $this->browser = new Browser();
        $this->language = new Language();
    }

    /**
     * Get all the methods applicable to browser detection
     * e.g getName(), getVersion()
     * @return \Sinergi\BrowserDetector\Browser
     */
    public function browser()
    {
        return $this->browser;
    }

    /**
     * Get all the methods applicable to Os detection
     * e.g getName(), getVersion()
     * @return \Sinergi\BrowserDetector\Os
     */
    public function os()
    {
        return $this->os;
    }

    /**
     * Get all the methods applicable to Language detection
     * @return \Sinergi\BrowserDetector\Language
     */
    public function lang()
    {
        return $this->language;
    }

}

Add language, os and browser methods

feat(package): Add language, os and browser methods


<?php

/*
 * This file is part of Alt Three TestBench.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\TestBench;

use Illuminate\Queue\SerializesModels;
use ReflectionClass;

/**
 * This is the job trait.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
trait JobTrait
{
    use CommandTrait;

    public function testJobSerializesModels()
    {
        $rc = new ReflectionClass($this->getObjectAndParams()['object']);

        $this->assertTrue(in_array(SerializesModels::class, $rc->getTraitNames(), true));
    }
}

<?php

/*
 * This file is part of Alt Three TestBench.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\TestBench;

use Illuminate\Queue\SerializesModels;
use ReflectionClass;

/**
 * This is the job trait.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
trait JobTrait
{
    use CommandTrait;

    public function testJobSerializesModels()
    {
        $data = $this->getObjectAndParams();

        $rc = new ReflectionClass($data['object']);

        if ($data['params']) {
            $this->assertTrue(in_array(SerializesModels::class, $rc->getTraitNames(), true));
        } else {
            $this->assertFalse(in_array(SerializesModels::class, $rc->getTraitNames(), true));
        }
    }
}

Enforce the model serialization trait only if there are params


<?php

/*
|-----------------------------------------------------------
| Create the Theme
|-----------------------------------------------------------
|
| Create a new Theme instance which behaves as singleton.
| This allows for easily bind and resolve various
| parts across all theme components.
|
*/

$theme = Tonik\Gin\Foundation\Theme::getInstance();

/*
 |-----------------------------------------------------------
 | Bind Theme Config
 |-----------------------------------------------------------
 |
 | We neet to bind configs like theme's paths, directories and
 | files to autoload. This values will be used by the rest
 | of theme components like assets, templates etc.
 |
 */

$config = require __DIR__ . '/../config/app.php';

$theme->bind('config', function () use ($config) {
    new Tonik\Gin\Foundation\Config($config);
});

/*
 |-----------------------------------------------------------
 | Return the Theme
 |-----------------------------------------------------------
 |
 | Here we returns the theme instance. Later, this instance
 | is used for autoload all theme's core component.
 |
 */

return $theme;

<?php

/*
|-----------------------------------------------------------
| Create the Theme
|-----------------------------------------------------------
|
| Create a new Theme instance which behaves as singleton.
| This allows for easily bind and resolve various
| parts across all theme components.
|
*/

$theme = Tonik\Gin\Foundation\Theme::getInstance();

/*
 |-----------------------------------------------------------
 | Bind Theme Config
 |-----------------------------------------------------------
 |
 | We neet to bind configs like theme's paths, directories and
 | files to autoload. This values will be used by the rest
 | of theme components like assets, templates etc.
 |
 */

$config = require __DIR__ . '/../config/app.php';

$theme->bind('config', function () use ($config) {
    return new Tonik\Gin\Foundation\Config($config);
});

/*
 |-----------------------------------------------------------
 | Return the Theme
 |-----------------------------------------------------------
 |
 | Here we returns the theme instance. Later, this instance
 | is used for autoload all theme's core component.
 |
 */

return $theme;

Return config instance in closure

Return config instance in closure


<?php

namespace RMiller\LazyBin;

use RMiller\LazyBin\Process\CachingExecutableFinder;
use RMiller\LazyBin\Process\CommandRunner\CliFunctionChecker;
use RMiller\LazyBin\Process\CommandRunner\PassthruCommandRunner;
use RMiller\LazyBin\Process\CommandRunner\PcntlCommandRunner;
use Symfony\Component\Process\PhpExecutableFinder;

class CommandRunner
{
    public function runCommand($command)
    {
        foreach ($this->getProcessRunners() as $runner) {
            if ($runner->isSupported()) {
                $runner->runCommand($this->getExecutableFinder()->getExecutablePath(), explode(' ', $command));
            }
        }
    }

    /**
     * @return CachingExecutableFinder
     */
    private function getExecutableFinder()
    {
        return new CachingExecutableFinder(new PhpExecutableFinder());
    }

    private function getProcessRunners()
    {
        $functionChecker = new CliFunctionChecker($this->getExecutableFinder());

        return [
            new PassthruCommandRunner($functionChecker),
            new PcntlCommandRunner($functionChecker),
        ];
    }
}

<?php

namespace RMiller\LazyBin;

use RMiller\LazyBin\Process\CommandRunner\CliFunctionChecker;
use RMiller\LazyBin\Process\CommandRunner\PassthruCommandRunner;
use RMiller\LazyBin\Process\CommandRunner\PcntlCommandRunner;

class CommandRunner
{
    public function runCommand($command)
    {
        foreach ($this->getProcessRunners() as $runner) {
            if ($runner->isSupported()) {
                $commandArgs = explode(' ', $command);
                $runner->runCommand(array_shift($commandArgs), $commandArgs);
            }
        }
    }

    private function getProcessRunners()
    {
        $functionChecker = new CliFunctionChecker($this->getExecutableFinder());

        return [
            new PassthruCommandRunner($functionChecker),
            new PcntlCommandRunner($functionChecker),
        ];
    }
}

Remove adding php path to the command

Remove adding php path to the command


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\User\Repository;

use Pagerfanta\PagerfantaInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\User\Model\UserInterface;

/**
 * @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface UserRepositoryInterface extends RepositoryInterface
{
    /**
     * @param array $criteria
     * @param array $sorting
     *
     * @return PagerfantaInterface
     */
    public function createFilterPaginator(array $criteria = null, array $sorting = null);

    /**
     * @param mixed $id
     *
     * @return UserInterface|null
     */
    public function findForDetailsPage($id);

    /**
     * @param \DateTime $from
     * @param \DateTime $to
     * @param null|string $status
     *
     * @return int
     */
    public function countBetweenDates(\DateTime $from, \DateTime $to, $status = null);

    /**
     * @param array $configuration
     *
     * @return array
     */
    public function getRegistrationStatistic(array $configuration = []);

    /**
     * @param string $email
     *
     * @return UserInterface|null
     */
    public function findOneByEmail($email);
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\User\Repository;

use Pagerfanta\PagerfantaInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\User\Model\UserInterface;

/**
 * @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface UserRepositoryInterface extends RepositoryInterface
{
    /**
     * @param \DateTime $from
     * @param \DateTime $to
     * @param null|string $status
     *
     * @return int
     */
    public function countBetweenDates(\DateTime $from, \DateTime $to, $status = null);

    /**
     * @param array $configuration
     *
     * @return array
     */
    public function getRegistrationStatistic(array $configuration = []);

    /**
     * @param string $email
     *
     * @return UserInterface|null
     */
    public function findOneByEmail($email);
}

[CoreBundle] Add UserRepository
[UserBundle] Move function which has connection between user and customer to core UserRepository


<?php

namespace Shim\TestSuite;

use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;

/**
 * Enhanced IntegrationTestCase class with debugging tools.
 */
abstract class IntegrationTestCase extends TestCase {

	use IntegrationTestTrait;
	use TestTrait;

	/**
	 * Globally disabling error handler middleware to see the actual errors instead of cloaking.
	 *
	 * You can enable this when you don't explicitly test exception handling for controllers.
	 *
	 * @var bool
	 */
	protected $disableErrorHandlerMiddleware = false;

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

		if (!$this->disableErrorHandlerMiddleware) {
			return;
		}
		$this->disableErrorHandlerMiddleware();
	}

}

<?php

namespace Shim\TestSuite;

use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;

/**
 * Enhanced IntegrationTestCase class with debugging tools.
 */
abstract class IntegrationTestCase extends TestCase {

	use IntegrationTestTrait;
	use TestTrait;

	/**
	 * Globally disabling error handler middleware to see the actual errors instead of cloaking.
	 *
	 * You can enable this when you don't explicitly test exception handling for controllers.
	 *
	 * @var bool
	 */
	protected $disableErrorHandlerMiddleware = false;

	/**
	 * @return void
	 */
	protected function setUp(): void {
		parent::setUp();

		if (!$this->disableErrorHandlerMiddleware) {
			return;
		}
		$this->disableErrorHandlerMiddleware();
	}

}

Use protected visibility as per parent

Use protected visibility as per parent


<?php

class m170222_195519_add_issue_to_draft_prescriptions extends CDbMigration
{
        // Use safeUp/safeDown to do migration with transaction
	public function safeUp()
	{
            $this->execute("INSERT INTO event_issue (event_id, issue_id, last_modified_date, created_date, created_user_id)
                            SELECT pd.event_id, (SELECT id FROM issue WHERE name = 'Draft'), pd.last_modified_date, pd.created_date, pd.created_user_id
                            FROM   et_ophdrprescription_details pd
                            WHERE  pd.draft = 1
                            AND  pd.event_id
                              NOT IN (SELECT event_id FROM event_issue WHERE issue_id = (SELECT id FROM issue WHERE name = 'Draft'));");
	}

	public function safeDown()
	{
            echo "m170222_195519_add_issue_to_draft_prescriptions does not support migration down.\n";
            return false;
	}

}

<?php

class m170222_195519_add_issue_to_draft_prescriptions extends CDbMigration
{
        // Use safeUp/safeDown to do migration with transaction
	public function safeUp()
	{
        $draft_id = $this->dbConnection->createCommand()->select('*')->from('issue')->where('name = :name', array(':name' => 'Draft'))->queryScalar();

        //no Draft in the issue table, we have to add it
        if(!$draft_id){
            $this->insert('issue', array('name' => 'Draft') );
        }

        $this->execute("INSERT INTO event_issue (event_id, issue_id, last_modified_date, created_date, created_user_id)
                            SELECT pd.event_id, (SELECT id FROM issue WHERE name = 'Draft'), pd.last_modified_date, pd.created_date, pd.created_user_id
                            FROM   et_ophdrprescription_details pd
                            WHERE  pd.draft = 1
                            AND  pd.event_id
                              NOT IN (SELECT event_id FROM event_issue WHERE issue_id = (SELECT id FROM issue WHERE name = 'Draft'));");
	}

	public function safeDown()
	{
            echo "m170222_195519_add_issue_to_draft_prescriptions does not support migration down.\n";
            return false;
	}

}

FIX : migration throws an error when there is no Draft in the issue table, this can happen if we install the OE on the first time, blank or sample DB


<?php

namespace Campaign\Model;

class Template
{
    /**
     * @var string
     */
    protected $code;

    /**
     * @param string $code
     */
    public function __construct($code)
    {
        $this->code = $code;
    }

    /**
     * @param Template $other
     *
     * @return bool
     */
    public function equals(Template $other)
    {
        return $this->code === $other->code;
    }
}

<?php

namespace Campaign\Model;

class Template
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $code;

    /**
     * @param string $name
     * @param string $code
     */
    public function __construct($name, $code)
    {
        $this->name = $name;
        $this->code = $code;
    }

    /**
     * @param Template $other
     *
     * @return bool
     */
    public function equals(Template $other)
    {
        return $this->code === $other->code;
    }
}

Add a name to templates

Add a name to templates


<?php

namespace Saft\Data;

interface ParserFactory
{
    /**
     * Creates a Parser instance for a given format, if available.
     *
     * @param  string     $format The format you need a parser for. In case it is not available, an exception
     *                            will be thrown.
     * @return Parser     Suitable parser for the requested format.
     * @throws \Exception If parser for requested format is not available.
     */
    public function createParserFor($format);
}

<?php

namespace Saft\Data;

interface ParserFactory
{
    /**
     * Creates a Parser instance for a given format, if available.
     *
     * @param  string     $serialization The serialization you need a parser for. In case it is not
     *                                   available, an exception will be thrown.
     * @return Parser     Suitable parser for the requested format.
     * @throws \Exception If parser for requested format is not available.
     */
    public function createParserFor($serialization);
}

Correct missing $format > $serialization


<?php

namespace Northstar\Http\Controllers;

class KeyController extends Controller
{
    public function __construct()
    {
        $this->middleware('role:admin');
    }

    /**
     * Return the public key, which can be used by other services
     * to verify JWT access tokens.
     * GET /key
     *
     * @return \Illuminate\Http\Response
     */
    public function show()
    {
        $path = base_path('storage/keys/public.key');
        $publicKey = file_get_contents($path);

        return [
            'algorithm' => 'RS256',
            'issuer' => url('/'),
            'public_key' => $publicKey,
        ];
    }
}

<?php

namespace Northstar\Http\Controllers;

class KeyController extends Controller
{
    public function __construct()
    {
        $this->middleware('role:admin');
    }

    /**
     * Return the public key, which can be used by other services
     * to verify JWT access tokens.
     * GET /key
     *
     * @return array
     */
    public function show()
    {
        $path = base_path('storage/keys/public.key');
        $publicKey = file_get_contents($path);

        return [
            'algorithm' => 'RS256',
            'issuer' => url('/'),
            'public_key' => $publicKey,
        ];
    }
}

Fix docblock for public key route.

Fix docblock for public key route.


<?php

namespace Northstar\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        // ...
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);

        //
    }
}

<?php

namespace Northstar\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Routing\Events\RouteMatched;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        // ...
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);

        // Update count on StatHat every time a route is hit.
        // e.g. will increment the "northstar - v1/users/{term}/{id}" stat each
        // time a client attempts to view a user profile through that route.
        $events->listen(RouteMatched::class, function (RouteMatched $match) {
            app('stathat')->ezCount(env('STATHAT_APP_NAME', 'northstar').' - '.$match->route->getUri());
        });
    }
}

Increment a stat every time a route is matched.

Is this overkill? I don’t know!


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Middleware;

use Closure;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param string|null              $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (auth()->guard($guard)->guest()) {
            return intend([
                'url' => route('guestarea.auth.login'),
                'with' => ['warning' => trans('cortex/foundation::messages.session_required')],
            ], 401);
        }

        return $next($request);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Middleware;

use Closure;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param string|null              $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (auth()->guard($guard)->guest()) {
            return intend([
                'url' => route('guestarea.auth.login'),
                'with' => ['warning' => trans('cortex/foundation::messages.session_required')],
            ]);
        }

        return $next($request);
    }
}

Fix wrong HTTP redirection status code

Fix wrong HTTP redirection status code


<?php declare(strict_types=1);

namespace League\Container\Inflector;

use Generator;
use League\Container\ContainerAwareTrait;

class InflectorAggregate implements InflectorAggregateInterface
{
    use ContainerAwareTrait;

    /**
     * @var \League\Container\Inflector[]
     */
    protected $inflectors = [];

    /**
     * {@inheritdoc}
     */
    public function add(string $type, callable $callback = null) : Inflector
    {
        $inflector          = new Inflector($type, $callback);
        $this->inflectors[] = $inflector;

        return $inflector;
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator() : Generator
    {
        $count = count($this->inflectors);

        for ($i = 0; $i < $count; $i++) {
            yield $this->inflectors[$i];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function inflect($object)
    {
        foreach ($this->getIterator() as $inflector) {
            $type = $inflector->getType();

            if (! $object instanceof $type) {
                continue;
            }

            $inflector->setContainer($this->getContainer());
            $inflector->inflect($object);
        }

        return $object;
    }
}

<?php declare(strict_types=1);

namespace League\Container\Inflector;

use Generator;
use League\Container\ContainerAwareTrait;

class InflectorAggregate implements InflectorAggregateInterface
{
    use ContainerAwareTrait;

    /**
     * @var \League\Container\Inflector\Inflector[]
     */
    protected $inflectors = [];

    /**
     * {@inheritdoc}
     */
    public function add(string $type, callable $callback = null) : Inflector
    {
        $inflector          = new Inflector($type, $callback);
        $this->inflectors[] = $inflector;

        return $inflector;
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator() : Generator
    {
        $count = count($this->inflectors);

        for ($i = 0; $i < $count; $i++) {
            yield $this->inflectors[$i];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function inflect($object)
    {
        foreach ($this->getIterator() as $inflector) {
            $type = $inflector->getType();

            if (! $object instanceof $type) {
                continue;
            }

            $inflector->setContainer($this->getContainer());
            $inflector->inflect($object);
        }

        return $object;
    }
}

Fix level 1 phpstan issues

Fix level 1 phpstan issues


<?php

namespace Slab\View;

use InvalidArgumentException;

/**
 * View Factory
 *
 * @package default
 * @author Luke Lanchester
 **/
class ViewFactory {

	/**
	 * @var Slab\View\ViewFinder
	 **/
	protected $finder;

	/**
	 * Constructor
	 *
	 * @param Slab\View\ViewFinder
	 * @return void
	 **/
	public function __construct(ViewFinder $finder) {

		$this->finder = $finder;

	}

	/**
	 * Get a new view
	 *
	 * @param string View name
	 * @param array View data
	 * @return Slab\View\ViewInterface
	 **/
	public function make($name, array $data = null) {

		$file = $this->finder->findFile($name);

		return new PhpView($file, $data);

	}

	/**
	 * Register a directory of views
	 *
	 * @param string Directory
	 * @param string Optional vendor prefix
	 * @return void
	 **/
	public function addDirectory($dir, $prefix = null) {

		return $this->finder->addDirectory($dir, $prefix);

	}

}

<?php

namespace Slab\View;

use InvalidArgumentException;

/**
 * View Factory
 *
 * @package default
 * @author Luke Lanchester
 **/
class ViewFactory {

	/**
	 * @var Slab\View\ViewFinder
	 **/
	protected $finder;

	/**
	 * Constructor
	 *
	 * @param Slab\View\ViewFinder
	 * @return void
	 **/
	public function __construct(ViewFinder $finder) {

		$this->finder = $finder;

	}

	/**
	 * Get a new view
	 *
	 * @param string View name
	 * @param array View data
	 * @return Slab\View\ViewInterface
	 **/
	public function make($name, array $data = null) {

		$file = $this->finder->findFile($name);

		if(!$file) {
			throw new InvalidArgumentException("View not found: $name");
		}

		return new PhpView($file, $data);

	}

	/**
	 * Register a directory of views
	 *
	 * @param string Directory
	 * @param string Optional vendor prefix
	 * @return void
	 **/
	public function addDirectory($dir, $prefix = null) {

		return $this->finder->addDirectory($dir, $prefix);

	}

}

Check for no view in factory

Check for no view in factory


<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
  <meta charset="<?php bloginfo('charset'); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width">
  <meta name="theme-color" content="#464646">

  <meta name="author" content="">
  <meta name="description" content="">

  <?php wp_head(); ?>

  <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body <?php body_class(); ?>>

    <header id="masthead" class="site-header" role="banner">
        <nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
            <?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
        </nav>
    </header>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
  <meta charset="<?php bloginfo('charset'); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width">
  <meta name="theme-color" content="#464646">

  <?php wp_head(); ?>

  <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body <?php body_class(); ?>>

    <header id="masthead" class="site-header" role="banner">
        <nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
            <?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
        </nav>
    </header>

Remove author and description meta tags

Remove author and description meta tags


@extends('layouts.master')

@section('content')
    @section('nav-left')

  Pending Accounts

  Users

    @stop
    @section('nav-right')

                {{ Auth::user()->name }}

  Logout

    @stop
    @yield('admin-content')
@stop

@extends('layouts.master')

@section('content')
    @section('nav-left')

  Pending Accounts

  Users

    @stop
    @section('nav-right')

                {{ Auth::user()->name }}

  Change Password

  Logout

    @stop
    @yield('admin-content')
@stop

Revert "Don't add Change Password item yet"

This reverts commit 7dd474eefb54fb31fa09fe50c4634f7bd5f51d71.


<?php
$path = DIR."/php/builder/seeds";
$dh = opendir($path);
$paths = [];
while ($filename = readdir($dh)) {
  if (in_array($filename, [".","..","index.php"])) continue;
  $paths[] = "$path/$filename";
}
asort($paths);
foreach ($paths as $v) include $v;

//seedOrganizations();
//seedClasses();
//seedFamilies();
//seedGenus();
//seedSpecies();
//seedIUCNStatus();
//seedIndoStatus();
//seedLocation();
//seedLandcover();
//seedGrids();

<?php
$path = DIR."/php/builder/seeds";
$dh = opendir($path);
$paths = [];
while ($filename = readdir($dh)) {
  if (in_array($filename, [".","..","index.php"])) continue;
  $paths[] = "$path/$filename";
}
asort($paths);
foreach ($paths as $v) include $v;

ini_set('memory_limit','256M');

//seedOrganizations();
//seedClasses();
//seedFamilies();
//seedGenus();
//seedSpecies();
//seedIUCNStatus();
//seedIndoStatus();
//seedLocation();
//seedLandcover();
//seedGrids();

Build Seeder, tambah ini set memory limit


<?php

class CMTest_ExceptionWrapper extends PHPUnit_Framework_ExceptionWrapper {

    public function __construct($e) {
        parent::__construct($e);

        if ($e instanceof CM_Exception) {
            $message = $e->getMessage();
            $variableInspector = new CM_Debug_VariableInspector();
            $metaInfo = Functional\map($e->getMetaInfo(), function ($value) use ($variableInspector) {
                return $variableInspector->getDebugInfo($value);
            });
            foreach ($metaInfo as $key => $value) {
                $message .= sprintf("\n - %s: %s", $key, $value);
            }
            $this->message = $message;
        }
    }
}

<?php

class CMTest_ExceptionWrapper extends PHPUnit_Framework_ExceptionWrapper {

    public function __construct(CM_Exception $e) {
        parent::__construct($e);
        $formatter = new CM_ExceptionHandling_Formatter_Plain();
        $serializedException = new CM_ExceptionHandling_SerializableException($e);
        $this->message = get_class($e) . ': ' . $e->getMessage() . PHP_EOL . $formatter->getMetaInfo($serializedException);
    }
}

Use CM_ExceptionHandling_Formatter_Plain to format MetaInfo


<?php declare(strict_types=1);

namespace Wnx\LaravelStats\Classifiers;

use Wnx\LaravelStats\ReflectionClass;
use Wnx\LaravelStats\Contracts\Classifier;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;

class ResourceClassifier implements Classifier
{
    public function name(): string
    {
        return 'Resources';
    }

    public function satisfies(ReflectionClass $class): bool
    {
        if (class_exists(\Illuminate\Http\Resources\Json\Resource::class) && $class->isSubclassOf(\Illuminate\Http\Resources\Json\Resource::class)) {
            return true;
        }

        if ($class->isSubclassOf(JsonResource::class)) {
            return true;
        }

        if ($class->isSubclassOf(ResourceCollection::class)) {
            return true;
        }

        return false;
    }

    public function countsTowardsApplicationCode(): bool
    {
        return true;
    }

    public function countsTowardsTests(): bool
    {
        return false;
    }
}

<?php declare(strict_types=1);

namespace Wnx\LaravelStats\Classifiers;

use Wnx\LaravelStats\ReflectionClass;
use Wnx\LaravelStats\Contracts\Classifier;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;

class ResourceClassifier implements Classifier
{
    public function name(): string
    {
        return 'Resources';
    }

    public function satisfies(ReflectionClass $class): bool
    {
        if ($class->isSubclassOf(JsonResource::class)) {
            return true;
        }

        if ($class->isSubclassOf(ResourceCollection::class)) {
            return true;
        }

        return false;
    }

    public function countsTowardsApplicationCode(): bool
    {
        return true;
    }

    public function countsTowardsTests(): bool
    {
        return false;
    }
}

Remove deprecated Resource classification logic

The \\Illuminate\Http\Resources\Json\Resource class has been deprecated in Laravel 6 and has been removed in Laravel 7.


<?php

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

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

<?php

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

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

Fix example test for laravel 5.4 compatibility


<?php namespace Jp\Twilio;

use Illuminate\Support\ServiceProvider;

class TwilioServiceProvider extends ServiceProvider {

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

    /**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app['twilio'] = $this->app->share(function($app)
        {
            $config = \Config::get('services.twilio');
            if (!array($config)) {
                throw new \Exception('Twilio: Invalid configuration.');
            }
            return new Twilio($config);
        });

        // Register Twilio Test SMS Command
        $this->app['twilio.sms'] = $this->app->share(function($app) {
            return new Commands\TwilioSmsCommand();
        });

        // Register Twilio Test Call Command
        $this->app['twilio.call'] = $this->app->share(function($app) {
            return new Commands\TwilioCallCommand();
        });

        $this->commands(
            'twilio.sms',
            'twilio.call'
        );

	}

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

}

<?php namespace Jp\Twilio;

use Illuminate\Support\ServiceProvider;

class TwilioServiceProvider extends ServiceProvider {

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

    /**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{

        // Register manager for usage with the Facade.
        $this->app->singleton('twilio', function () {
            $config = \Config::get('twilio');
            if (!array($config)) {
                throw new \Exception('Twilio: Invalid configuration.');
            }
            return new Twilio($config);
        });

        // $this->app['twilio'] = $this->app->share(function($app)
        // {
        //     $config = \Config::get('services.twilio');
        //     if (!array($config)) {
        //         throw new \Exception('Twilio: Invalid configuration.');
        //     }
        //     return new Twilio($config);
        // });

        // // Register Twilio Test SMS Command
        // $this->app['twilio.sms'] = $this->app->share(function($app) {
        //     return new Commands\TwilioSmsCommand();
        // });

        // // Register Twilio Test Call Command
        // $this->app['twilio.call'] = $this->app->share(function($app) {
        //     return new Commands\TwilioCallCommand();
        // });

        // $this->commands(
        //     'twilio.sms',
        //     'twilio.call'
        // );

	}

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

}

Update Service Provider to 5.4

Update Service Provider to 5.4


<?php

namespace App\Factory\Db\Adapter;

use Interop\Container\ContainerInterface;
use Zend\Db\Adapter\Adapter;

class Adapter
{
    public function __invoke(ContainerInterface $container)
    {
        $config = $container->get('config');
        return new Adapter($config['db']);
    }
}

<?php

namespace App\Factory\Db\Adapter;

use Interop\Container\ContainerInterface;
use Zend\Db\Adapter\Adapter as ZendAdapter;

class Adapter
{
    public function __invoke(ContainerInterface $container)
    {
        $config = $container->get('config');
        return new ZendAdapter($config['db']);
    }
}

Fix de erro no PHP 5

Fix de erro no PHP 5