<?php

/* GNU FM -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Free Software Foundation, Inc

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

/**
 * Encodes an URL component in a mod_rewrite friendly way, handling plus,
 * ampersand, hash and slash signs.
 *
 * @param string The text to encode
 * @return string A mod_rewrite compatible encoding of the given text.
 */
function rewrite_encode($url) {
	$url = urlencode($url);
	$url = preg_replace('/%2B/', '%252B', $url); // +
	$url = preg_replace('/%2F/', '%252F', $url); // /
	$url = preg_replace('/%26/', '%2526', $url); // &
	$url = preg_replace('/%23/', '%2523', $url); // #
	return $url;
}

<?php

/* GNU FM -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Free Software Foundation, Inc

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

/**
 * Encodes an URL component in a mod_rewrite friendly way, handling plus,
 * ampersand, hash and slash signs.
 *
 * @param string The text to encode
 * @return string A mod_rewrite compatible encoding of the given text.
 */
function rewrite_encode($url) {
	if (preg_match('/Apache/', $_SERVER['SERVER_SOFTWARE'])) {
		$url = urlencode($url);
		$url = preg_replace('/%2B/', '%252B', $url); // +
		$url = preg_replace('/%2F/', '%252F', $url); // /
		$url = preg_replace('/%26/', '%2526', $url); // &
		$url = preg_replace('/%23/', '%2523', $url); // #
	} else {
		$url = rawurlencode($url);
	}

	return $url;
}

Fix url rewrites in nginx

Fix url rewrites in nginx


<?php

namespace spec\Scato\Serializer\ObjectAccess;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use stdClass;

class SimpleAccessorSpec extends ObjectBehavior
{
    function it_should_be_an_object_accessor()
    {
        $this->shouldHaveType('Scato\Serializer\Navigation\ObjectAccessorInterface');
    }

    function it_should_find_names()
    {
        $object = new stdClass();
        $object->foo = 'bar';

        $this->getNames($object)->shouldBe(array('foo'));
    }

    function it_should_read_values()
    {
        $object = new stdClass();
        $object->foo = 'bar';

        $this->getValue($object, 'foo')->shouldBe('bar');
    }
}

<?php

namespace spec\Scato\Serializer\ObjectAccess;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use stdClass;

class SimpleAccessorSpec extends ObjectBehavior
{
    function it_should_be_an_object_accessor()
    {
        $this->shouldHaveType('Scato\Serializer\Navigation\ObjectAccessorInterface');
    }

    function it_should_find_names()
    {
        $object = new stdClass();
        $object->foo = 'bar';

        $this->getNames($object)->shouldBe(array('foo'));
    }

    function it_should_read_values()
    {
        $object = new stdClass();
        $object->foo = 'bar';

        $this->getValue($object, 'foo')->shouldBe('bar');
    }

    function it_should_find_properties_with_dashes()
    {
        $array = ['foo-bar' => 'foobar'];
        $object = (object) $array;

        $this->getNames($object)->shouldBe(array('foo-bar'));
    }

    function it_should_read_properties_with_dashes()
    {
        $array = ['foo-bar' => 'foobar'];
        $object = (object) $array;

        $this->getValue($object, 'foo-bar')->shouldBe('foobar');
    }
}

Make sure properties with dashes are handled correctly


<?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
	Everyman\Neo4j\Batch;

/**
 * Commit a batch operation
 * @todo: Handle the case of empty body or body\data needing to be objects not arrays
 */
class Commit extends Command
{
	protected $batch = null;

	/**
	 * Set the batch to drive the command
	 *
	 * @param Client $client
	 * @param Batch $batch
	 */
	public function __construct(Client $client, Batch $batch)
	{
		parent::__construct($client);
		$this->batch = $batch;
	}

	/**
	 * Return the data to pass
	 *
	 * @return mixed
	 */
	protected function getData()
	{
		$operations = $this->batch->getOperations();
		$data = array();
		foreach ($operations as $op) {
			if ($op->reserve()) {
				$command = $op->getCommand();
				$data = array_merge($data, $command->getData());
			}
		}
		return $data;
	}

	/**
	 * Use the results
	 *
	 * @param array $result
	 */
	protected function handleSingleResult($result)
	{
		$operations = $this->batch->getOperations();
		$command = $operations[$result['id']]->getCommand();
		return $command->handleSingleResult($result);
	}
}

<?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
	Everyman\Neo4j\Batch;

/**
 * Commit a batch operation
 * @todo: Handle the case of empty body or body\data needing to be objects not arrays
 */
class Commit extends Command
{
	protected $batch = null;

	/**
	 * Set the batch to drive the command
	 *
	 * @param Client $client
	 * @param Batch $batch
	 */
	public function __construct(Client $client, Batch $batch)
	{
		parent::__construct($client);
		$this->batch = $batch;
	}

	/**
	 * Return the data to pass
	 *
	 * @return mixed
	 */
	protected function getData()
	{
		$operations = $this->batch->getOperations();
		$data = array();
		foreach ($operations as $op) {
			if ($op->reserve()) {
				$opData = $op->getCommand()->getData();
				foreach ($opData as $datum) {
					$data[] = $datum;
				}
			}
		}
		return $data;
	}

	/**
	 * Use the results
	 *
	 * @param array $result
	 */
	protected function handleSingleResult($result)
	{
		$operations = $this->batch->getOperations();
		$command = $operations[$result['id']]->getCommand();
		return $command->handleSingleResult($result);
	}
}

Append new individual batch operation data to the end of the batch data array.

array_merge() is *slow* as the number of operations gets larger.


<?php
	if(isset($_GET['trigger']) && $_GET['trigger'] == 1) {
		error_reporting(E_ALL);
		exec('gpio write 7 0');
		usleep(1000000);
		exec('gpio write 7 1');
	}
?>
<!DOCTYPE html>

		<title>Garage Opener</title>
		<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
		<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
		<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone-retina-display.png" />
		<link rel="stylesheet" href="css/style.css" type="text/css">
		<meta name="apple-mobile-web-app-capable" content="yes">

<?php
	if(isset($_GET['trigger']) && $_GET['trigger'] == 1) {
		error_reporting(E_ALL);
		exec('gpio -g write 18 0');
		usleep(1000000);
		exec('gpio -g write 18 1');
	}
?>
<!DOCTYPE html>

		<title>Garage Opener</title>
		<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
		<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
		<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone-retina-display.png" />
		<link rel="stylesheet" href="css/style.css" type="text/css">
		<meta name="apple-mobile-web-app-capable" content="yes">

Change to write to the IO18 pin

Change to write to the IO18 pin


<?php
namespace PhpBrew\Downloader;

class UrlDownloader
{
    public $logger;

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

    /**
     * @param string $url
     * @return string downloaded file (basename)
     */
    public function download($url)
    {
        $this->logger->info("===> Downloading from $url");

        $info = parse_url($url);
        $basename = basename( $info['path'] );

        // curl is faster than php
        system( 'curl -C - -# -O ' . $url ) !== false or die('Download failed.');

        $this->logger->info("===> $basename downloaded.");

        if( ! file_exists($basename) ) {
            throw Exception("Download failed.");
        }
        return $basename; // return the filename
    }

}

<?php
namespace PhpBrew\Downloader;
use RuntimeException;

class UrlDownloader
{
    public $logger;

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

    /**
     * @param string $url
     * @return string downloaded file (basename)
     */
    public function download($url)
    {
        $this->logger->info("===> Downloading from $url");

        $info = parse_url($url);
        if ( false == $info ) {
            throw new RuntimeException("Can not parse url");
        }

        $basename = basename( $info['path'] );

        // curl is faster than php
        system( 'curl -C - -# -O ' . $url ) !== false or die('Download failed.');

        $this->logger->info("===> $basename downloaded.");

        if( ! file_exists($basename) ) {
            throw Exception("Download failed.");
        }
        return $basename; // return the filename
    }

}

Throw exception if we can't parse url

Throw exception if we can't parse url


<?php

use AmyBoyd\PgnParser\Game;
use AmyBoyd\PgnParser\PgnParser;

class GameTest extends PHPUnit_Framework_TestCase
{
    public function testGetAndSetWhiteAndBlack()
    {
        $game = new Game();
        $this->assertEquals(null, $game->getWhite());

        $game->setWhite('Amy Boyd');
        $this->assertEquals('Amy Boyd', $game->getWhite());
    }

    public function testToJSON()
    {
      $file = 'test/data/2010 World Championship.pgn';
      $parser = new PgnParser($file);
      $game = $parser->getGame(5);
      $json = $game->toJSON();

      $this->assertInternalType('string', $json);
      $this->assertInternalType('array', json_decode($json, true));
      $this->assertJsonStringEqualsJsonFile(__DIR__ . '/expected-toJSON-1.json', $json);
    }
}

<?php

use AmyBoyd\PgnParser\Game;
use AmyBoyd\PgnParser\PgnParser;

class GameTest extends PHPUnit_Framework_TestCase
{
    public function testGetAndSetWhiteAndBlack()
    {
        $game = new Game();
        $this->assertEquals(null, $game->getWhite());

        $game->setWhite('Amy Boyd');
        $this->assertEquals('Amy Boyd', $game->getWhite());
    }

    public function testToJSON()
    {
      $file = 'test/data/2010 World Championship.pgn';
      $parser = new PgnParser($file);
      $game = $parser->getGame(5);
      $json = $game->toJSON();

      $this->assertInternalType('string', $json);
      $this->assertInternalType('array', json_decode($json, true));
      $this->assertJsonStringEqualsJsonFile(__DIR__ . '/expected-toJSON-1.json', $json);
    }

    public function testGetMoves()
    {
      $file = 'test/data/200open.pgn';
      $parser = new PgnParser($file);
      $game = $parser->getGame(0);

      $this->assertEquals(
        'e4 e5 Nf3 d6 d4 f5 dxe5 fxe4 Ng5 d5 e6 Nh6 Nc3 c6 Ngxe4 dxe4 Qh5+ g6 Qe5 Rg8 Bxh6 Bxh6 Rd1 Qg5 Qc7 Bxe6 Qxb7 e3 f3 Qe7 Qxa8 Kf7 Ne4 Bf4 Be2 Kg7 O-O Qc7 Nc5 Bxh2+ Kh1 Bc8 Rd4 Bg3 Re4 Kh8 Rd1 Qg7 Rh4 Bxh4 Qxb8 Ba6 Qh2 Bxe2 Rd7 Qh6 Ne4 Bc4 Nf6 e2 Re7 Qc1+ Qg1 Qxg1+ Kxg1 e1=Q+ Rxe1 Bxe1',
        $game->getMoves()
      );
      $this->assertEquals(
        68,
        $game->getMovesCount()
      );
    }
}

Add failing test for 'Numeric Annotation Glyphs aren't correctly removed'.

Issue: https://github.com/amyboyd/pgn-parser/issues/1


<?php
/**
 * Application configuration shared by all test types
 */
return [
    'language' => 'en-US',
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\faker\FixtureController',
            'fixtureDataPath' => '@tests/codeception/fixtures',
            'templatePath' => '@tests/codeception/templates',
            'namespace' => 'tests\codeception\fixtures',
        ],
    ],
    'components' => [
        'db' => [
            'dsn' => 'mysql:host=localhost;dbname=yii2_basic_tests',
        ],
        'mailer' => [
            'useFileTransport' => true,
        ],
        'urlManager' => [
            'showScriptName' => true,
        ],
    ],
];

<?php
/**
 * Application configuration shared by all test types
 */
return [
    'language' => 'en-US',
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\faker\FixtureController',
            'fixtureDataPath' => '@tests/codeception/fixtures',
            'templatePath' => '@tests/codeception/templates',
            'namespace' => 'tests\codeception\fixtures',
        ],
    ],
    'components' => [
        'db' => [
            'dsn' => 'mysql:host=localhost;dbname=intern_system_tests',
        ],
        'mailer' => [
            'useFileTransport' => true,
        ],
        'urlManager' => [
            'showScriptName' => true,
        ],
    ],
];

Add db name for unit tests

Add db name for unit tests


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     3.3.0
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App;

use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;

/**
 * Application setup class.
 *
 * This defines the bootstrapping logic, and middleware layers you
 * want to use in your application.
 */
class Application extends BaseApplication
{
    /**
     * Setup the middleware your application will use.
     *
     * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to setup.
     * @return \Cake\Http\MiddlewareStack The updated middleware.
     */
    public function middleware($middleware)
    {
        // Catch any exceptions in the lower layers,
        // and make an error page/response
        $middleware->push(new ErrorHandlerMiddleware());

        // Handle plugin/theme assets like CakePHP normally does.
        $middleware->push(new AssetMiddleware());

        // Apply routing
        $middleware->push(new RoutingMiddleware());

        return $middleware;
    }
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     3.3.0
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App;

use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;

/**
 * Application setup class.
 *
 * This defines the bootstrapping logic, and middleware layers you
 * want to use in your application.
 */
class Application extends BaseApplication
{
    /**
     * Setup the middleware your application will use.
     *
     * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to setup.
     * @return \Cake\Http\MiddlewareStack The updated middleware.
     */
    public function middleware($middleware)
    {
        $middleware
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->push(new ErrorHandlerMiddleware();

            // Handle plugin/theme assets like CakePHP normally does.
            ->push(new AssetMiddleware())

            // Apply routing
            ->push(new RoutingMiddleware());

        return $middleware;
    }
}

Use fluent interface for DRYer code.

Use fluent interface for DRYer code.


<?php

namespace Nectary\Tests;

use PHPUnit\Framework\TestCase;

/**
 * @group utility
 */
class Array_Utilities_Test extends TestCase {
	public function test_array_peak() {
		$this->assertEquals( array_peak( [ 'first', 'second' ] ), 'first' );
		$this->assertEquals( array_peak( [] ), null );
		$this->assertEquals( array_peak( null ), null );
	}

	public function test_to_array() {
		$this->assertEquals( array(), to_array( null ) );
		$this->assertEquals( array( 'blah' ), to_array( 'blah' ) );
		$this->assertEquals( array( 'blah' ), to_array( array( 'blah' ) ) );
	}
}

<?php

namespace Nectary\Tests;

use PHPUnit\Framework\TestCase;

/**
 * @group utility
 */
class Array_Utilities_Test extends TestCase {
	public function test_array_peek() {
		$this->assertEquals( array_peek( [ 'first', 'second' ] ), 'first' );
		$this->assertEquals( array_peek( [] ), null );
		$this->assertEquals( array_peek( null ), null );
	}

	public function test_to_array() {
		$this->assertEquals( array(), to_array( null ) );
		$this->assertEquals( array( 'blah' ), to_array( 'blah' ) );
		$this->assertEquals( array( 'blah' ), to_array( array( 'blah' ) ) );
	}
}

Update test references to array_peek()

Update test references to array_peek()


@extends('layouts.app')

@section('content')

Dashboard

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    You are logged in!

            <passport-clients></passport-clients>

            <passport-authorized-clients></passport-authorized-clients>

            <passport-personal-access-tokens></passport-personal-access-tokens>

@endsection

@extends('layouts.app')

@section('content')

Dashboard

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    You are logged in!

            <passport-clients></passport-clients>

            <passport-personal-access-tokens></passport-personal-access-tokens>

@endsection

Remove unneeded component from user interface [WEB-133]


<?php

declare(strict_types=1); // @codeCoverageIgnore

namespace Recoil;

context('api/stop', function () {
    it('stops the kernel', function () {
        $kernel = $this->kernel();

        $kernel->execute(function () {
            yield Recoil::stop();
            expect(false)->to->be->ok('strand was resumed');
        });

        $kernel->run();
    });

    it('does not resume any strands', function () {
        $kernel = $this->kernel();

        $kernel->execute(function () {
            yield 1;
            expect(false)->to->be->ok('strand was resumed');
        });

        $kernel->execute(function () {
            yield Recoil::stop();
        });

        $kernel->run();
    });
});

<?php

declare(strict_types=1); // @codeCoverageIgnore

namespace Recoil;

context('api/stop', function () {
    it('stops the kernel', function () {
        $kernel = $this->kernel();

        $kernel->execute(function () {
            yield Recoil::stop();
            expect(false)->to->be->ok('strand was resumed');
        });

        $kernel->run();
    });

    it('does not resume any strands', function () {
        $kernel = $this->kernel();

        $kernel->execute(function () {
            yield;
            expect(false)->to->be->ok('strand was resumed');
        });

        $kernel->execute(function () {
            yield Recoil::stop();
        });

        $kernel->run();
    });

    it('does not wait for sleeping strands', function () {
        $kernel = $this->kernel();

        $kernel->execute(function () {
            yield 5;
        });

        $kernel->execute(function () {
            yield Recoil::stop();
        });

        $time = microtime(true);
        $kernel->run();
        $diff = microtime(true) - $time;

        expect($diff)->to->be->below(0.05);
    });
});

Add function test to ensure `Recoil::stop()` does not wait for sleeping strands.


<?php

namespace mpyw\Co;

interface CoInterface
{
    const RETURN_WITH = '__RETURN_WITH__';
    const RETURN_ = '__RETURN_WITH__'; // alias
    const RET = '__RETURN_WITH__'; // alias
    const RTN = '__RETURN_WITH__'; // alias
    const UNSAFE = '__UNSAFE__';
    const SAFE = '__SAFE__';
    const DELAY = '__DELAY__';
    const SLEEP = '__DELAY__'; // alias

    public static function setDefaultOptions(array $options);
    public static function getDefaultOptions();
    public static function wait($value, array $options = []);
    public static function async($value);
}

<?php

namespace mpyw\Co;

interface CoInterface
{
    const RETURN_WITH = '__RETURN_WITH__';
    const RETURN_ = '__RETURN_WITH__'; // alias
    const RET = '__RETURN_WITH__'; // alias
    const RTN = '__RETURN_WITH__'; // alias
    const UNSAFE = '__UNSAFE__';
    const SAFE = '__SAFE__';
    const DELAY = '__DELAY__';
    const SLEEP = '__DELAY__'; // alias

    public static function setDefaultOptions(array $options);
    public static function getDefaultOptions();
    public static function wait($value, array $options = []);
    public static function async($value, $throw = null);
}

Fix insufficient interface method argument


@if (app()->environment('local') && $appId = config('services.intercom.app_id'))
    <script>
        window.intercomSettings = {
            @if (Auth::check())
                user_id: {{ Auth::user()->id() }},
                user_hash: "{{ Auth::user()->intercomHash() }}",
                name: "{{ Auth::user()->name() }}",
                email: "{{ Auth::user()->emailAddress() }}",
                created_at: {{ Auth::user()->createdAt()->timestamp }},

                @if ($githubUsername = Auth::user()->githubUsername())
                    github: "{{ $githubUsername }}",
                @endif
            @endif

            app_id: "{{ $appId }}"
        };
    </script>
    <script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k7e25len';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>
@endif

@if (app()->environment('production') && $appId = config('services.intercom.app_id'))
    <script>
        window.intercomSettings = {
            @if (Auth::check())
                user_id: {{ Auth::user()->id() }},
                user_hash: "{{ Auth::user()->intercomHash() }}",
                name: "{{ Auth::user()->name() }}",
                email: "{{ Auth::user()->emailAddress() }}",
                created_at: {{ Auth::user()->createdAt()->timestamp }},

                @if ($githubUsername = Auth::user()->githubUsername())
                    github: "{{ $githubUsername }}",
                @endif
            @endif

            app_id: "{{ $appId }}"
        };
    </script>
    <script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k7e25len';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>
@endif

Use correct environment for Intercom

Use correct environment for Intercom

Whoops ¯\_(ツ)_/¯


<?php
namespace pcre\preg_replace_callback_001;

function f() {
	echo preg_replace_callback('~-([a-z])~', function ($match) {
		return strtoupper($match[1]);
	}, 'hello-world');
}

f();

<?php
namespace pcre\preg_replace_callback_001;

function f() {
	echo preg_replace_callback('~-([a-z])~', function ($match) {
    echo "callback\n";
		return strtoupper($match[1]);
	}, 'hello-world');
}

f();

Make preg_replace_callback test more thorough

Check that the callback isn't called more than once, see #666


<?php
class Inputs
{
    protected static $_instance = Null;

    public static function instance()
    {
        if (!self::$_instance)
            self::$_instance = new self;

        return self::$_instance;
    }

    public function input($key, $default = Null)
    {
        switch (Router::instance()->method) {
            case Router::POST:
                $result = $this->post($key, $default);
                break;
            case Router::PUT:
                $result = $this->put($key, $default);
                break;
            case Router::GET:
                $result = $this->get($key, $default);
                break;
            default:
                $result = $default;
        }

        return $result;
    }

    public function post($key, $default = Null)
    {
        return isset($_POST[$key]) ? filter_var($_POST[$key], FILTER_SANITIZE_STRING) : $default;
    }

    public function get($key, $default = Null)
    {
        return filter_var(Router::instance()->query($key, $default), FILTER_SANITIZE_STRING);
    }

    public function put($key, $default = Null)
    {
        parse_str(file_get_contents("php://input"), $vars);
        return isset($vars[$key]) ? filter_var($vars[$key], FILTER_SANITIZE_STRING) : $default;
    }
}

<?php
class Inputs
{
    protected static $_instance = Null;

    public static function instance()
    {
        if (!self::$_instance)
            self::$_instance = new self;

        return self::$_instance;
    }

    public function input($key, $default = Null)
    {
        switch (Router::instance()->method) {
            case Router::POST:
                $result = $this->post($key, $default);
                break;
            case Router::PUT:
                $result = $this->put($key, $default);
                break;
            case Router::GET:
                $result = $this->get($key, $default);
                break;
            default:
                $result = $default;
        }

        return $result;
    }

    public function post($key, $default = Null)
    {
        if (isset($_POST[$key])) {
            if (is_array($_POST[$key])) {
                $results = Array();

                foreach ($_POST[$key] as $index => $value)
                    $results[$index] = filter_var($value, FILTER_SANITIZE_STRING);

                return $results;
            } else
                return filter_var($_POST[$key], FILTER_SANITIZE_STRING);
        } else
            return $default;
    }

    public function get($key, $default = Null)
    {
        return filter_var(Router::instance()->query($key, $default), FILTER_SANITIZE_STRING);
    }

    public function put($key, $default = Null)
    {
        parse_str(file_get_contents("php://input"), $vars);
        return isset($vars[$key]) ? filter_var($vars[$key], FILTER_SANITIZE_STRING) : $default;
    }
}

Handle arrays in post input

Handle arrays in post input


<?php

class ScreenElements {

	public function get_by_screen($screen) {
		return ScreensDB::select("* FROM status_screens_elements WHERE screen_id = ".$screen->id, "ScreenElement", true);
	}

}

class ScreenElement {

	public function get_element() {
		return Elements::get_by_id($this->element_id);
	}

	public function get_parameters() {
		return ScreenElementParameters::get_by_screenelement($this);
	}

}

?>

<?php

class ScreenElements {

	public function get_by_screen($screen) {
		return ScreensDB::select("* FROM status_screens_elements WHERE screen_id = ".$screen->id." ORDER BY id ASC", "ScreenElement", true);
	}

}

class ScreenElement {

	public function get_element() {
		return Elements::get_by_id($this->element_id);
	}

	public function get_parameters() {
		return ScreenElementParameters::get_by_screenelement($this);
	}

}

?>

Order elements properly so that stacking works


            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Panou administrare

Aproba inscrieri

Dezaproba inscrieri

Logout

Modify logout button to right

Modify logout button to right


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

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

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

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

			<?php if($page->date($format=true)): ?>

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

			<?php endif; ?>

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

			<?php if($page->hasImages()) : ?>

Photo(s) form page

				<?php foreach($page->images() as $image): ?>
					<?php $caption = $image->caption() == '' ? $image->title() : ''; ?>
					<?php echo figure($image, array('cropratio' => 1/2, 'caption' => $caption)); ?>
				<?php endforeach; ?>

			<?php endif; ?>

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

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

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

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

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

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

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

			<?php if($page->date($format=true)): ?>

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

			<?php endif; ?>

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

			<?php /* if($page->hasImages()) : ?>

Photo(s) form page

				<?php foreach($page->images() as $image): ?>
					<?php $caption = $image->caption() == '' ? $image->title() : ''; ?>
					<?php echo figure($image, array('cropratio' => 1/2, 'caption' => $caption)); ?>
				<?php endforeach; ?>

			<?php endif; */ ?>

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

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

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

Hide ‘photo's from (blog) page’.

Hide ‘photo's from (blog) page’.


<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == 'jamendo://') {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == 'track/stream/') {
		$id = substr($url, 23);
		return 'http://api.jamendo.com/get2/stream/track/redirect/?id=' . $id . '&streamencoding=ogg2';
	}

	if (substr($url, 10, 15) == 'album/download/') {
		$id = substr($url, 25);
		return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
	}

	if (substr($url, 10, 10) == 'album/art/') {
		$id = substr($url, 20);
		return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
	}

	// We don't know what this is
	return $url;
}

<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == 'jamendo://') {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == 'track/stream/') {
		$id = substr($url, 23);
		return 'http://gigue.rrbone.net/' . $id . '.ogg2';
	}

	if (substr($url, 10, 15) == 'album/download/') {
		$id = substr($url, 25);
		return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
	}

	if (substr($url, 10, 10) == 'album/art/') {
		$id = substr($url, 20);
		return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
	}

	// We don't know what this is
	return $url;
}

Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime.


<?php
/**
 * SiteCLI - Help you manage Nginx local development configuration
 *
 * @author  panlatent@gmail.com
 * @link    https://github.com/panlatent/site-cli
 * @license https://opensource.org/licenses/MIT
 */

namespace Panlatent\SiteCli\Commands;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ListSiteCommand extends Command
{
    protected function configure()
    {
        $this->setName('list:site')
            ->setAliases(['sites'])
            ->setDescription('Lists all sites in a group');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);
        $sites = $this->manager->getSites();
        sort($sites);
        foreach ($sites as $site) {
            $status = $site->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
            $name = $site->isEnable() ? '<info>%s/%s</info>' : '<comment>%s/%s</comment>';
            $count = $site->count();
            $output->writeln(sprintf(" - %s $name [%d]",
                $status,
                $site->getGroup()->getName(),
                $site->getName(),
                $count
                ));
        }
    }
}

<?php
/**
 * SiteCLI - Help you manage Nginx local development configuration
 *
 * @author  panlatent@gmail.com
 * @link    https://github.com/panlatent/site-cli
 * @license https://opensource.org/licenses/MIT
 */

namespace Panlatent\SiteCli\Commands;

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

class ListSiteCommand extends Command
{
    protected function configure()
    {
        $this->setName('list:site')
            ->setAliases(['sites'])
            ->setDescription('Lists all sites in a group')
            ->addOption(
                'enable',
                'e',
                InputOption::VALUE_NONE,
                'Show only enabled sites'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);
        $sites = $this->manager->getSites();

        if ($input->getOption('enable')) {
            $sites = array_filter($sites, function($site) {
                /** @var \Panlatent\SiteCli\Site $site */
                return $site->isEnable();
            });
        }

        sort($sites);
        foreach ($sites as $site) {
            $status = $site->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
            $name = $site->isEnable() ? '<info>%s/%s</info>' : '<comment>%s/%s</comment>';
            $count = $site->count();
            $output->writeln(sprintf(" - %s $name [%d]",
                $status,
                $site->getGroup()->getName(),
                $site->getName(),
                $count
                ));
        }
    }
}

Add list:site command enable option

Add list:site command enable option


<?php

namespace BetterReflectionTest\Util\Autoload;

use BetterReflection\Reflection\ReflectionClass;
use BetterReflection\Util\Autoload\ClassLoader;
use BetterReflectionTest\Fixture\TestClassForAutoloader;

/**
 * @covers \BetterReflection\Util\Autoload\ClassLoader
 */
class ClassLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testAddClassThrowsExceptionWhenAutoloadNotInitialised()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAddClassThrowsExceptionWhenClassAlreadyRegisteredInAutoload()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAddClassThrowsExceptionWhenClassAlreadyLoaded()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testInitailiseCannotBeCalledTwice()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAutoloadStackObeyedWhenClassNotRegisteredInAutoload()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAutoloadThrowsExceptionWhenClassIsNotLoadedCorrectlyAfterAttemptingToLoad()
    {
        $this->markTestIncomplete(__METHOD__);
    }
}

<?php

namespace BetterReflectionTest\Util\Autoload;

use BetterReflection\Reflection\ReflectionClass;
use BetterReflection\Util\Autoload\ClassLoader;
use BetterReflection\Util\Autoload\ClassLoaderMethod\EvalLoader;
use BetterReflection\Util\Autoload\ClassLoaderMethod\LoaderMethodInterface;
use BetterReflectionTest\Fixture\TestClassForAutoloader;

/**
 * @covers \BetterReflection\Util\Autoload\ClassLoader
 */
class ClassLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testAutoloadSelfRegisters()
    {
        $initialAutoloaderCount = count(spl_autoload_functions());

        $loader = new ClassLoader($this->createMock(LoaderMethodInterface::class));

        self::assertCount($initialAutoloaderCount + 1, spl_autoload_functions());

        spl_autoload_unregister($loader);

        self::assertCount($initialAutoloaderCount, spl_autoload_functions());
    }

    public function testAutoloadTriggersLoaderMethod()
    {
        $reflection = ReflectionClass::createFromName(TestClassForAutoloader::class);
        self::assertFalse(class_exists(TestClassForAutoloader::class, false));

        $loader = new ClassLoader(new EvalLoader());
        $loader->addClass($reflection);

        new TestClassForAutoloader();
    }

    public function testAddClassThrowsExceptionWhenAutoloadNotInitialised()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAddClassThrowsExceptionWhenClassAlreadyRegisteredInAutoload()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAddClassThrowsExceptionWhenClassAlreadyLoaded()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testInitailiseCannotBeCalledTwice()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAutoloadStackObeyedWhenClassNotRegisteredInAutoload()
    {
        $this->markTestIncomplete(__METHOD__);
    }

    public function testAutoloadThrowsExceptionWhenClassIsNotLoadedCorrectlyAfterAttemptingToLoad()
    {
        $this->markTestIncomplete(__METHOD__);
    }
}

Add basic tests for core functionality of ClassLoader


<?php

define('SERVER_PROTOCOL', 'HTTP/1.1');
$_SERVER['DOCUMENT_ROOT'] = str_replace( 'deploy/tests', '', __DIR__ );
$_SERVER['SERVER_NAME'] = gethostname();

<?php

$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
$_SERVER['DOCUMENT_ROOT'] = str_replace( 'deploy/tests', '', __DIR__ );
$_SERVER['SERVER_NAME'] = gethostname();

Define the server protcol properly

Define the server protcol properly


<?php
declare(strict_types=1);

namespace HomoChecker\View;

class ServerSentEventView implements ViewInterface
{
    public $event;

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

        // @codeCoverageIgnoreStart
        if (!headers_sent()) {
            header('Content-Type: text/event-stream');
        }
        // @codeCoverageIgnoreEnd

        // 2 KiB padding
        echo ":" . str_repeat(" ", 2048) . "\n";

        $this->flush();
    }

    /**
     * @codeCoverageIgnore
     */
    public function render($data, $event = null): void
    {
        $event = $event ?? $this->event;
        echo "event: {$event}\n";
        echo "data: " . json_encode($data) . "\n\n";
        $this->flush();
    }

    public function flush(): void
    {
        @ob_flush();
        flush();
    }

    public function close(): void
    {
        echo "event: close\n";
        echo "data: end\n\n";
    }
}

<?php
declare(strict_types=1);

namespace HomoChecker\View;

class ServerSentEventView implements ViewInterface
{
    public $event;

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

        // @codeCoverageIgnoreStart
        if (!headers_sent()) {
            header('Content-Type: text/event-stream');
        }
        // @codeCoverageIgnoreEnd

        // 2 KiB padding
        echo ":" . str_repeat(" ", 2048) . "\n";

        $this->flush();
    }

    /**
     * @codeCoverageIgnore
     */
    public function render($data, $event = null): void
    {
        $event = $event ?? $this->event;
        echo "event: {$event}\n";
        echo "data: " . json_encode($data) . "\n\n";
        $this->flush();
    }

    public function flush(): void
    {
        @ob_flush();
        flush();
    }

    public function close(): void
    {
        echo "event: close\n";
        echo "data: end\n\n";
        $this->flush();
    }
}

Fix a bug where close event was not sent


@extends('layouts.app')

@section('content')

@lang('twofactor-auth::twofactor-auth.title')

                    <form class="form-horizontal" role="form" method="POST" action="{{ route('auth.token') }}">
                        {{ csrf_field() }}

has('token') ? ' has-error' : '' }}">
                            @lang('twofactor-auth::twofactor-auth.label')

                                <input id="token" type="text" class="form-control" name="token" value="{{ old('token') }}" required autofocus>

                                @if ($errors->has('token'))

                                        {{ $errors->first('token') }}

                                @endif

                                <button type="submit" class="btn btn-primary">
                                    @lang('twofactor-auth::twofactor-auth.send')
                                </button>

                    </form>

@endsection

@extends('layouts.app')

@section('content')

@lang('twofactor-auth::twofactor-auth.title')

                    <form class="form-horizontal" role="form" method="POST" action="{{ route('auth.token') }}">
                        @csrf

                            @lang('twofactor-auth::twofactor-auth.label')

                                <input id="token" type="text" class="form-control{{ $errors->has('token') ? ' is-invalid' : '' }}" name="token" value="{{ old('token') }}" required autofocus>

                                @if ($errors->has('token'))

                                        {{ $errors->first('token') }}

                                @endif

                                <button type="submit" class="btn btn-primary">
                                    @lang('twofactor-auth::twofactor-auth.send')
                                </button>

                    </form>

@endsection

Update auth token form layout

Update auth token form layout


<?php
/**
 * Api_Admin should be used for building your own application's administration
 * model. The benefit is that you'll have access to a number of add-ons which
 * are specifically written for admin system.
 *
 * Exporting add-ons, database migration, test-suites and other add-ons
 * have developed User Interface which can be simply "attached" to your
 * application's admin.
 *
 * This is done through hooks in the Admin Class. It's also important that
 * Api_Admin relies on layout_fluid which makes it easier for add-ons to
 * add menu items, sidebars and foot-bars.
 */
class Api_Admin extends ApiFrontend {

    public $menu;

    function init() {
        parent::init();

        $this->add('Layout_Fluid');

        $this->menu = $this->layout->addMenu();
        $this->layout->addFooter();

        $this->initAddons();
    }

    function initAddons() {
        // TODO: Initialize add-ons automatically which have standard
        // controllers out there
        foreach($this->api->getConfig('addons/active',array()) as $addon) {
            $this->add($addon.'/Controller');
        }
    }
}

<?php
/**
 * Api_Admin should be used for building your own application's administration
 * model. The benefit is that you'll have access to a number of add-ons which
 * are specifically written for admin system.
 *
 * Exporting add-ons, database migration, test-suites and other add-ons
 * have developed User Interface which can be simply "attached" to your
 * application's admin.
 *
 * This is done through hooks in the Admin Class. It's also important that
 * Api_Admin relies on layout_fluid which makes it easier for add-ons to
 * add menu items, sidebars and foot-bars.
 */
class Api_Admin extends ApiFrontend {

    public $menu;

    function init() {
        parent::init();

        $this->add('Layout_Fluid');

        $this->menu = $this->layout->addMenu();
        $this->layout->addFooter();

        $this->add('jUI');

        $this->police = $this->add('Controller_Police');
        $this->layout->add('sandbox/View_Toolbar',null,'Toolbar');

        $this->initAddons();
    }

    function initAddons() {
        // TODO: Initialize add-ons automatically which have standard
        // controllers out there
        foreach($this->api->getConfig('addons/active',array()) as $addon) {
            $this->add($addon.'/Controller');
        }
    }
}

Add police and toolbar at the top API level.


<?php
/* Site-wide utility functions */

require_once('secureConstants.php');

function mysqliConn() {
	$db = new mysqli(
		$GLOBALS['DB']['SERVER'],
		$GLOBALS['DB']['USERNAME'],
		$GOLBALS['DB']['PASSWORD'],
		$GLOBALS['DB']['DATABASE']
	);

	if ($db->connect_errno) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
	}

	return $db;
}

function pdoConn() {
	$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";

	try {
		$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'],	$GOLBALS['DB']['PASSWORD']);
	} catch (PDOException $e) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
	}

	return $db;
}

<?php
/* Site-wide utility functions */

require_once('secureConstants.php');

function mysqliConn() {
	$db = new mysqli(
		$GLOBALS['DB']['SERVER'],
		$GLOBALS['DB']['USERNAME'],
		$GOLBALS['DB']['PASSWORD'],
		$GLOBALS['DB']['DATABASE']
	);

	if ($db->connect_errno) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
	}

	return $db;
}

function pdoConn() {
	$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";

	try {
		$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'],	$GOLBALS['DB']['PASSWORD'], [PDO::ATTR_PERSISTENT => true]);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	} catch (PDOException $e) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
	}

	return $db;
}

Make PDO connections persistent and exceptional


<?php

namespace Begin;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'tasks';
}

<?php

namespace Begin;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'tasks';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title', 'description'];
}

Add the field that are mass assignable on the tasks table


<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Repository as Contract;
use Coreplex\Meta\Exceptions\MetaGroupNotFoundException;

class Repository implements Contract
{
    /**
     * Find a meta group by it's identifier
     *
     * @param  mixed $identifier
     * @return \Coreplex\Meta\Contracts\Group
     * @throws MetaGroupNotFoundException
     */
    public function find($identifier)
    {
        if ($meta = Meta::where('identifier', $identifier)->first()) {
            return $meta;
        }

        throw new MetaGroupNotFoundException('A meta group with the identifier "' . $identifier . '" could not be found.');
    }

    /**
     * Get the default meta group if one exists
     *
     * @return \Coreplex\Meta\Contracts\Group|null
     */
    public function defaultGroup()
    {
        return Meta::defaultGroup();
    }
}

<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Repository as Contract;
use Coreplex\Meta\Contracts\Variant;
use Coreplex\Meta\Exceptions\MetaGroupNotFoundException;

class Repository implements Contract
{
    /**
     * Find a meta group by it's identifier
     *
     * @param  mixed  $identifier
     * @param Variant $variant
     * @return \Coreplex\Meta\Contracts\Group|null
     * @throws MetaGroupNotFoundException
     */
    public function find($identifier, Variant $variant = null)
    {
        if ($variant) {
            if ($meta = Meta::where('identifier', $identifier)
                            ->where('variant_id', $variant->getKey())
                            ->where('variant_type', $variant->getType())
                            ->first()
            ) {
                return $meta;
            }
        } else {
            if ($meta = Meta::where('identifier', $identifier)->first()) {
                return $meta;
            }
        }

        throw new MetaGroupNotFoundException('A meta group with the identifier "' . $identifier . '" could not be found.');
    }

    /**
     * Get the default meta group if one exists
     *
     * @return \Coreplex\Meta\Contracts\Group|null
     */
    public function defaultGroup()
    {
        return Meta::defaultGroup();
    }
}

Update the find method in the repository to work with variants


<?php

namespace League\Route;

trait RouteConditionTrait
{
    /**
     * @var string
     */
    protected $host;

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

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

    /**
     * Get the host.
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Set the host.
     *
     * @param string $host
     *
     * @return \League\Route\Route
     */
    public function setHost($host)
    {
        $this->host = $host;

        return $this;
    }

    /**
     * Get the name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the name.
     *
     * @param string name
     *
     * @return \League\Route\Route
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get the scheme.
     *
     * @return string
     */
    public function getScheme()
    {
        return $this->scheme;
    }

    /**
     * Set the scheme.
     *
     * @param string $scheme
     *
     * @return \League\Route\Route
     */
    public function setScheme($scheme)
    {
        $this->scheme = $scheme;

        return $this;
    }
}

<?php

namespace League\Route;

trait RouteConditionTrait
{
    /**
     * @var string
     */
    protected $host;

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

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

    /**
     * Get the host.
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Set the host.
     *
     * @param string $host
     *
     * @return \League\Route\Route
     */
    public function setHost($host)
    {
        $this->host = $host;

        return $this;
    }

    /**
     * Get the name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the name.
     *
     * @param string $name
     *
     * @return \League\Route\Route
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get the scheme.
     *
     * @return string
     */
    public function getScheme()
    {
        return $this->scheme;
    }

    /**
     * Set the scheme.
     *
     * @param string $scheme
     *
     * @return \League\Route\Route
     */
    public function setScheme($scheme)
    {
        $this->scheme = $scheme;

        return $this;
    }
}

Fix: Add missing $ before parameter name in docblock


<?php

namespace allejo\stakx\Twig;

use Symfony\Component\Finder\Finder;

class FinderFunction
{
    public static function get ()
    {
        return new \Twig_SimpleFunction('finder', new Finder());
    }
}

<?php

namespace allejo\stakx\Twig;

use allejo\stakx\System\Filesystem;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\Finder\Finder;
use Twig_Environment;

class FinderFunction
{
    public function __invoke(Twig_Environment $env, $folderLocation)
    {
        $fs    = new Filesystem();
        $globs = $env->getGlobals();
        $dir   = $fs->getFolderPath($globs['__currentTemplate']);
        $path  = $fs->appendPath($dir, $folderLocation);

        if (strpos($path, getcwd()) !== 0)
        {
            throw new FileNotFoundException(sprintf(
                "The '%s' file could not be found or is outside the website working directory",
                $folderLocation
            ));
        }

        $finder = new Finder();
        $finder->in($folderLocation);

        return $finder;
    }

    public static function get ()
    {
        return new \Twig_SimpleFunction('finder', new self(), array(
            'needs_environment' => true
        ));
    }
}

Fix the broken Twig 'finder' function

Fix the broken Twig 'finder' function


<?php

namespace Test\Staq;

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

class Application_Test extends \PHPUnit_Framework_TestCase {

	/*************************************************************************
	 ATTRIBUTES
	 *************************************************************************/
	public $starter_namespaces = [ 'Staq\App\Starter', 'Staq\Core\Router', 'Staq\Core\Ground' ];

	/*************************************************************************
	  TEST METHODS
	 *************************************************************************/
	public function test_empty_project__extensions( ) {
		$app = \Staq\Application::create( );
		$this->assertEquals( $this->starter_namespaces, $app->get_extensions( 'namespace' ) );
	}

	public function test_empty_project__platform( ) {
		$app = \Staq\Application::create( );
		$this->assertEquals( 'prod', $app->get_platform( ) );
	}

	public function test_named_project__extensions( ) {
		$project_namespace = 'Staq';
		$app = \Staq\Application::create( $project_namespace );
		$expected = $this->starter_namespaces;
		array_unshift( $expected, $project_namespace );
		$this->assertEquals( $expected, $app->get_extensions( 'namespace' ) );
	}
}

<?php

namespace Test\Staq;

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

class Application_Test extends \PHPUnit_Framework_TestCase {

	/*************************************************************************
	 ATTRIBUTES
	 *************************************************************************/
	public $starter_namespaces = [ 'Staq\App\Starter', 'Staq\Core\Router', 'Staq\Core\Ground' ];

	/*************************************************************************
	  TEST METHODS
	 *************************************************************************/
	public function test_empty_project__extensions( ) {
		$app = \Staq\Application::create( );
		$this->assertEquals( $this->starter_namespaces, $app->get_extensions( 'namespace' ) );
	}

	public function test_empty_project__platform( ) {
		$app = \Staq\Application::create( );
		$this->assertEquals( 'prod', $app->get_platform( ) );
	}

	public function test_named_project__extensions( ) {
		$project_namespace = 'Staq';
		$app = \Staq\Application::create( $project_namespace );
		$expected = $this->starter_namespaces;
		array_unshift( $expected, $project_namespace );
		$this->assertEquals( $expected, $app->get_extensions( 'namespace' ) );
	}
}

Use PSR-0 structure for the test too

Use PSR-0 structure for the test too


<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */
    "password" => "A senha deverá conter pelo menos seis carateres e ser igual à confirmação.",

    "user"     => "Não conseguimos encontrar nenhum usuário com o endereço de email indicado.",

    "token"    => "Este código de recuperação da senha é inválido.",

    "sent"     => "O lembrete da senha foi enviado!",

    "reset"    => "Password has been reset!",

);

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */
    "password" => "A senha deverá conter pelo menos seis carateres e ser igual à confirmação.",

    "user"     => "Não conseguimos encontrar nenhum usuário com o endereço de email indicado.",

    "token"    => "Este código de recuperação da senha é inválido.",

    "sent"     => "O lembrete da senha foi enviado!",

    "reset"    => "A senha foi redefinida!",

);

Reset in Reminders in Portuguese

Reset in Reminders in Portuguese


{!! Form::open(['action' => 'UsersController@search', 'method' => 'GET']) !!}

{!! Form::text('query', request()->get('query'), ['class' => 'text-field -search', 'placeholder' => 'Search by email, mobile, Drupal ID…', 'style' => 'min-width: 400px']) !!}

{!! Form::submit('Search', ['class' => 'button']) !!}

{!! Form::close () !!}

{!! Form::open(['action' => 'UsersController@search', 'method' => 'GET']) !!}

{!! Form::text('query', request()->get('query'), ['class' => 'text-field -search', 'placeholder' => 'Find user by email, mobile, ID…', 'style' => 'min-width: 400px']) !!}

{!! Form::submit('Search', ['class' => 'button']) !!}

{!! Form::close () !!}

Remove reference to Drupal ID.

Remove reference to Drupal ID.


<?php
/**
 * Created by PhpStorm.
 * User: GeoMash
 * Date: 3/17/14
 * Time: 4:13 PM
 */

<?php
namespace application\nutsNBolts\controller\rest\contentTypeRole
{
	use application\nutsNBolts\base\RestController;

	class Index extends RestController
	{
		public function init()
		{
			$this->bindPaths
			(
				array
				(
					'{int}'				=>'getByContentId',
				)
			);
		}
		/*
		 * sample request: $.getJSON('/rest/contentType/1.json');
		 */
		public function getByContentId()
		{
			$contentTypeId=$this->getFullRequestPart(2);
			if(isset($contentTypeId) && is_numeric($contentTypeId))
			{
				$content=$this->model->ContentTypeRole->read(['content_type_id'=>$contentTypeId]);
				if(count($content))
				{
					$this->setResponseCode(200);
					$this->respond
					(
						true,
						'OK',
						$content[0]
					);
				}
				else
				{
					// no content by that id
					$this->setResponseCode(404);
					$this->respond
					(
						true,
						'Not Found',
						'Content type role not found'
					);
				}
			}
			else
			{
				$this->setResponseCode(404);
				$this->respond
				(
					false,
					'Expecting content type id to be an integer.'
				);
			}
		}
	}
}
?>

Add contentTypeRole to rest controller

Add contentTypeRole to rest controller


<?php

include_once('includes/autoload.php');

class taskManagerTest extends PHPUnit_Framework_TestCase {

	// set up global app var
	public function setUp() {
		// init global app var
		global $app;
		$app['param'] = getConfig("test");
		$app['users'] = loadJson($app['param']['db_path_users']);
		$app['pages'] = loadJson($app['param']['db_path_pages']);
		$app['tasks'] = loadJson($app['param']['db_path_tasks']);
		$app['trans'] = "testLang";
	}

	public function testCreateTask() {
		// TODO
	}
}

<?php

include_once('includes/autoload.php');

class taskManagerTest extends PHPUnit_Framework_TestCase {

	// set up global app var
	public function setUp() {
		// init global app var
		global $app;
		$app['param'] = getConfig("test");
		$app['users'] = loadJson($app['param']['db_path_users']);
		$app['pages'] = loadJson($app['param']['db_path_pages']);
		$app['tasks'] = loadJson($app['param']['db_path_tasks']);
		$app['trans'] = "testLang";
	}

	public function testCheckFields() {
		// TODO
	}

	public function testCreateTask() {
		// TODO
	}

	public function testUpdateTask() {
		// TODO
	}

	public function testDeleteTask() {
		// TODO
	}
}

Add methods to taskManager test

Add methods to taskManager test


<?php
/**
 * Initialize the application
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 */

require_once '../config/global.php';

\Skeleton\Core\Web\Handler::Run();

<?php
/**
 * Initialize the application
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 * @author David Vandemaele <david@tigron.be>
 */

require_once dirname(__FILE__) . '/../config/global.php';

\Skeleton\Core\Web\Handler::Run();

Make it work when situated in a subfolder


<?php

namespace Boris\Loader\Provider;

class EzPublish extends AbstractProvider
{
    public $name = 'ezpublish';

    public function assertDir($dir)
    {
        return is_file("$dir/ezpublish/bootstrap.php.cache")
            && is_file("$dir/ezpublish/EzPublishKernel.php");
    }

    public function initialize(\Boris\Boris $boris, $dir)
    {
        parent::initialize($boris, $dir);

        putenv("EZPUBLISH_SITEACCESS=fr");

        require "$dir/ezpublish/bootstrap.php.cache";
        require_once "$dir/ezpublish/EzPublishKernel.php";

        $kernel = new \EzPublishKernel('dev', true);
        $kernel->loadClassCache();
        $kernel->boot();

        $boris->onStart(function ($worker, $vars) use ($kernel) {
            $worker->setLocal('kernel', $kernel);
            $worker->setLocal('container', $kernel->getContainer());
        });
    }

}

<?php

namespace Boris\Loader\Provider;

class EzPublish extends AbstractProvider
{
    public $name = 'ezpublish';

    public function assertDir($dir)
    {
        return is_file("$dir/ezpublish/bootstrap.php.cache")
            && is_file("$dir/ezpublish/EzPublishKernel.php");
    }

    public function initialize(\Boris\Boris $boris, $dir)
    {
        parent::initialize($boris, $dir);

        require "$dir/ezpublish/bootstrap.php.cache";
        require_once "$dir/ezpublish/EzPublishKernel.php";

        $kernel = new \EzPublishKernel('dev', true);
        $kernel->loadClassCache();
        $kernel->boot();

        $boris->onStart(function ($worker, $vars) use ($kernel) {
            $worker->setLocal('kernel', $kernel);
            $worker->setLocal('container', $kernel->getContainer());
        });
    }

}

Remove unneeded env var to set siteaccess


<?php
namespace SepomexPhp;

class Locations implements \IteratorAggregate, \Countable
{
    /** @var Location[] */
    private $collection;

    public function __construct(Location ...$location)
    {
        $this->collection = $location;

    public static function extractUniqueCities(Location ...$locations): Cities
    {
        // This method is static because it does not use $this
        $cities = [];
        foreach ($locations as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->collection);
    }

    public function count(): int
    {
        return count($this->collection);
    }

    /**
     * @return Cities|City[]
     */
    public function cities(): Cities
    {
        $cities = [];
        foreach ($this->collection as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function asArray(): array
    {
        $array = [];
        foreach ($this->collection as $location) {
            $array[] = $location->asArray();
        }
        return $array;
    }
}

<?php
namespace SepomexPhp;

class Locations implements \IteratorAggregate, \Countable
{
    /** @var Location[] */
    private $collection;

    /** @var Cities */
    private $cities;

    public function __construct(Location ...$location)
    {
        $this->collection = $location;
        $this->cities = $this->extractUniqueCities(...$location);
    }

    public static function extractUniqueCities(Location ...$locations): Cities
    {
        // This method is static because it does not use $this
        $cities = [];
        foreach ($locations as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->collection);
    }

    public function count(): int
    {
        return count($this->collection);
    }

    /**
     * @return Cities|City[]
     */
    public function cities(): Cities
    {
        return $this->cities;
    }

    public function asArray(): array
    {
        $array = [];
        foreach ($this->collection as $location) {
            $array[] = $location->asArray();
        }
        return $array;
    }
}

Make cities a property, set inside constructor


<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/App/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/App/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->bind('objects', ObjectsService::class);
    }
}

<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/app/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/app/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->bind('objects', ObjectsService::class);
    }
}

Change namespace in example classes

Change namespace in example classes


<?php

namespace User\Form;

use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AddGroupType extends AbstractType
{
    private $user;

    function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $user = $this->user;
        $builder
            ->add('group', 'entity', array(
                'property'=>'displayName',
                'class' => 'App\Entity\Group',
                'query_builder'=>function (EntityRepository $repo) {
                    return $repo->createQueryBuilder('g')
                                ->where('g.noUsers = false AND g.userJoinable = true');

                },
                'required'=>true,
                'multiple'=>false,
            ))
            ->add('submit', 'submit', array(
                'label' => 'Join group',
                'attr' => array(
                    'class' => 'btn-sm',
                )
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'usr_group_add';
    }
}

<?php

namespace User\Form;

use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AddGroupType extends AbstractType
{
    private $user;

    function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $user = $this->user;
        $builder
            ->add('group', 'entity', array(
                'property'=>'displayName',
                'class' => 'App\Entity\Group',
                'query_builder'=>function (EntityRepository $repo) use($user) {
                    $qb = $repo->createQueryBuilder('g')
                                ->where('g.noUsers = false AND g.userJoinable = true');
                    if($user->getGroups()->count() == 0)
                        return $qb;
                    return $qb->andWhere('g NOT IN(:groups)')
                                ->setParameter('groups', $user->getGroups());
                },
                'required'=>true,
                'multiple'=>false,
            ))
            ->add('submit', 'submit', array(
                'label' => 'Join group',
                'attr' => array(
                    'class' => 'btn-sm',
                )
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'usr_group_add';
    }
}

Hide groups the user is already member of in user add group form.


<?php

namespace Predis\Options;

class CustomOption extends Option {
    private $__validate, $_default;

    public function __construct(Array $options) {
        $validate = isset($options['validate']) ? $options['validate'] : 'parent::validate';
        $default  = isset($options['default']) ? $options['default'] : 'parent::getDefault';
        if (!is_callable($validate) || !is_callable($default)) {
            throw new \InvalidArgumentException("Validate and default must be callable");
        }
        $this->_validate = $validate;
        $this->_default  = $default;
    }

    public function validate($value) {
        return call_user_func($this->_validate, $value);
    }

    public function getDefault() {
        return $this->validate(call_user_func($this->_default));
    }
}

<?php

namespace Predis\Options;

class CustomOption extends Option {
    private $_validate, $_default;

    public function __construct(Array $options) {
        $validate = isset($options['validate']) ? $options['validate'] : 'parent::validate';
        $default  = isset($options['default']) ? $options['default'] : 'parent::getDefault';
        if (!is_callable($validate) || !is_callable($default)) {
            throw new \InvalidArgumentException("Validate and default must be callable");
        }
        $this->_validate = $validate;
        $this->_default  = $default;
    }

    public function validate($value) {
        return call_user_func($this->_validate, $value);
    }

    public function getDefault() {
        return $this->validate(call_user_func($this->_default));
    }
}

Fix wrong name for private field.

Fix wrong name for private field.


<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Validator;

class Category extends Model {

	protected $fillable = ['name'];

	private static $messages = [
		// name messages
		'name.required' => 'El nombre es requerido',
		'name.alpha' => 'El nombre no puede contener números ni símbolos',
		'name.max' => 'El nombre debe tener menos de :max caracteres',
		'name.min' => 'El nombre debe tener al menos :min caracteres',
	];

	private static $rulesForCreation = [
			'name' => 'required|alpha|min:4|max:50|unique:categories,name'
	];

	public static function validate($all) {
		$rules = self::$rulesForCreation;
		$messages = self::$messages;

		return Validator::make($all, $rules, $messages);
	}

	public static function validateUpdate($all) {
		$rulestemp = self::$rulesForCreation;
		$messages = self::$messages;

		$rulestemp['name'] = 'required|alpha|min:4|max:50|unique:categories,name,'.$all['id'];

		return Validator::make($all, $rulestemp, $messages);
	}

	//
	public function articles() {
		return $this->hasMany('App\Article');
	}
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Validator;

class Category extends Model {

	protected $fillable = ['name'];

	private static $messages = [
		// name messages
		'name.required' => 'El nombre es requerido',
		'name.unique' => 'Ya existe una categoría con ese nombre',
		'name.alpha' => 'El nombre no puede contener números ni símbolos',
		'name.max' => 'El nombre debe tener menos de :max caracteres',
		'name.min' => 'El nombre debe tener al menos :min caracteres',
	];

	private static $rulesForCreation = [
			'name' => 'required|alpha|min:4|max:50|unique:categories,name'
	];

	public static function validate($all) {
		$rules = self::$rulesForCreation;
		$messages = self::$messages;

		return Validator::make($all, $rules, $messages);
	}

	public static function validateUpdate($all) {
		$rulestemp = self::$rulesForCreation;
		$messages = self::$messages;

		$rulestemp['name'] = $rulestemp['name'].','.$all['id'];

		return Validator::make($all, $rulestemp, $messages);
	}

	//
	public function articles() {
		return $this->hasMany('App\Article');
	}
}

Fix validation messages in category

Fix validation messages in category


<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

namespace PHPMD\Stubs;

use PHPMD\AbstractWriter;

/**
 * Simple test implementation of PHPMD's writer.
 */
class WriterStub extends AbstractWriter
{
    /**
     * The written data chunks.
     *
     * @var array
     */
    public $chunks = array();

    /**
     * Writes a data string to the concrete output.
     *
     * @param string $data The data to write.
     *
     * @return void
     */
    public function write($data)
    {
        $this->chunks[] = $data;
    }

    /**
     * Returns a concated string of all data chunks.
     *
     * @return string
     */
    public function getData()
    {
        return join('', $this->chunks);
    }

    /**
     * Returns the written data chunks.
     *
     * @return array
     */
    public function getChunks()
    {
        return $this->chunks;
    }
}

<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

namespace PHPMD\Stubs;

use PHPMD\AbstractWriter;

/**
 * Simple test implementation of PHPMD's writer.
 */
class WriterStub extends AbstractWriter
{
    /**
     * The written data chunks.
     *
     * @var array
     */
    public $chunks = array();

    /**
     * Writes a data string to the concrete output.
     *
     * @param string $data The data to write.
     *
     * @return void
     */
    public function write($data)
    {
        $this->chunks[] = $data;
    }

    /**
     * Returns a concated string of all data chunks.
     *
     * @return string
     */
    public function getData()
    {
        return implode('', $this->chunks);
    }

    /**
     * Returns the written data chunks.
     *
     * @return array
     */
    public function getChunks()
    {
        return $this->chunks;
    }
}

Replace outdated join function with implode


<form method="POST" action="{{ action('\GeniusTS\Preferences\Controllers\SettingsController@update') }}">
    <input type="hidden" name="_method" value="PATCH" />

    @if(version_compare($version, '5.3.0') < 0)
        @include('geniusts_preferences::settings_5_2')
    @else
        @include('geniusts_preferences::settings_5_3')
    @endif

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

</form>

<form method="POST" action="{{ action('SettingsController@update') }}">
    <input type="hidden" name="_method" value="PATCH" />

    @if(version_compare($version, '5.3.0') < 0)
        @include('geniusts_preferences::settings_5_2')
    @else
        @include('geniusts_preferences::settings_5_3')
    @endif

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

</form>

Change the route of the form tp App\Http\SettingsController


<?php
use filter\Filter;
use VCR\VCR;

$this->args()->argument('reporter', 'default', 'verbose');

VCR::configure()->setCassettePath(__DIR__.'/spec/fixtures');
VCR::turnOn();

Filter::register('exclude.namespaces', function ($chain) {
});

Filter::apply($this, 'interceptor', 'exclude.namespaces');

<?php
use filter\Filter;
use VCR\VCR;

$this->args()->argument('reporter', 'default', 'verbose');

VCR::configure()
    ->setCassettePath(__DIR__.'/spec/fixtures')
    ->enableRequestMatchers(array('method', 'url', 'query_string', 'host'));

VCR::turnOn();

Filter::register('exclude.namespaces', function ($chain) {
});

Filter::apply($this, 'interceptor', 'exclude.namespaces');

fix(spec): Remove headers from php-vcr request matching


<?php

namespace App\Presenters;

trait PresentableTrait {

    /*
     * The Presenter class
     *
     * @var mixed
     */
    protected $presenter;

    /**
     * View presenter instance
     *
     * @var mixed
     */
    protected $presenterInstance;

    /**
     * Prepare a new or cached presenter instance
     *
     * @return mixed
     * @throws PresenterException
     */
    public function present()
    {
        if (!$this->presenter or !class_exists($this->presenter)) {
            throw new Exception\PresenterException("The {$presenter} property is not set");
        }

        if (!isset($this->presenterInstance)) {
            $this->presenterInstance = new $this->presenter($this);
        }
        return $this->presenterInstance;
    }
}

<?php

namespace App\Presenters;

trait PresentableTrait {

    /**
     * View presenter instance
     *
     * @var mixed
     */
    protected $presenterInstance;

    /**
     * Prepare a new or cached presenter instance
     *
     * @return mixed
     * @throws PresenterException
     */
    public function present()
    {
        if (!$this->presenter or !class_exists($this->presenter)) {
            throw new Exception\PresenterException("The {$presenter} property is not set");
        }

        if (!isset($this->presenterInstance)) {
            $this->presenterInstance = new $this->presenter($this);
        }
        return $this->presenterInstance;
    }
}

Remove presenter prop from Trait.

Remove presenter prop from Trait.


<?php

namespace Meatings\Repositories;

use Meatings\User;

class UserRepository {

    public function findByUsernameOrCreate($userData)
    {

        return User::firstOrCreate([
            'name' => $userData->name,
            'email' => $userData->email,
            'avatar' => $userData->avatar,
        ]);
    }
}

<?php

namespace Meatings\Repositories;

use Meatings\User;

class UserRepository {

    public function findByUsernameOrCreate($userData)
    {
        $user = User::firstOrCreate([
            'name' => $userData->getName(),
            'email' => $userData->getEmail(),
            'avatar' => $userData->getAvatar(),
        ]);

        $user->token = $userData->token;
        $user->save();

        return $user;
    }
}

Save user data right from the object

Save user data right from the object


<?php

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

namespace Symfony\Component\Security\Http;

final class SecurityEvents
{
    /**
     * The INTERACTIVE_LOGIN event occurs after a user is logged in
     * interactively for authentication based on http, cookies or X509.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const INTERACTIVE_LOGIN = 'security.interactive_login';

    /**
     * The SWITCH_USER event occurs before switch to another user and
     * before exit from an already switched user.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const SWITCH_USER = 'security.switch_user';
}

<?php

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

namespace Symfony\Component\Security\Http;

final class SecurityEvents
{
    /**
     * The INTERACTIVE_LOGIN event occurs after a user has actively logged
     * into your website. It is important to distinguish this action from
     * non-interactive authentication methods, such as:
     *   - authentication based on your session.
     *   - authentication using a HTTP basic or HTTP digest header.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const INTERACTIVE_LOGIN = 'security.interactive_login';

    /**
     * The SWITCH_USER event occurs before switch to another user and
     * before exit from an already switched user.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const SWITCH_USER = 'security.switch_user';
}

[Security] Fix security.interactive_login event const doc block


@extends('layout.master')

@section('main_content')

  {{ Form::open(['route' => 'sessions.store', 'class' => 'form-signin']) }}

Please sign in

    {{ Form::text('email', NULL, array('class' => 'form-control', 'placeholder' => 'Email Address')) }}

    {{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}

    {{ Form::submit('Sign in', array('class' => 'btn btn-lg btn-primary btn-block')) }}

  {{ Form::close() }}

@stop

@extends('layout.master')

@section('main_content')

  {{ Form::open(['route' => 'sessions.store', 'class' => 'form-signin']) }}

Please sign in

      {{ Form::label('email', 'Email', array('class' => 'sr-only')) }}
      {{ Form::text('email', NULL, array('class' => 'form-control', 'placeholder' => 'Email Address')) }}

      {{ Form::label('password', 'Password', array('class' => 'sr-only')) }}
      {{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}

    {{ Form::submit('Sign in', array('class' => 'btn btn-lg btn-primary btn-block')) }}

  {{ Form::close() }}

@stop

Add labels, form group div to signin form.


<?php

namespace AlterPHP\EasyAdminExtensionBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('easy_admin_extension');

        $rootNode
            ->children()
                ->arrayNode('custom_form_types')
                    ->useAttributeAsKey('short_name')
                    ->prototype('scalar')
                        ->validate()
                            ->ifTrue(function ($v) {
                                return !\class_exists($v);
                            })
                                ->thenInvalid('Class %s for custom type does not exist !')
                        ->end()
                    ->end()
                ->end()
                ->scalarNode('minimum_role')
                    ->defaultNull()
                ->end()
                ->arrayNode('embedded_list')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('open_new_tab')
                            ->defaultTrue()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace AlterPHP\EasyAdminExtensionBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('easy_admin_extension');

        $treeBuilder
            ->getRootNode()
            ->children()
                ->arrayNode('custom_form_types')
                    ->useAttributeAsKey('short_name')
                    ->prototype('scalar')
                        ->validate()
                            ->ifTrue(function ($v) {
                                return !\class_exists($v);
                            })
                                ->thenInvalid('Class %s for custom type does not exist !')
                        ->end()
                    ->end()
                ->end()
                ->scalarNode('minimum_role')
                    ->defaultNull()
                ->end()
                ->arrayNode('embedded_list')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('open_new_tab')
                            ->defaultTrue()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Remove Sf4.2 deprecation on TreeBuilder constructor


<?php

namespace AppBundle\Service;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\EntityManager;

/**
 * Class JwtService
 * @package AppBundle\Service
 */
class JwtService{
    private $ts;

    /**
     * JwtService constructor.
     * @param TokenStorage $ts
     */
    public function __construct(TokenStorage $ts, $jwtManager){
        $this->ts           = $ts;
        $this->jwtManager   = $jwtManager;
    }

    /**
     * Create token acces
     * @return mixed
     */
    public function getToken(){
        $client  = $this->ts->getToken()->getUser();
        return $this->jwtManager->create($client);
    }
}

Fix (JWT Service): Text files should end with a newline character


<?php

function init_phabricator_script(array $options) {
  error_reporting(E_ALL | E_STRICT);
  ini_set('display_errors', 1);

  $include_path = ini_get('include_path');
  ini_set(
    'include_path',
    $include_path.PATH_SEPARATOR.dirname(__FILE__).'/../../../');

  $ok = @include_once 'arcanist/scripts/init/init-script.php';
  if (!$ok) {
    echo
      'FATAL ERROR: Unable to load the "Arcanist" library. '.
      'Put "arcanist/" next to "phabricator/" on disk.';
    echo "\n";

    exit(1);
  }

  phutil_load_library('arcanist/src');
  phutil_load_library(dirname(__FILE__).'/../../src/');

  $config_optional = $options['config.optional'];
  PhabricatorEnv::initializeScriptEnvironment($config_optional);
}

<?php

function init_phabricator_script(array $options) {
  error_reporting(E_ALL | E_STRICT);
  ini_set('display_errors', 1);

  $include_path = ini_get('include_path');
  ini_set(
    'include_path',
    $include_path.PATH_SEPARATOR.dirname(__FILE__).'/../../../');

  $ok = @include_once 'arcanist/support/init/init-script.php';
  if (!$ok) {
    echo
      'FATAL ERROR: Unable to load the "Arcanist" library. '.
      'Put "arcanist/" next to "phabricator/" on disk.';
    echo "\n";

    exit(1);
  }

  phutil_load_library('arcanist/src');
  phutil_load_library(dirname(__FILE__).'/../../src/');

  $config_optional = $options['config.optional'];
  PhabricatorEnv::initializeScriptEnvironment($config_optional);
}

Update a Phabricator -> Arcanist include path for scripts in Phabricator

Summary: Ref T13395. Since there's very little code which really makes sense in "scripts/", I've moved most of it to other places.

Test Plan: Ran `bin/phd`.

Maniphest Tasks: T13395

Differential Revision: https://secure.phabricator.com/D20994


<?php

namespace Darvin\ConfigBundle;

use Darvin\ConfigBundle\DependencyInjection\Compiler\ConfigurationPoolPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Configuration bundle
 */
class DarvinConfigBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new ConfigurationPoolPass(), PassConfig::TYPE_BEFORE_REMOVING);
    }
}

<?php

namespace Darvin\ConfigBundle;

use Darvin\ConfigBundle\DependencyInjection\Compiler\ConfigurationPoolPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Configuration bundle
 */
class DarvinConfigBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new ConfigurationPoolPass());
    }
}

Reset configuration pool compiler pass type to default.


<?php
/**
 * Script to validate a cfdi and show all the errors found
 */

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

use CFDIReader\CFDIFactory;

call_user_func(function() use($argv, $argc) {

    $script = array_shift($argv);
    if ($argc == 1) {
        echo "Set the file of the file to validate\n";
        echo "Usage: $script [file1.xml] [file2.xml]\n";
        exit;
    }

    // create objects
    $factory = new CFDIFactory();
    while(count($argv)) {
        $argument = array_shift($argv);
        $filename = realpath($argument);
        if ("" === $filename or !is_readable($filename)) {
            echo "File $argument was not found or is not readable\n";
            continue;
        }
        try {
            $errors = [];
            $warnings = [];
            $reader = $factory->newCFDIReader(file_get_contents($filename), $errors, $warnings);
            foreach($errors as $message) {
                echo "File $argument ERROR: $message\n";
            }
            foreach($warnings as $message) {
                echo "File $argument ERROR: $message\n";
            }
            echo "File $argument with UUID " . $reader->getUUID(), " OK\n";
        } catch(Exception $ex) {
            echo "File $argument give exception: ", $ex->getMessage(), "\n";
            echo $ex->getTraceAsString(), "\n";
        }

    }

});

<?php
/**
 * Script to validate cfdi files and show all the errors found
 */

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

use CFDIReader\CFDIFactory;

$script = array_shift($argv);
if ($argc == 1 || in_array('-h', $argv) || in_array('--help', $argv)) {
    echo "Set the file of the file to validate\n";
    echo "Usage: $script [file1.xml] [file2.xml]\n";
    exit;
}

// create the factory
$factory = new CFDIFactory();
while (count($argv)) {
    // process next argument
    $argument = array_shift($argv);
    $filename = realpath($argument);
    if ("" === $filename or !is_file($filename) or !is_readable($filename)) {
        echo "File $argument FATAL: not found or is not readable\n";
        continue;
    }
    // do the object creation
    $errors = [];
    $warnings = [];
    try {
        $reader = $factory->newCFDIReader(file_get_contents($filename), $errors, $warnings);
        foreach ($errors as $message) {
            echo "File $argument ERROR: $message\n";
        }
        foreach ($warnings as $message) {
            echo "File $argument WARNING: $message\n";
        }
        echo "File $argument UUID: " . $reader->getUUID(), "\n";
    } catch (Exception $ex) {
        echo "File $argument FATAL: ", $ex->getMessage(), "\n";
    }
}

Reformat and normalize messages, include -h and --help parameters


<?php

require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');

class MustacheTestSuite extends TestSuite {
  function MustacheTestSuite() {
    $this->TestSuite('All Mustache tests');
    $this->addFile("tests/testStringScanner.php");
    $this->addFile("tests/testMustache.php");
    $this->addFile("tests/testContext.php");
    $this->addFile("tests/testParser.php");
    $this->addFile("tests/testGenerator.php");
  }
};

?>

<?php

require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');

class MustacheTestSuite extends TestSuite {
  function MustacheTestSuite() {
    $this->TestSuite('All Mustache tests');
    $this->addFile(dirname(__FILE__)."/testStringScanner.php");
    $this->addFile(dirname(__FILE__)."/testHelpers.php");
    $this->addFile(dirname(__FILE__)."/testMustache.php");
    $this->addFile(dirname(__FILE__)."/testContext.php");
    $this->addFile(dirname(__FILE__)."/testParser.php");
    $this->addFile(dirname(__FILE__)."/testGenerator.php");
    $this->addFile(dirname(__FILE__)."/testSpec.php");
  }
};

?>

Add new unit test files to testsuite

Add new unit test files to testsuite


<?php namespace Tests\Feature;

use Tests\DatabaseTestCase;

class ProfilesTest extends DatabaseTestCase
{
	/** @test **/
	public function a_user_has_a_profile()
	{
		$user = create('App\Data\User');

		$this->get(route('profile', $user))
			->assertSee($user->name);
	}

	/** @test **/
	public function profiles_display_all_discussions_by_the_user()
	{
		$user = create('App\Data\User');

		$discussion = create('App\Data\Discussion', ['user_id' => $user->id]);

		$this->get(route('profile', $user))
			->assertSee($discussion->title);
	}
}

<?php namespace Tests\Feature;

use Tests\DatabaseTestCase;

class ProfilesTest extends DatabaseTestCase
{
	/** @test **/
	public function a_user_has_a_profile()
	{
		$user = $this->createUser();

		$this->get(route('profile', $user))
			->assertSee($user->name);
	}

	/** @test **/
	public function profiles_display_all_discussions_by_the_user()
	{
		$user = $this->createUser();

		$discussion = create('App\Data\Discussion', ['user_id' => $user->id]);

		$this->get(route('profile', $user))
			->assertSee($discussion->title);
	}
}

Work on the profiles tests

Work on the profiles tests