<?php

/**
 * Description of MemberLoginFilter
 *
 * @author marcus
 */
class MemberLoginFilter implements RequestFilter
{

    public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
    {
    }

    /**
     * Check if we're in a login request. If so, we're going to explicitly disable
     * restrictedobjects permission checks. This is poor, but dictated by the core
     * member login code performing writes prior to having a user context.
     *
     * @param \SS_HTTPRequest $request
     * @param \Session $session
     * @param \DataModel $model
     */
    public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model)
    {
        if (strtolower($request->httpMethod()) === 'post' && $request->getURL() === 'Security/LoginForm') {
            Restrictable::set_enabled(false);
        }
    }
}

<?php

/**
 * Description of MemberLoginFilter
 *
 * @author marcus
 */
class MemberLoginFilter implements RequestFilter
{

    public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
    {
    }

    /**
     * Check if we're in a login request. If so, we're going to explicitly disable
     * restrictedobjects permission checks. This is poor, but dictated by the core
     * member login code performing writes prior to having a user context.
     *
     * @param \SS_HTTPRequest $request
     * @param \Session $session
     * @param \DataModel $model
     */
    public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model)
    {
        if (strtolower($request->httpMethod()) === 'post' && (
            $request->getURL() === 'Security/LoginForm' ||
            $request->getURL() === 'Security/LostPasswordForm'
            )) {
            Restrictable::set_enabled(false);
        }
    }
}

Allow submits from LostPasswordForm through


<?php

/**
 * This file is part of CodeIgniter 4 framework.
 *
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace CodeIgniter\Log\Handlers;

/**
 * Base class for logging
 */
abstract class BaseHandler implements HandlerInterface
{
    /**
     * Handles
     *
     * @var array
     */
    protected $handles;

    /**
     * Date format for logging
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * Constructor
     */
    public function __construct(array $config)
    {
        $this->handles = $config['handles'] ?? [];
    }

    /**
     * Checks whether the Handler will handle logging items of this
     * log Level.
     */
    public function canHandle(string $level): bool
    {
        return in_array($level, $this->handles, true);
    }

    /**
     * Handles logging the message.
     * If the handler returns false, then execution of handlers
     * will stop. Any handlers that have not run, yet, will not
     * be run.
     *
     * @param string $level
     * @param string $message
     */
    abstract public function handle($level, $message): bool;

    /**
     * Stores the date format to use while logging messages.
     */
    public function setDateFormat(string $format): HandlerInterface
    {
        $this->dateFormat = $format;

        return $this;
    }
}

<?php

/**
 * This file is part of CodeIgniter 4 framework.
 *
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace CodeIgniter\Log\Handlers;

/**
 * Base class for logging
 */
abstract class BaseHandler implements HandlerInterface
{
    /**
     * Handles
     *
     * @var array
     */
    protected $handles;

    /**
     * Date format for logging
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * Constructor
     */
    public function __construct(array $config)
    {
        $this->handles = $config['handles'] ?? [];
    }

    /**
     * Checks whether the Handler will handle logging items of this
     * log Level.
     */
    public function canHandle(string $level): bool
    {
        return in_array($level, $this->handles, true);
    }

    /**
     * Stores the date format to use while logging messages.
     */
    public function setDateFormat(string $format): HandlerInterface
    {
        $this->dateFormat = $format;

        return $this;
    }
}

Remove unneeded abstract `handle()` method


<?php namespace Bican\Roles;

trait HasRole {

    /**
     * User belongs to many roles.
     *
     * @return mixed
     */
    public function roles()
    {
        return $this->belongsToMany('Bican\Roles\Role');
    }

    /**
     * Check if a user has provided role.
     *
     * @param int|string $providedRole
     * @return bool
     */
    public function hasRole($providedRole)
    {
        foreach ($this->roles()->get() as $role)
        {
            if ($role->id === $providedRole || $role->name === $providedRole) return true;
        }

        return false;
    }

    /**
     * Attach role.
     *
     * @param int|Role $role
     * @return mixed
     */
    public function attachRole($role)
    {
        return $this->roles()->attach($role);
    }

    /**
     * Detach role.
     *
     * @param int|Role $role
     * @return mixed
     */
    public function detachRole($role)
    {
        return $this->roles()->detach($role);
    }

}

<?php namespace Bican\Roles;

trait HasRole {

    /**
     * User belongs to many roles.
     *
     * @return mixed
     */
    public function roles()
    {
        return $this->belongsToMany('Bican\Roles\Role');
    }

    /**
     * Check if a user has any of the provided roles
     *
     * @param int|string|array $providedRoles
     * @return bool
     */
    public function hasRole($providedRoles)
    {
        if(!is_array($providedRoles))
        {
            $providedRoles = array($providedRoles);
        }

        foreach($providedRoles as $role)
        {
            if($this->hasSingleRole($role))
            {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if a user has provided role.
     *
     * @param int|string $providedRole
     * @return bool
     */
    public function hasSingleRole($providedRole)
    {
        foreach ($this->roles()->get() as $role)
        {
            if ($role->id === $providedRole || $role->name === $providedRole) return true;
        }

        return false;
    }

    /**
     * Attach role.
     *
     * @param int|Role $role
     * @return mixed
     */
    public function attachRole($role)
    {
        return $this->roles()->attach($role);
    }

    /**
     * Detach role.
     *
     * @param int|Role $role
     * @return mixed
     */
    public function detachRole($role)
    {
        return $this->roles()->detach($role);
    }

}

Add ability to check for multiple roles (using OR)


<?php
declare(strict_types=1);

namespace MattyG\Handlebars\Helper;

class ConcatHelper
{
    public function __invoke(...$args)
    {
        $options = array_pop($args);
        return implode("", $args);
    }
}

<?php
declare(strict_types=1);

namespace MattyG\Handlebars\Helper;

class ConcatHelper
{
    /**
     * @param ...$args
     */
    public function __invoke(...$args)
    {
        $options = array_pop($args);
        return implode("", $args);
    }
}

Add missing docblock to concat helper

Add missing docblock to concat helper


<?php

use UWDOEM\Framework\Etc\Settings;

class MockSettings extends Settings {

    public static function clear() {
        static::$settings = [];
    }
}

class SettingsTest extends PHPUnit_Framework_TestCase {

    public function testAddTemplateTheme() {
        MockSettings::addTemplateTheme("theme1");
        MockSettings::addTemplateTheme("theme2");

        $result = MockSettings::getTemplateThemes();

        $this->assertContains("theme1", $result);
        $this->assertContains("theme2", $result);
        $this->assertEquals(2, sizeof($result));

        MockSettings::clear();
    }

}

<?php

use UWDOEM\Framework\Etc\Settings;

class MockSettings extends Settings {

    public static function clear() {
        static::$settings["templateDirectories"] = [];
    }
}

class SettingsTest extends PHPUnit_Framework_TestCase {

    public function testAddTemplateTheme() {
        MockSettings::addTemplateTheme("theme1");
        MockSettings::addTemplateTheme("theme2");

        $result = MockSettings::getTemplateDirectories();

        $this->assertContains("theme1", $result[0]);
        $this->assertContains("theme2", $result[1]);
        $this->assertEquals(2, sizeof($result));

        MockSettings::clear();
    }

}

Adjust test to new settings.

Adjust test to new settings.


<?php

use Illuminate\Contracts\Console\Kernel;
use Symfony\Component\Console\Output\ConsoleOutput;

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

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

/** @var \Pterodactyl\Console\Kernel $kernel */
$kernel = $app->make(Kernel::class);

/*
 * Bootstrap the kernel and prepare application for testing.
 */
$kernel->bootstrap();

$output = new ConsoleOutput;

/*
 * Perform database migrations and reseeding before continuing with
 * running the tests.
 */
$output->writeln(PHP_EOL . '<comment>Refreshing database for Integration tests...</comment>');
$kernel->call('migrate:fresh', ['--database' => 'testing']);

$output->writeln('<comment>Seeding database for Integration tests...</comment>' . PHP_EOL);
$kernel->call('db:seed', ['--database' => 'testing']);

<?php

use Illuminate\Contracts\Console\Kernel;
use Symfony\Component\Console\Output\ConsoleOutput;

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

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

/** @var \Pterodactyl\Console\Kernel $kernel */
$kernel = $app->make(Kernel::class);

/*
 * Bootstrap the kernel and prepare application for testing.
 */
$kernel->bootstrap();

$output = new ConsoleOutput;

if (config('database.default') !== 'testing') {
    $output->writeln(PHP_EOL . '<error>Cannot run test process against non-testing database.</error>');
    $output->writeln(PHP_EOL . '<error>Environment is currently pointed at: "' . config('database.default') . '".</error>');
    exit(1);
}

/*
 * Perform database migrations and reseeding before continuing with
 * running the tests.
 */
if (!env('SKIP_MIGRATIONS')) {
    $output->writeln(PHP_EOL . '<info>Refreshing database for Integration tests...</info>');
    $kernel->call('migrate:fresh', ['--database' => 'testing']);

    $output->writeln('<info>Seeding database for Integration tests...</info>' . PHP_EOL);
    $kernel->call('db:seed', ['--database' => 'testing']);
} else {
    $output->writeln(PHP_EOL . '<comment>Skipping database migrations...</comment>' . PHP_EOL);
}

Make quick iteration testing easier

Make quick iteration testing easier


<?php

namespace Silber\Bouncer\Middleware;

use Illuminate\Routing\ControllerMiddlewareOptions;

trait AuthorizesResources
{
    /**
     * Authorize a resource action.
     *
     * @param  string  $name
     * @param  string  $model
     * @param  array  $options
     * @param  \Illuminate\Http\Request  $request
     * @return null|\Illuminate\Routing\ControllerMiddlewareOptions
     */
    public function authorizeResource($name, $model, array $options = [], $request = null)
    {
        $method = array_last(explode('@', ($request ?: request())->route()->getActionName()));

        $map = [
            'index' => 'view', 'create' => 'create', 'store' => 'create', 'show' => 'view',
            'edit' => 'update', 'update' => 'update', 'delete' => 'delete',
        ];

        if (property_exists($this, 'abilityMap')) {
            $map = array_merge($map, $this->abilityMap);
        }

        if ( ! in_array($method, array_keys($map))) {
            return new ControllerMiddlewareOptions($options);
        }

        $model = in_array($method, ['index', 'create', 'store']) ? $model : $name;

        return $this->middleware("can:{$map[$method]},{$model}");
    }
}

<?php

namespace Silber\Bouncer\Middleware;

use Illuminate\Routing\ControllerMiddlewareOptions;

trait AuthorizesResources
{
    /**
     * Authorize a resource action.
     *
     * @param  string  $name
     * @param  string  $model
     * @param  array  $options
     * @param  \Illuminate\Http\Request  $request
     * @return null|\Illuminate\Routing\ControllerMiddlewareOptions
     */
    public function authorizeResource($name, $model, array $options = [], $request = null)
    {
        $method = array_last(explode('@', ($request ?: request())->route()->getActionName()));

        $map = [
            'index' => 'view', 'create' => 'create', 'store' => 'create', 'show' => 'view',
            'edit' => 'update', 'update' => 'update', 'delete' => 'delete',
        ];

        if (property_exists($this, 'abilityMap')) {
            $map = array_merge($map, $this->abilityMap);
        }

        if ( ! in_array($method, array_keys($map))) {
            if (class_exists(ControllerMiddlewareOptions::class)) {
                return new ControllerMiddlewareOptions($options);
            }

            return null;
        }

        $model = in_array($method, ['index', 'create', 'store']) ? $model : $name;

        return $this->middleware("can:{$map[$method]},{$model}");
    }
}

Support earlier versions of laravel that don't have ControllerMiddlewareOptions


<?php

namespace Tests\Functional;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class NavigationTest extends \Tests\TestCase {

    use DatabaseMigrations;

    public function testGuestNavigation()
    {
        $this->get('/')
            ->assertSee('Log In')
            ->assertSee('href="/login"', false)
            ->assertDontSee('My List')
            ->assertDontSee('/list');
    }

    public function testUserListNavigation()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('My List')
            ->assertSee('/list')
            ->assertDontSee('Login')
            ->assertDontSee('href="/login"');
    }

    public function testUserAccountNavigation()
    {
        $user = factory(User::class)->create();
        $encodedUsername = htmlentities(
            $user->username,
            ENT_COMPAT | ENT_HTML401 | ENT_QUOTES
        );

        $this->actingAs($user)
            ->get('/')
            ->assertSee($encodedUsername)
            ->assertSee('href="/account"', false);
    }

    public function testUserAccountLogOut()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('Log Out')
            ->assertSee('href="/logout"', false);
    }

}

<?php

namespace Tests\Functional;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class NavigationTest extends \Tests\TestCase {

    use DatabaseMigrations;

    public function testGuestNavigation()
    {
        $this->get('/')
            ->assertSee('Log In')
            ->assertSee('href="/login"', false)
            ->assertDontSee('My List')
            ->assertDontSee('/list');
    }

    public function testUserListNavigation()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('My List')
            ->assertSee('/list')
            ->assertDontSee('Login')
            ->assertDontSee('href="/login"', false);
    }

    public function testUserAccountNavigation()
    {
        $user = factory(User::class)->create();
        $encodedUsername = htmlentities(
            $user->username,
            ENT_COMPAT | ENT_HTML401 | ENT_QUOTES
        );

        $this->actingAs($user)
            ->get('/')
            ->assertSee($encodedUsername, false)
            ->assertSee('href="/account"', false);
    }

    public function testUserAccountLogOut()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('Log Out')
            ->assertSee('href="/logout"', false);
    }

}

Disable HTML entity encoding in some tests


<?php class Analytics_PageTool extends PageTool {
/**
 * Google Analytics.
 * This simple PageTool doesn't have any functionality in the go() method.
 * Instead, pass the tracking code into the track() method.
 */
public function go($api, $dom, $template, $tool) { }

/**
 * Injects the required JavaScript code where needed to start tracking using
 * Google Analytics.
 *
 * @param string $trackingCode Your Google Analytics account code, looks like
 * this: UA-12345678-1
 */
public function track($trackingCode) {
	$js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js");
	if($js === false) {
		throw new HttpError(500, "Google Analytics script failure");
	}
	$js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js);
	$this->_dom["head"]->append(
		"script",
		["data-PageTool" => "Analytics"],
		$js
	);
}

}#

<?php class Analytics_PageTool extends PageTool {
/**
 * Google Analytics.
 * This simple PageTool doesn't have any functionality in the go() method.
 * Instead, pass the tracking code into the track() method.
 */
public function go($api, $dom, $template, $tool) { }

/**
 * Injects the required JavaScript code where needed to start tracking using
 * Google Analytics.
 *
 * @param string $trackingCode Your Google Analytics account code, looks like
 * this: UA-12345678-1
 */
public function track($trackingCode) {
	$js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js");
	if($js === false) {
		throw new HttpError(500, "Google Analytics script failure");
	}
	$js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js);
	$this->_dom["head"]->prependChild(
		"script",
		["data-PageTool" => "Analytics"],
		$js
	);
}

}#

Prepend js, improving load times

Prepend js, improving load times


<?php

// Return post entry meta information
function roots_entry_meta() {
  echo '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. sprintf(__('Posted on %s at %s.', 'roots'), get_the_date(), get_the_time()) .'</time>';
  echo '
'. __('Written by', 'roots') .' '. get_the_author() .'
';
}

Fix lowercase reference to $WP_User->ID on roots_entry_meta()


<?php

namespace Tests\Feature;

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

use App;

class LoginTest extends TestCase
{
    use DatabaseMigrations;

    public function testBasicTest()
    {
        $this->get('/')->assertRedirect('/login');
        $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ])
            ->assertStatus(401);
    }

    public function testLoginForm()
    {
        $response = $this->get('/login');
        $response->assertViewIs('auth.login');
        $response->assertStatus(200);
    }

    public function testLoggedIn()
    {
        $user = factory(App\User::class)->create();
        $response = $this->actingAs($user)->get('/');
        $response->assertViewIs('home');
        $response->assertStatus(200);
    }

    public function testLogout()
    {
        $user = factory(App\User::class)->create();
        $this->actingAs($user)->post('/logout')->assertRedirect('/');
    }
}

<?php

namespace Tests\Feature;

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

use App;

class LoginTest extends TestCase
{
    use DatabaseMigrations;

    public function testBasicTest()
    {
        $this->get('/')->assertRedirect('/login');
        $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ])
            ->assertStatus(401);
    }

    public function testLoginForm()
    {
        $response = $this->get('/login');
        $response->assertViewIs('auth.login');
        $response->assertStatus(200);
    }

    public function testLoggedIn()
    {
        $user = factory(App\User::class)->create();
        $response = $this->actingAs($user)->get('/');
        $response->assertViewIs('dashboard');
        $response->assertStatus(200);
    }

    public function testLogout()
    {
        $user = factory(App\User::class)->create();
        $this->actingAs($user)->post('/logout')->assertRedirect('/');
    }
}

Fix an assertion due to a related view rename


<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatEntry.php';

/**
 * A single line search entry widget
 *
 * @package   Swat
 * @copyright 2004-2007 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatSearch extends SwatEntry
{
	// {{{ public properties

    /**
     * SwatSearch title value
     *
     * Text content of the widget, or defaults to 'Enter Search'.
     *
     * @var string
     */
	public $title;

	// }}}
	// {{{ protected function getDisplayValue()

	/**
	 * Displays a value for SwatSearch
	 *
	 * The methond returns either the title or the correct search entry.
	 *
	 * @return string the display value
	 */
	protected function getDisplayValue()
	{
		if ($this->value === null){
			if ($this->title === null)
				return 'Enter Search...';
			else
				return $this->title;
		} else {
			return parent::getDisplayValue();
		}
	}

	// }}}
}

?>

Use tabs instead of spaces to indent docblock

svn commit r15184


<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Logger;

use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

class Logger extends AbstractLogger implements LoggerInterface
{
    /**
     * @var string
     */
    private $filePath;

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

    public function log($level, $message, array $context = []): void
    {
        if (!file_exists($this->filePath)) {
            if (!mkdir($concurrentDirectory = dirname($this->filePath), 0777, true) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }

        file_put_contents(
            $this->filePath,
            sprintf(
                "Time: %s, Level: %s, Message: %s, Context: %s\n\n",
                (new \DateTime())->format('d-m-y H:i:s'),
                $level,
                $message,
                json_encode($context)
            ),
            FILE_APPEND
        );
    }
}

<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Logger;

use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

class Logger extends AbstractLogger implements LoggerInterface
{
    /**
     * @var string
     */
    private $filePath;

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

    public function log($level, $message, array $context = []): void
    {
        if (!file_exists(dirname($this->filePath))) {
            if (!mkdir($concurrentDirectory = dirname($this->filePath), 0777, true) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }

        file_put_contents(
            $this->filePath,
            sprintf(
                "Time: %s, Level: %s, Message: %s, Context: %s\n\n",
                (new \DateTime())->format('d-m-y H:i:s'),
                $level,
                $message,
                json_encode($context)
            ),
            FILE_APPEND
        );
    }
}

Create dir only if it does not exit, not if the file does not exist


<?php

namespace Frontend\Modules\Profiles\Actions;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Core\Engine\Navigation as FrontendNavigation;
use Frontend\Modules\Profiles\Engine\Authentication as FrontendProfilesAuthentication;

/**
 * This is the index-action, it can be used as a dashboard.
 */
class Index extends FrontendBaseBlock
{
    public function execute(): void
    {
        // only logged in profiles can seer their dashboard
        if (FrontendProfilesAuthentication::isLoggedIn()) {
            // call the parent
            parent::execute();

            /*
             * You could use this as some kind of dashboard where you can show an activity
             * stream, some statistics, ...
             */

            $this->loadTemplate();
        } else {
            // profile not logged in
            $this->redirect(
                FrontendNavigation::getUrlForBlock(
                    'Profiles',
                    'Login'
                ) . '?queryString=' . FrontendNavigation::getUrlForBlock('Profiles'),
                307
            );
        }
    }
}

<?php

namespace Frontend\Modules\Profiles\Actions;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Modules\Profiles\Engine\Authentication as FrontendProfilesAuthentication;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;

/**
 * You could use this as some kind of dashboard where you can show an activity
 * stream, some statistics, ...
 */
class Index extends FrontendBaseBlock
{
    public function execute(): void
    {
        if (!FrontendProfilesAuthentication::isLoggedIn()) {
            throw new InsufficientAuthenticationException('You need to log in to see your dashboard');
        }

        parent::execute();
        $this->loadTemplate();
    }
}

Clean up the profiles index action

Clean up the profiles index action


<?php
namespace AndreasWolf\DebuggerClient\Tests\Unit\Protocol;

use AndreasWolf\DebuggerClient\Protocol\DebugSession;
use AndreasWolf\DebuggerClient\Tests\Unit\UnitTestCase;

/**
 *
 *
 * @author Andreas Wolf <aw@foundata.net>
 */
class DebugSessionTest extends UnitTestCase {

	/**
	 * @test
	 */
	public function newSessionIsNotInitialized() {
		$session = new DebugSession();
		$this->assertFalse($session->isInitialized());
	}

}

<?php
namespace AndreasWolf\DebuggerClient\Tests\Unit\Protocol;

use AndreasWolf\DebuggerClient\Protocol\DebuggerCommand;
use AndreasWolf\DebuggerClient\Protocol\DebugSession;
use AndreasWolf\DebuggerClient\Tests\Unit\UnitTestCase;

/**
 *
 *
 * @author Andreas Wolf <aw@foundata.net>
 */
class DebugSessionTest extends UnitTestCase {

	/**
	 * @test
	 */
	public function newSessionIsNotInitialized() {
		$session = new DebugSession();
		$this->assertFalse($session->isInitialized());
	}

	/**
	 * @test
	 */
	public function transactionsAreCorrectlyCreated() {
		$session = new DebugSession();
		/** @var DebuggerCommand $command */
		$command = $this->getMock('AndreasWolf\DebuggerClient\Protocol\DebuggerCommand');

		$transaction = $session->startTransaction($command);

		$this->assertSame(0, $transaction->getId());
	}

	/**
	 * @test
	 */
	public function consecutiveTransactionsHaveDifferentIds() {
		$session = new DebugSession();
		/** @var DebuggerCommand $command */
		$command = $this->getMock('AndreasWolf\DebuggerClient\Protocol\DebuggerCommand');

		$transactionA = $session->startTransaction($command);
		$transactionB = $session->startTransaction($command);

		$this->assertNotEquals($transactionA->getId(), $transactionB->getId());
	}

}

[TASK] Add a few unit tests for transaction handling


<?php include ('theme/header.php'); ?>

Installation

    <form action="install.php">
      <legend>Database Name</legend>
      <input type="text" name="dbname">

      <legend>Database Username</legend>
      <input type="text" name="dbusername">

      <legend>Database Password</legend>
      <input type="password" name="dbpassword">

      <input type="submit" name="submit" value="Submit" class="success button">
    </form>

<?php include('theme/footer.php'); ?>

<?php include ('theme/header.php'); ?>

<?php
$sql = '"CREATE TABLE small_victories (date DATE, latest_amount DECIMAL(8,2));"';
?>

Installation

    <form action="install.php">
      <legend>Database Name</legend>
      <input type="text" name="dbname">

      <legend>Database Username</legend>
      <input type="text" name="dbusername">

      <legend>Database Password</legend>
      <input type="password" name="dbpassword">

      <input type="submit" name="submit" value="Submit" class="success button">
    </form>

<?php include('theme/footer.php'); ?>

Add sql statement for creating the table that will store the deb data


<?php
class Kwc_Basic_BackgroundWindowWidth_Form extends Kwc_Abstract_Composite_Form
{
    protected function _initFields()
    {
        parent::_initFields();

        $backgroundColors = Kwc_Abstract::getSetting($this->getClass(), 'backgroundColors');
        $fs = $this->add(new Kwf_Form_Container_FieldSet(trlKwf('Standard Adjustments')));
        $fs->add(new Kwf_Form_Field_Select('background_color', trlKwf('Background Color')))
            ->setAllowBlank(true)
            ->setValues($backgroundColors);
        $fs->add(new Kwf_Form_Field_NumberField('margin_bottom', trlKwf('Margin Bottom')))
            ->setAllowBlank(true)
            ->setWidth(30)
            ->setComment('px');
    }
}

<?php
class Kwc_Basic_BackgroundWindowWidth_Form extends Kwc_Abstract_Composite_Form
{
    protected function _initFields()
    {
        parent::_initFields();

        $backgroundColors = Kwc_Abstract::getSetting($this->getClass(), 'backgroundColors');
        $fs = $this->add(new Kwf_Form_Container_FieldSet(trlKwf('Standard Adjustments')));
        $fs->setName('standardAdjustments');
        $fs->add(new Kwf_Form_Field_Select('background_color', trlKwf('Background Color')))
            ->setAllowBlank(true)
            ->setValues($backgroundColors);
        $fs->add(new Kwf_Form_Field_NumberField('margin_bottom', trlKwf('Margin Bottom')))
            ->setAllowBlank(true)
            ->setWidth(30)
            ->setComment('px');
    }
}

Set fieldset name for standard adjustments necessary to be able to extend fieldset with form fields


<?php

class MockJsonModel extends Illuminate\Database\Eloquent\Model
{
    use \ModelJsonColumn\JsonColumnTrait;

    protected $json_columns;

    public function __construct(array $attributes = [])
    {
        static::$booted[get_class($this)] = true;
        parent::__construct($attributes);
    }

    public function setJsonColumns(array $columns)
    {
        $this->json_columns = $columns;
    }

    public function setCastsColumns(array $columns)
    {
        $this->casts = $columns;
    }

    public function setJsonColumnDefaults($column_name, $defaults)
    {
        $this->json_defaults[$column_name] = $defaults;
    }

    public function getCustomGetAttribute()
    {
        return 'custom getter result';
    }

    public function setCustomSetAttribute($value)
    {
        $this->setJsonAttribute($this->jsonAttributes['custom_set'], 'custom_set', "custom {$value}");
    }
}

<?php

class MockJsonModel extends Illuminate\Database\Eloquent\Model
{
    use \ModelJsonColumn\JsonColumnTrait;

    protected $json_columns;

    public function __construct(array $attributes = [])
    {
        static::$booted[get_class($this)] = true;
        parent::__construct($attributes);
    }

    public function setJsonColumns(array $columns)
    {
        $this->json_columns = $columns;
    }

    public function setCastsColumns(array $columns)
    {
        $this->casts = $columns;
    }

    public function setJsonColumnDefaults($column_name, $defaults)
    {
        $this->json_defaults[$column_name] = $defaults;
    }
}

Remove irrelvant methods in the test model


<?php

namespace Solid\Ajax\Controllers;

use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    /**
     * Execute an action on the controller.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callAction($method, $parameters)
    {
        $result = parent::callAction($method, $parameters);

        if (app('ajax.helper')->isFrameworkAjax()) {
            $result = $this->prepareAjaxActionResponse($result);
        }

        return $result;
    }

    /**
     * Prepare response to make it compatible with
     * front end Ajax Framework
     *
     * @param  mixed        $result
     *
     * @return JsonResponse
     */
    protected function prepareAjaxActionResponse($result)
    {
        if ($result instanceof \Illuminate\View\View) {
            return $this->ajaxResponse(['result' => $result->render()]);
        }

        if (is_array($result)) {
            foreach ($result as $key => $value) {
                if ($value instanceof \Illuminate\View\View) {
                    $result[$key] = $value->render();
                }
            }
        }
        return $this->ajaxResponse($result);
    }

    /**
     * Convert given result to format expected by front end framework
     *
     * @param  mixed        $result
     *
     * @return JsonResponse
     */
    protected function ajaxResponse($result)
    {
        return response()->json($result);
    }
}

<?php

namespace Solid\Ajax;

use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    /**
     * Execute an action on the controller.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callAction($method, $parameters)
    {
        $result = parent::callAction($method, $parameters);

        if (app('ajax.helper')->isFrameworkAjax()) {
            $result = $this->prepareAjaxActionResponse($result);
        }

        return $result;
    }

    /**
     * Prepare response to make it compatible with
     * front end Ajax Framework
     *
     * @param  mixed        $result
     *
     * @return JsonResponse
     */
    protected function prepareAjaxActionResponse($result)
    {
        if ($result instanceof \Illuminate\View\View) {
            return $this->ajaxResponse(['result' => $result->render()]);
        }

        if (is_array($result)) {
            foreach ($result as $key => $value) {
                if ($value instanceof \Illuminate\View\View) {
                    $result[$key] = $value->render();
                }
            }
        }
        return $this->ajaxResponse($result);
    }

    /**
     * Convert given result to format expected by front end framework
     *
     * @param  mixed        $result
     *
     * @return JsonResponse
     */
    protected function ajaxResponse($result)
    {
        return response()->json($result);
    }
}

Fix namespace on solid ajax.

Fix namespace on solid ajax.


<?php

namespace Jira\Service;

use Jira\HttpClient;

class Version
{
    /**
     * @var HttpClient
     */
    protected  $client;

    /**
     * Project constructor.
     * @param HttpClient $client
     */
    public function __construct($client)
    {
        $this->client = $client;
    }

    /**
     * @param string $versionId
     * @return object
     */
    public function getVersion($versionId)
    {
        return $this->client->request('GET','/rest/api/2/version/'. urlencode($versionId));
    }

    /**
     * Update the version
     *
     * @param object $version
     */
    public function updateVersion($version)
    {
        $this->client->request('PUT','/rest/api/2/version/'. $version->id, ['body' => json_decode(json_encode($version), true)]);
    }

    /**
     * Create a new version
     *
     * @param object $version
     */
    public function createVersion($version)
    {
        $this->client->request('POST','/rest/api/2/version', ['body' => json_decode(json_encode($version), true)]);
    }
}

<?php

namespace Jira\Service;

use Jira\HttpClient;

class Version
{
    /**
     * @var HttpClient
     */
    protected  $client;

    /**
     * Project constructor.
     * @param HttpClient $client
     */
    public function __construct($client)
    {
        $this->client = $client;
    }

    /**
     * @param string $versionId
     * @return object
     */
    public function getVersion($versionId)
    {
        return $this->client->request('GET','/rest/api/2/version/'. urlencode($versionId));
    }

    /**
     * Update the version
     *
     * @param object $version
     */
    public function updateVersion($version)
    {
       $this->client->request('PUT','/rest/api/2/version/'. $version->id, [
            'json' => json_decode(json_encode($version), true)
       ]);
    }

    /**
     * Create a new version
     *
     * @param object $version
     */
    public function createVersion($version)
    {
        $this->client->request('POST','/rest/api/2/version', [
            'json' => json_decode(json_encode($version), true)
        ]);
    }
}

Fix issue releated to create and update of the version


<?php

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('elixir')) {
    /**
     * Get the path to a versioned Elixir file.
     *
     * @param  string  $file
     * @param  string  $buildDirectory
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    function elixir($file, $buildDirectory = '/')
    {
        static $manifest;
        static $manifestPath;

        if (is_null($manifest) || $manifestPath !== $buildDirectory) {
            $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true);

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return '/'.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }
}

<?php

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('elixir')) {
    /**
     * Get the path to a versioned Elixir file.
     *
     * @param  string  $file
     * @param  string  $buildDirectory
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    function elixir($file, $buildDirectory = 'build')
    {
        static $manifest;
        static $manifestPath;

        if (is_null($manifest) || $manifestPath !== $buildDirectory) {
            $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true);

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return '/'.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }
}

Revert "Adjust default build directory for `elixir`"

This reverts commit f38c2e156dfe61d2e55d98c8a59d5629d8e7cf1c.


<?php

/*
 * This file is part of the Sami utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sami\Version;

class SingleVersionCollection extends VersionCollection
{
    public function add($version, $longname = null)
    {
        if (count($this->versions)) {
            throw new \LogicException('A SingleVersionCollection can only contain one Version');
        }

        parent::add($version, $longname);
    }

    protected function switchVersion(Version $version)
    {
    }
}

<?php

/*
 * This file is part of the Sami utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sami\Version;

class SingleVersionCollection extends VersionCollection
{
    public function add($version, $longname = null)
    {
        $countable = is_array($this->versions) || $this->versions instanceof \Countable;

        if ($countable && count($this->versions)) {
            throw new \LogicException('A SingleVersionCollection can only contain one Version');
        }

        parent::add($version, $longname);
    }

    protected function switchVersion(Version $version)
    {
    }
}

Fix counting of non-countable versions for PHP 7.2


<form action="<?php echo OC_Helper::linkToRoute('core_lostpassword_reset', $_['args']) ?>" method="post">
	<fieldset>
		<?php if($_['success']): ?>

<?php echo $l->t('Your password was reset'); ?>

<a href="<?php echo OC_Helper::linkTo('', 'index.php') ?>/"><?php echo $l->t('To login page'); ?>

		<?php else: ?>

				<?php echo $l->t( 'New password' ); ?>
				<input type="password" name="password" id="password" value="" required />

			<input type="submit" id="submit" value="<?php echo $l->t('Reset password'); ?>" />
		<?php endif; ?>
	</fieldset>
</form>

<form action="<?php print_unescaped(OC_Helper::linkToRoute('core_lostpassword_reset', $_['args'])) ?>" method="post">
	<fieldset>
		<?php if($_['success']): ?>

<?php p($l->t('Your password was reset')); ?>

<a href="<?php print_unescaped(OC_Helper::linkTo('', 'index.php')) ?>/"><?php p($l->t('To login page')); ?>

		<?php else: ?>

				<?php p($l->t('New password')); ?>
				<input type="password" name="password" id="password" value="" required />

			<input type="submit" id="submit" value="<?php p($l->t('Reset password')); ?>" />
		<?php endif; ?>
	</fieldset>
</form>

Replace echo with `p` or `print_unescaped`

Using echo instead of `p` or `print_unescaped` is a bad style, to prevent people from copying it  I've adjusted it.


<?php

/**
 * sfWidgetFormDuration is a text field that parses a duration ("1:15") into an integer
 *
 * @package    limetracker
 * @subpackage widget
 * @author     Michael Nutt <michael@nuttnet.net>
 * @version    0.1
 */

class sfWidgetFormDuration extends sfWidgetFormInput
{
  /**
   * Configures the current widget
   */
  protected function configure()
  {
    parent::configure($options, $attributes);
  }

  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    return parent::render($name, $this->getFormattedLength($value), $attributes, $errors);
  }

  public function getFormattedLength($length=0) {
    $hours = (int) ($length / 3600);
    $minutes = (int) ($length % 3600 / 60);
    $seconds = (int) ($length % 60);

    if($seconds < 10)
      $seconds = "0".$seconds;

    if($hours > 0) {
      if($minutes < 10)
        $minutes = "0".$minutes;
      return $hours.":".$minutes.":".$seconds;
    } else {
      return $minutes.":".$seconds;
    }
  }
}

<?php

/**
 * sfWidgetFormDuration is a text field that parses a duration ("1:15") into an integer
 *
 * @package    limetracker
 * @subpackage widget
 * @author     Michael Nutt <michael@nuttnet.net>
 * @version    0.1
 */

class sfWidgetFormDuration extends sfWidgetFormInput
{
  /**
   * Configures the current widget
   */
  protected function configure($options=array(), $attributes=array())
  {
    parent::configure($options, $attributes);
  }

  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    return parent::render($name, $this->getFormattedLength($value), $attributes, $errors);
  }

  public function getFormattedLength($length=0) {
    $hours = (int) ($length / 3600);
    $minutes = (int) ($length % 3600 / 60);
    $seconds = (int) ($length % 60);

    if($seconds < 10)
      $seconds = "0".$seconds;

    if($hours > 0) {
      if($minutes < 10)
        $minutes = "0".$minutes;
      return $hours.":".$minutes.":".$seconds;
    } else {
      return $minutes.":".$seconds;
    }
  }
}

Fix warnings in widget form

Fix warnings in widget form


<?php
namespace Fathomminds\Rest;

use Fathomminds\Rest\Contracts\ISchema;
use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory;
use Fathomminds\Rest\Exceptions\RestException;

abstract class Schema implements ISchema
{
    public function __construct($object = null)
    {
        if ($object === null) {
            return;
        }
        if (gettype($object) !== 'object') {
            throw new RestException('Schema constructor expects object or null as parameter', [
                'parameter' => $object,
            ]);
        }
        foreach (get_object_vars($object) as $name => $value) {
            $this->{$name} = $value;
        }
    }

    public function __get($name)
    {
        if (!isset($this->{$name})) {
            throw new RestException() {
                'Trying to access undefined property ' . $name,
                []
            }
        }
    }

    abstract public function schema();
}

<?php
namespace Fathomminds\Rest;

use Fathomminds\Rest\Contracts\ISchema;
use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory;
use Fathomminds\Rest\Exceptions\RestException;

abstract class Schema implements ISchema
{
    public function __construct($object = null)
    {
        if ($object === null) {
            return;
        }
        if (gettype($object) !== 'object') {
            throw new RestException('Schema constructor expects object or null as parameter', [
                'parameter' => $object,
            ]);
        }
        foreach (get_object_vars($object) as $name => $value) {
            $this->{$name} = $value;
        }
    }

    public function __get($name)
    {
        if (!isset($this->{$name})) {
            throw new RestException(
                'Trying to access undefined property ' . $name,
                []
            );
        }
    }

    abstract public function schema();
}

Throw exception when trying to access undefined property


Top 10

Top 50

Top 100

	<?php

			include 'includes/sqllogin.php';

			$result = mysqli_query($con,"SELECT * FROM  `Top Player` ORDER BY Distance DESC LIMIT 10");

			echo "

					Rank
					Name
					Distance

";

				while($row = mysqli_fetch_array($result))
				{
					$rank = 1;
					echo "
";
					echo "" . $rank++ . "	";
					echo "" . $row['PlayerName'] . "	";
					echo "" . $row['Distance'] . "	";
					echo "
";
				}
			echo "
";

			mysqli_close($con);
	?>

Top 10

Top 50

Top 100

	<?php
	$rank = 1;
			include 'includes/sqllogin.php';

			$result = mysqli_query($con,"SELECT * FROM  `Top Player` ORDER BY Distance DESC LIMIT 10");

			echo "

					Rank
					Name
					Distance

";

				while($row = mysqli_fetch_array($result))
				{

					echo "
";
					echo "" . $rank++ . "	";
					echo "" . $row['PlayerName'] . "	";
					echo "" . $row['Distance'] . "	";
					echo "
";
				}
			echo "
";

			mysqli_close($con);
	?>

TEST moving rank outside loop

TEST moving rank outside loop


<?php
namespace core\site\models;
require_once __DIR__.'/../../common/BaseModel.php';

use \core\common\BaseModel;

class PostModel extends BaseModel
{
    public function getListOfPosts()
    {
        $st = self::getConnection()->prepare(
            'SELECT * FROM posts'
        );

        $st->execute();
        return $st->fetchAll(\PDO::FETCH_CLASS);
    }
}

<?php
namespace core\site\models;
require_once __DIR__.'/../../common/BaseModel.php';

use \core\common\BaseModel;

class PostModel extends BaseModel
{
    public function getListOfPosts()
    {
        $st = self::getConnection()->prepare(
            'SELECT id, teaser, count_comments, title FROM posts'
        );

        $st->execute();
        return $st->fetchAll(\PDO::FETCH_CLASS);
    }
}

Change type geting posts info

Change type geting posts info


<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\CodeToken;
use Phug\Lexer\Token\TextToken;

class CodeScanner implements ScannerInterface
{
    public function scan(State $state)
    {
        $reader = $state->getReader();

        if (!$reader->peekChar('-')) {
            return;
        }

        /** @var CodeToken $token */
        $token = $state->createToken(CodeToken::class);

        $reader->consume();

        //Single-line code
        foreach ($state->scan(TextScanner::class) as $textToken) {
            //Trim the text as expressions usually would
            yield $state->endToken($token);

            if ($textToken instanceof TextToken) {
                $textToken->setValue(trim($textToken->getValue()));
                yield $textToken;
            }

            return;
        }

        //Multi-line code
        $token->setIsBlock(true);
        yield $state->endToken($token);

        foreach ($state->scan(MultilineScanner::class) as $token) {
            yield $token;
        }
    }
}

<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\CodeToken;
use Phug\Lexer\Token\TextToken;

class CodeScanner implements ScannerInterface
{
    public function scan(State $state)
    {
        $reader = $state->getReader();

        if (!$reader->match('-[ \t]*')) {
            return;
        }

        /** @var CodeToken $token */
        $token = $state->createToken(CodeToken::class);

        $reader->consume();

        //Single-line code
        foreach ($state->scan(TextScanner::class) as $textToken) {
            //Trim the text as expressions usually would
            yield $state->endToken($token);

            if ($textToken instanceof TextToken) {
                $textToken->setValue(trim($textToken->getValue()));
                yield $textToken;
            }

            return;
        }

        //Multi-line code
        $token->setIsBlock(true);
        yield $state->endToken($token);

        foreach ($state->scan(MultilineScanner::class) as $token) {
            yield $token;
        }
    }
}

Allow whitespace after multiline code open dash


<?php
namespace Anavel\Crud\View\Composers;

use Anavel\Crud\Contracts\Abstractor\ModelFactory as ModelAbstractorFactory;
use Route;

class SidebarComposer
{
    protected $modelFactory;

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

    public function compose($view)
    {
        $models = config('anavel-crud.models');

        $items = [];

        foreach ($models as $modelName => $model) {
            $modelAbstractor = $this->modelFactory->getByName($modelName);

            $isActive = false;
            if (Route::current()->getParameter('model') === $modelAbstractor->getSlug()) {
                $isActive = true;
            }

            $items[] = [
                'route' => route('anavel-crud.model.index', $modelAbstractor->getSlug()),
                'name' => $modelAbstractor->getName(),
                'isActive' => $isActive
            ];
        }

        $view->with([
            'items' => $items
        ]);
    }
}

<?php
namespace Anavel\Crud\View\Composers;

use Anavel\Crud\Contracts\Abstractor\ModelFactory as ModelAbstractorFactory;
use Route;
use Gate;

class SidebarComposer
{
    protected $modelFactory;

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

    public function compose($view)
    {
        $models = config('anavel-crud.models');

        $items = [];

        foreach ($models as $modelName => $model) {
            $modelAbstractor = $this->modelFactory->getByName($modelName);

            if (array_key_exists('authorize', $config = $modelAbstractor->getConfig()) && $config['authorize'] === true) {
                if (Gate::denies('adminIndex', $modelAbstractor->getInstance())) {
                    continue;
                }
            }

            $isActive = false;
            if (Route::current()->getParameter('model') === $modelAbstractor->getSlug()) {
                $isActive = true;
            }

            $items[] = [
                'route' => route('anavel-crud.model.index', $modelAbstractor->getSlug()),
                'name' => $modelAbstractor->getName(),
                'isActive' => $isActive
            ];
        }

        $view->with([
            'items' => $items
        ]);
    }
}

Hide actions not allowed from menu

Hide actions not allowed from menu


<?php $this->pageTitle = Yii::app()->name . '- Further Steps'; ?>

<?php echo CHtml::encode(Yii::app()->name); ?> - Further Steps

Success! The database has been set up and Metadata Games has been configured.

Some things are however left to to do:

All links below will open in a new tab or window to allow you to return to this list.

<a href="<?php echo Yii::app()->baseUrl; ?>/index.php/user/login" target="_blank">Login gain access to the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin" target="_blank">admin tool.

Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/plugins" target="_blank">plugin tool

<a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/imageSet" target="_blank">Create image sets and <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/import" target="_blank">import images

Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/games" target="_blank">games tool and activate the ones you want to make use of

Goto the <a href="<?php echo Yii::app()->baseUrl; ?>" target="_blank">Arcade and play!

<?php $this->pageTitle = Yii::app()->name . '- Further Steps'; ?>

<?php echo CHtml::encode(Yii::app()->name); ?> - Further Steps

Success! The database has been set up and Metadata Games has been installed.

Now to configure your install of Metadata Games:

All links below will open in a new tab or window to allow you to return to this list.

<a href="<?php echo Yii::app()->baseUrl; ?>/index.php/user/login" target="_blank">Login to gain access to the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin" target="_blank">admin tool.

Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/plugins" target="_blank">plugin tool.

<a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/imageSet" target="_blank">Create image sets and <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/import" target="_blank">import images.

Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/games" target="_blank">games tool and activate the ones you want to use.

Go to the <a href="<?php echo Yii::app()->baseUrl; ?>" target="_blank">Arcade and play!

Edit text for installer page

Edit text for installer page


<?php namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Contact;
use App\Business;
use Session;
use Input;

class ContactFormRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		# $business = Business::findOrFail( $this->business );

		if (! \Auth::user()->isOwner($this->business) ) return false;

		return $this->contact === null || $this->contact->isSuscribedTo($this->business);
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		$rules = [	'firstname' => 'required|min:3',
					'lastname' => 'required|min:3',
					'gender' => 'required|max:1',
					'mobile' => 'phone',
					'mobile_country' => 'required_with:mobile|max:2' /* FIXME: LENGHT MUST BE EXACT 2 */
				];

		switch ($this->method())
		{
			case 'PATCH':
			case 'PUT':
			case 'POST':
				return $rules;
				break;
			default:
				return [];
				break;
		}
	}
}

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Contact;
use App\Business;
use Session;
use Input;

class ContactFormRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		if (! \Auth::user()->isOwner($this->business) ) return false;

		return $this->contact === null || $this->contact->isSuscribedTo($this->business);
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		$rules = [	'firstname' => 'required|min:3',
					'lastname' => 'required|min:3',
					'gender' => 'required|max:1',
					'mobile' => 'phone',
					'mobile_country' => 'required_with:mobile|size:2' /* FIXME: LENGHT MUST BE EXACT 2 */
				];

		switch ($this->method())
		{
			case 'PATCH':
			case 'PUT':
			case 'POST':
				return $rules;
				break;
			default:
				return [];
				break;
		}
	}
}

Fix country ISO code (2) validation rule to match exactly 2 chars long


<?php

namespace RKD\BanklinkTests;

/**
 * Test suite for LHV banklink.
 *
 * @author  Rene Korss <rene.korss@gmail.com>
 */
class PocopayTest extends SEBTest
{
    protected $bankClass = "RKD\Banklink\Pocopay";

    protected $requestUrl = 'https://my.pocopay.com/banklink';
    protected $testRequestUrl = 'http://localhost:8080/banklink/seb-common';
}

<?php

namespace RKD\BanklinkTests;

/**
 * Test suite for LHV banklink.
 *
 * @author  Rene Korss <rene.korss@gmail.com>
 */
class PocopayTest extends SEBTest
{
    protected $bankClass = "RKD\Banklink\Pocopay";

    protected $requestUrl = 'https://my.pocopay.com/banklink';
    protected $testRequestUrl = 'https://alpha.elementare.eu/banklink';
}

Fix Pocopay test against test url

Fix Pocopay test against test url


<?php

namespace Jasny\FormBuilder;

/**
 * Representation of an HTML <fieldset>.
 *
 * @option legend  <legend> of the fieldset
 */
class Fieldset extends Group
{
    /**
     * @var string
     */
    protected $tagname = 'fieldset';

    /**
     * Class constructor.
     *
     * @param array  $options  Element options
     * @param array  $attr     HTML attributes
     */
    public function __construct(array $options=[], array $attr=[])
    {
        parent::__construct($options, $attr);
    }

    /**
     * Set the legend of the fieldset.
     *
     * @param string $legend
     * @return Boostrap\Fieldset  $this
     */
    public function setLegend($legend)
    {
        $this->legend = $legend;
        return $this;
    }

    /**
     * Get the legend of the fieldset.
     *
     * @return string
     */
    public function getLegend()
    {
        return $this->legend;
    }

    /**
     * Render the fieldset to HTML.
     *
     * @return string
     */
    public function open()
    {
        $html = "<fieldset {$this->attr}>";
        if (isset($this->legend)) $html .= "\n<legend>" . $this->legend . "</legend>";

        return $html;
    }
}

<?php

namespace Jasny\FormBuilder;

/**
 * Representation of an HTML <fieldset>.
 *
 * @option legend  <legend> of the fieldset
 */
class Fieldset extends Group
{
    /**
     * @var string
     */
    protected $tagname = 'fieldset';

    /**
     * Class constructor.
     *
     * @param array  $options  Element options
     * @param array  $attr     HTML attributes
     */
    public function __construct(array $options=[], array $attr=[])
    {
        parent::__construct($options, $attr);
    }

    /**
     * Set the legend of the fieldset.
     *
     * @param string $legend
     * @return Boostrap\Fieldset  $this
     */
    public function setLegend($legend)
    {
        $this->setOption('legend', $legend);
        return $this;
    }

    /**
     * Get the legend of the fieldset.
     *
     * @return string
     */
    public function getLegend()
    {
        return $this->getOption('legend');
    }

    /**
     * Render the fieldset to HTML.
     *
     * @return string
     */
    public function open()
    {
        $html = "<fieldset {$this->attr}>";
        if ($this->getLegend()) $html .= "\n<legend>" . $this->getLegend() . "</legend>";

        return $html;
    }
}

Fix displaying legend for fieldset

Fix displaying legend for fieldset


<?php namespace Modules\Menu\Tests;

class MenuRepositoryTest extends BaseMenuTest
{
    /** @test */
    public function it_creates_menu()
    {
        $menu = $this->createMenu('main', 'Main Menu');

        $this->assertEquals(1, $this->menu->find($menu->id)->count());
        $this->assertEquals($menu->name, $this->menu->find($menu->id)->name);
    }
}

<?php namespace Modules\Menu\Tests;

class MenuRepositoryTest extends BaseMenuTest
{
    /** @test */
    public function it_creates_menu()
    {
        $menu = $this->createMenu('main', 'Main Menu');

        $this->assertEquals(1, $this->menu->find($menu->id)->count());
        $this->assertEquals($menu->name, $this->menu->find($menu->id)->name);
    }

    public function it_should_create_root_item_when_creating_new_menu()
    {
        $menu = $this->createMenu('main', 'Main Menu');

        $items = $this->menuItem->allRootsForMenu($menu->id);
    }
}

Prepare a new test for checking root item creation


<?php

namespace Desk\Response\Customers;

class ListCustomerEmails implements \ArrayAccess, \Iterator
{
    protected $data;
    private $position = 0;

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

    public function getAddresses()
    {
        return array_map(function ($item) {
            return $item['value'];
        }, $this->data);
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->data[$offset]) ? (object) $this->data[$offset] : null;
    }

    public function rewind() {
        $this->position = 0;
    }

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

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

    public function next() {
        ++$this->position;
    }

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

<?php

namespace Desk\Response\Customers;

class ListCustomerEmails implements \ArrayAccess, \Iterator
{
    protected $data;
    private $position = 0;

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

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

    public function getAddresses()
    {
        return array_map(function ($item) {
            return $item['value'];
        }, $this->data);
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->data[$offset]) ? (object) $this->data[$offset] : null;
    }

    public function rewind() {
        $this->position = 0;
    }

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

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

    public function next() {
        ++$this->position;
    }

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

Add data getter to listcustomeremails

Add data getter to listcustomeremails


<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

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

		$this->registerFormBuilder();
	}

	/**
	 * Register the HTML builder instance.
	 *
	 * @return void
	 */
	protected function registerHtmlBuilder()
	{
		$this->app->alias('html', 'Illuminate\Html\HtmlBuilder');
		$this->app->bindShared('html', function($app)
		{
			return new HtmlBuilder($app['url']);
		});
	}

	/**
	 * Register the form builder instance.
	 *
	 * @return void
	 */
	protected function registerFormBuilder()
	{
		$this->app->alias('form', 'Illuminate\Html\FormBuilder');
		$this->app->bindShared('form', function($app)
		{
			$form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());

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

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

}

<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

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

		$this->registerFormBuilder();

		$this->app->alias('html', 'Illuminate\Html\HtmlBuilder');
		$this->app->alias('form', 'Illuminate\Html\FormBuilder');
	}

	/**
	 * Register the HTML builder instance.
	 *
	 * @return void
	 */
	protected function registerHtmlBuilder()
	{
		$this->app->bindShared('html', function($app)
		{
			return new HtmlBuilder($app['url']);
		});
	}

	/**
	 * Register the form builder instance.
	 *
	 * @return void
	 */
	protected function registerFormBuilder()
	{
		$this->app->bindShared('form', function($app)
		{
			$form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());

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

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

}

Move alias registration to the `register` method


<?php

namespace Rogue\Http\Requests\Three;

use Rogue\Http\Requests\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'status' => 'in:pending,accepted,rejected',
            'caption' => 'string|max:140',
            'quantity' => 'int',
        ];
    }
}

<?php

namespace Rogue\Http\Requests\Three;

use Rogue\Http\Requests\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'campaign_id' => 'required',
            'campaign_run_id' => 'required_with:campaign_id|integer',
            'why_participated' => 'nullable|string',
            'caption' => 'required|nullable|string|max:140',
            'quantity' => 'required|nullable|integer',
            'file' => 'image|dimensions:min_width=400,min_height=400',
        ];
    }
}

Add missing validation rules for v3 posts.

Users should *not* be able to specify whether their post is approved, and we should enforce some restrictions on other fields.


<?php
require("./creds.php");

// Connect to Database
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());

// Get Latitude/Longitude data from MySQL
$geoqry = mysql_query("SELECT kff1006, kff1005
                      FROM $db_table
                      ORDER BY time DESC
                      LIMIT 5000") or die(mysql_error());
$latlong = array();
while($geo = mysql_fetch_array($geoqry)) {
    if (($geo["0"] != 0) && ($geo["1"] != 0)) {
        $latlong[] = array("latitude" => $geo["0"], "longitude" => $geo["1"]);
    }
}

// Create array of Latitude/Longitude strings in Google Maps JavaScript format
$mapdata = array();
foreach($latlong as $d) {
    $mapdata[] = "new google.maps.LatLng(" . $d['latitude'] . ", " . $d['longitude'] . ")";
}
$imapdata = implode(",\n                    ", $mapdata);

// Centering location for the map is the most recent location
$centerlat = $latlong[0]["latitude"];
$centerlong = $latlong[0]["longitude"];
?>

<?php
require("./creds.php");

// Connect to Database
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());

// Get Latitude/Longitude data from MySQL
$geoqry = mysql_query("SELECT kff1006, kff1005
                      FROM $db_table
                      ORDER BY time DESC
                      LIMIT 5000") or die(mysql_error());
$latlong = array();
while($geo = mysql_fetch_array($geoqry)) {
    if (($geo["0"] != 0) && ($geo["1"] != 0)) {
        $latlong[] = array("latitude" => $geo["0"], "longitude" => $geo["1"]);
    }
}

// Create array of Latitude/Longitude strings in Google Maps JavaScript format
$mapdata = array();
foreach($latlong as $d) {
    $mapdata[] = "new google.maps.LatLng(" . $d['latitude'] . ", " . $d['longitude'] . ")";
}
$imapdata = implode(",\n                    ", $mapdata);

// Centering location for the map is the most recent location
if (isset($latlong[0])) {
    $centerlat = $latlong[0]["latitude"];
    $centerlong = $latlong[0]["longitude"];
}
else {
    $centerlat = 38.5;
    $centerlong = -98;
}
?>

Set default location when no GPS data exists.


<?php

use CachetHQ\Cachet\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

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

        $users = [
            [
                "username" => "admin",
                "password" => "admin",
                "email"    => "admin@example.com",
                "level"    => "1",
            ],
            [
                "username" => "user",
                "password" => "user",
                "email"    => "user@example.com"
            ],
        ];

        foreach ($users as $user) {
            User::create($user);
        }
    }
}

<?php

use CachetHQ\Cachet\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

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

        $users = [
            [
                "username" => "test",
                "password" => "test123",
                "email"    => "test@test.com",
            ]
        ];

        foreach ($users as $user) {
            User::create($user);
        }
    }
}

Change the user seeder for the test account


<?php

class Zenc_EmailLogger_RestController extends Zenc_EmailLogger_Controller_Restful
{
    protected $_methods = array('get');

    public function getListAction()
    {
        $this->render(array(
            'count' => $this->_getCollection()->count(),
            'items' => $this->_getCollection()->walk(function($item) {
                return array(
                    'id' => $item->getId(),
                    'subject' => $item->getSubject(),
                    'created_at' => $item->getCreatedAt(),
                );
            })
        ));
    }

    public function getReadAction()
    {
        $id = $this->getRequest()->get('id');
        if ($id == 'last') {
            $item = $this->_getCollection()->getLastItem();
        } else {
            $item = Mage::getModel('zenc_emaillogger/log')->load($id);
        }

        $this->render($item->getData());
    }

    private function _getCollection()
    {
        return Mage::getModel('zenc_emaillogger/log')->getCollection();
    }
}

<?php

class Zenc_EmailLogger_RestController extends Zenc_EmailLogger_Controller_Restful
{
    protected $_methods = array('get');

    public function getListAction()
    {
        $this->render(array(
            'count' => $this->_getCollection()->count(),
            'items' => $this->_getCollection()->walk(function($item) {
                return array(
                    'id' => $item->getId(),
                    'subject' => $item->getSubject(),
                    'created_at' => $item->getCreatedAt(),
                );
            })
        ));
    }

    public function getReadAction()
    {
        $id = $this->getRequest()->get('id');
        if ($id == 'last') {
            $id = $this->_getCollection()->getLastItem()->getId();
        }

        $item = Mage::getModel('zenc_emaillogger/log')->load($id);

        $this->render($item->getData());
    }

    private function _getCollection()
    {
        return Mage::getModel('zenc_emaillogger/log')->getCollection();
    }
}

Fix serialized fields not showing for latest item


<?php

namespace Encore\Admin\Grid\Displayers;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\Storage;

class Image extends AbstractDisplayer
{
    public function display($server = '', $width = 200, $height = 200)
    {
        if ($this->value instanceof Arrayable) {
            $this->value = $this->value->toArray();
        }

        return collect((array) $this->value)->filter()->map(function ($path) use ($server, $width, $height) {
            if (url()->isValidUrl($path)) {
                $src = $path;
            } elseif ($server) {
                $src = rtrim($server, '/').'/'.ltrim($path, '/');
            } else {
                $src = Storage::disk(config('admin.upload.disk'))->url($path);
            }

            return "<img src='$src' style='max-width:{$width}px;max-height:{$height}px' class='img img-thumbnail' />";
        })->implode(' ');
    }
}

<?php

namespace Encore\Admin\Grid\Displayers;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\Storage;
use Encore\Admin\Admin;

class Image extends AbstractDisplayer
{
    public function display($server = '', $width = 200, $height = 200, $expand = false)
    {
        if ($this->value instanceof Arrayable) {
            $this->value = $this->value->toArray();
        }

        return collect((array) $this->value)->filter()->map(function ($path) use ($server, $width, $height, $expand) {
            if (url()->isValidUrl($path)) {
                $src = $path;
            } elseif ($server) {
                $src = $server.$path;
            } else {
                $src = Storage::disk(config('admin.upload.disk'))->url($path);
            }

            if ($expand) Admin::script("$('img.img-expand').on('click', function() { $('.img-expanded').attr('src', $(this).attr('src')); $('#img-expand-" . $this->getKey() . "').modal('show'); });");
            return ($expand?'
getKey() . '" tabindex="-1" role="dialog" aria-labelledby="img-expand" aria-hidden="true">

':'') . "";
        })->implode(' ');
    }
}

Expand function for grid->image column

Expand function for grid->image column

Last parameter for expand feature
$grid->picture()->image('', 40, 40, true);


<?php

namespace Aerys;

interface Bootable {
    /** May return an instance of Middleware and/or callable to be used instead of the class implementing Bootable (which may also implement Middleware and/or be callable) */
    function boot(Server $server, Logger $logger);
}

<?php

namespace Aerys;

interface Bootable {
    /**
     * @return Middleware|callable|null to be used instead of the class implementing Bootable (which may also implement Middleware and/or be callable)
     */
    function boot(Server $server, Logger $logger);
}

Use a proper phpdoc syntax

Use a proper phpdoc syntax


<?php

namespace ChaseH\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

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

<?php

namespace ChaseH\Providers;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

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

Fix for column key too long for Aurora.

Fix for column key too long for Aurora.


<?php declare(strict_types=1);

namespace WyriMaps\XHeaders;

final class Horde
{
    public static function headers()
    {
        return [
            'X-Horde' => 'For the Horde!',
            'X-Orc' => 'Lok-tar ogar!',
            'X-Alliance' => 'Puny Alliance',
        ];
    }
}

<?php declare(strict_types=1);

namespace WyriMaps\XHeaders;

final class Horde
{
    public static function headers()
    {
        return [
            'X-Horde' => 'For the Horde!',
            'X-Orc' => 'Lok-tar ogar!',
            'X-Alliance' => 'Puny Alliance',
            'X-Thrall' => 'For Doomhammer!',
        ];
    }
}

Add a new quote by thrall

Add a new quote by thrall


<?php
namespace Axstrad\DoctrineExtensions\Sluggable\Sluggable;

use Gedmo\Sluggable\Sluggable as BaseInterface;

/**
 * Axstrad\DoctrineExtensions\Sluggable\Sluggable\Sluggable
 */
interface Sluggable extends BaseInterface
{
    /**
     * @return string
     */
    public function getSlug();
}

<?php
namespace Axstrad\DoctrineExtensions\Sluggable;

use Gedmo\Sluggable\Sluggable as BaseInterface;

/**
 * Axstrad\DoctrineExtensions\Sluggable\Sluggable
 */
interface Sluggable extends BaseInterface
{
    /**
     * @return string
     */
    public function getSlug();
}

Refactor the repository's ORM entities

Refactor the repository's ORM entities


<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Acd\core\tests;

/**
 * Description of RequestTest
 *
 * @author Luca
 */
class RequestTest extends \PHPUnit_Framework_TestCase
{

  private $header;

  public function setUp() {
         $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'it';
  }

  public function tearDown() {
    unset($_SERVER['HTTP_ACCEPT_LANGUAGE']);
    parent::tearDown();
  }

     public function testGetRequestHeaders()
     {

        $this->header = $this->request_headers();

     $this->assertEquals($this->header, ['Accept-Language' => 'it']);
   }

     public function request_headers()
     {
    if(function_exists("apache_request_headers"))
    {
        if($headers = apache_request_headers())
        {
            return $headers;
        }
    }

    $headers = array();
    foreach(array_keys($_SERVER) as $skey)
    {
        if(substr($skey, 0, 5) == "HTTP_")
        {
            $headername = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))));
            $headers[$headername] = $_SERVER[$skey];
        }
    }
    return $headers;
}

}

<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Acd\core\tests;

/**
 * Description of RequestTest
 *
 * @author Luca
 */
class RequestTest extends \PHPUnit_Framework_TestCase
{

  private $header;

  public function setUp() {
         $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'it';
  }

  public function tearDown() {
    unset($_SERVER['HTTP_ACCEPT_LANGUAGE']);
    parent::tearDown();
  }

     public function testGetRequestHeaders()
     {

        $this->header = $this->request_headers();

     $this->assertEquals($this->header, ['Accept-Language' => 'it']);
   }

}

Remove function from request test

Remove function from request test


<?php

/*
 * This file is part of Twig.
 *
 * (c) 2010 Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class Twig_Node_Expression_Binary_Power extends Twig_Node_Expression_Binary
{
    public function compile(Twig_Compiler $compiler)
    {
        if (PHP_VERSION_ID >= 50600) {
            return parent::compile($compiler);
        }

        $compiler
            ->raw('pow(')
            ->subcompile($this->getNode('left'))
            ->raw(', ')
            ->subcompile($this->getNode('right'))
            ->raw(')')
        ;
    }

    public function operator(Twig_Compiler $compiler)
    {
        return $compiler->raw('**');
    }
}

<?php

/*
 * This file is part of Twig.
 *
 * (c) 2010 Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class Twig_Node_Expression_Binary_Power extends Twig_Node_Expression_Binary
{
    public function operator(Twig_Compiler $compiler)
    {
        return $compiler->raw('**');
    }
}

Use ** operator over function pow()

Use ** operator over function pow()


@extends('lanager-core::layouts.default')
@section('content')

{{{ $title }}}

	{{ Table::open() }}
	@foreach ($users as $user)
		<?php
		// Get steam state for user if one exists
		$steamState = $user->steamStates()->latest();
		$status = (count($user->steamStates)) ? $steamState->getStatus() : '';
		$appLink = (!empty($steamState->app_id)) ? link_to(SteamBrowserProtocol::viewAppInStore($steamState->app_id), $steamState->app_name) : '';
		$connectLink = (!empty($steamState->server_ip)) ? link_to(SteamBrowserProtocol::connectToServer($steamState->server_ip), $steamState->server_ip) : '';

		$tableBody[] = array(
			'user'		=> 'avatar.'"> '.link_to_route('user.show', $user->username, $user->id),
			'status'	=> $status,
			'app'		=> $appLink,
			'server'	=> $connectLink,
			);
		?>
	@endforeach
	{{ Table::body($tableBody) }}
	{{ Table::close() }}
	{{ $users->links() }}
@endsection

@extends('lanager-core::layouts.default')
@section('content')

{{{ $title }}}

	@if(count($users))
		{{ Table::open() }}
		@foreach ($users as $user)
			<?php
			// Get steam state for user if one exists
			$steamState = $user->steamStates()->latest();
			$status = (count($user->steamStates)) ? $steamState->getStatus() : '';
			$appLink = (!empty($steamState->app_id)) ? link_to(SteamBrowserProtocol::viewAppInStore($steamState->app_id), $steamState->app_name) : '';
			$connectLink = (!empty($steamState->server_ip)) ? link_to(SteamBrowserProtocol::connectToServer($steamState->server_ip), $steamState->server_ip) : '';

			$tableBody[] = array(
				'user'		=> 'avatar.'"> '.link_to_route('user.show', $user->username, $user->id),
				'status'	=> $status,
				'app'		=> $appLink,
				'server'	=> $connectLink,
				);
			?>
		@endforeach
		{{ Table::body($tableBody) }}
		{{ Table::close() }}
		{{ $users->links() }}
	@else
		No users found!
	@endif
@endsection

Check if there are any users before making list


<?php

namespace React\Whois;

use React\Async\Util as Async;
use React\Curry\Util as Curry;
use React\Dns\Resolver\Resolver;

class Client
{
    private $resolver;
    private $connFactory;

    public function __construct(Resolver $resolver, $connFactory)
    {
        $this->resolver = $resolver;
        $this->connFactory = $connFactory;
    }

    public function query($domain, $callback)
    {
        Async::waterfall(
            array(
                Curry::bind(array($this, 'init'), $domain),
                array($this, 'resolveWhoisServer'),
                Curry::bind(array($this, 'queryWhoisServer'), $domain),
            ),
            $callback
        );
    }

    public function init($domain, $callback)
    {
        $callback($domain);
    }

    public function resolveWhoisServer($domain, $callback)
    {
        $tld = substr(strrchr($domain, '.'), 1);
        $target = $tld.'.whois-servers.net';

        $this->resolver->resolve($target, $callback);
    }

    public function queryWhoisServer($domain, $ip, $callback)
    {
        $result = '';

        $conn = call_user_func($this->connFactory, $ip);
        $conn->write("$domain\r\n");
        $conn->on('data', function ($data) use (&$result) {
            $result .= $data;
        });
        $conn->on('close', function () use (&$result, $callback) {
            $result = str_replace("\r\n", "\n", $result);
            $callback($result);
        });
    }
}

<?php

namespace React\Whois;

use React\Async\Util as Async;
use React\Curry\Util as Curry;
use React\Dns\Resolver\Resolver;

class Client
{
    private $resolver;
    private $connFactory;

    public function __construct(Resolver $resolver, $connFactory)
    {
        $this->resolver = $resolver;
        $this->connFactory = $connFactory;
    }

    public function query($domain, $callback)
    {
        Async::waterfall(
            array(
                Curry::bind(array($this, 'resolveWhoisServer'), $domain),
                Curry::bind(array($this, 'queryWhoisServer'), $domain),
            ),
            $callback
        );
    }

    public function resolveWhoisServer($domain, $callback)
    {
        $tld = substr(strrchr($domain, '.'), 1);
        $target = $tld.'.whois-servers.net';

        $this->resolver->resolve($target, $callback);
    }

    public function queryWhoisServer($domain, $ip, $callback)
    {
        $result = '';

        $conn = call_user_func($this->connFactory, $ip);
        $conn->write("$domain\r\n");
        $conn->on('data', function ($data) use (&$result) {
            $result .= $data;
        });
        $conn->on('close', function () use (&$result, $callback) {
            $result = str_replace("\r\n", "\n", $result);
            $callback($result);
        });
    }
}

Simplify client, remove unneeded init method


<?php # -*- coding: utf-8 -*-

if ( is_admin() ) {
	add_action( 'inpsyde_mlp_loaded', 'mlp_feature_user_backend_language', 0 );
}

/**
 * @param Inpsyde_Property_List_Interface $data Plugin data.
 *
 * @return void
 */
function mlp_feature_user_backend_language( Inpsyde_Property_List_Interface $data ) {

	$user_lang = new Mlp_User_Backend_Language( $data->get( 'module_manager' ) );
	$user_lang->setup();
}

<?php # -*- coding: utf-8 -*-

if ( is_admin() ) {
	global $wp_version;

	if ( version_compare( $wp_version, '4.7', '<' ) ) {
		add_action( 'inpsyde_mlp_loaded', 'mlp_feature_user_backend_language', 0 );
	}
}

/**
 * @param Inpsyde_Property_List_Interface $data Plugin data.
 *
 * @return void
 */
function mlp_feature_user_backend_language( Inpsyde_Property_List_Interface $data ) {

	$user_lang = new Mlp_User_Backend_Language( $data->get( 'module_manager' ) );
	$user_lang->setup();
}

Disable User Backend Language feature for WordPress 4.7+.


<?php
/**
 * This file is part of the ramsey/uuid library
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
 * @license http://opensource.org/licenses/MIT MIT
 * @link https://benramsey.com/projects/ramsey-uuid/ Documentation
 * @link https://packagist.org/packages/ramsey/uuid Packagist
 * @link https://github.com/ramsey/uuid GitHub
 */

namespace Ramsey\Uuid\Generator;

use RandomLib\Generator;
use RandomLib\Factory;

class RandomLibAdapter implements RandomGeneratorInterface
{
    private $generator;

    public function __construct(Generator $generator = null)
    {
        $this->generator = $generator;

        if ($this->generator == null) {
            $factory = new Factory();

            $this->generator = $factory->getLowStrengthGenerator();
        }
    }

    public function generate($length)
    {
        return $this->generator->generate($length);
    }
}

<?php
/**
 * This file is part of the ramsey/uuid library
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
 * @license http://opensource.org/licenses/MIT MIT
 * @link https://benramsey.com/projects/ramsey-uuid/ Documentation
 * @link https://packagist.org/packages/ramsey/uuid Packagist
 * @link https://github.com/ramsey/uuid GitHub
 */

namespace Ramsey\Uuid\Generator;

use RandomLib\Generator;
use RandomLib\Factory;

class RandomLibAdapter implements RandomGeneratorInterface
{
    private $generator;

    public function __construct(Generator $generator = null)
    {
        $this->generator = $generator;

        if ($this->generator == null) {
            $factory = new Factory();

            $this->generator = $factory->getMediumStrengthGenerator();
        }
    }

    public function generate($length)
    {
        return $this->generator->generate($length);
    }
}

Use a medium strength generator for ircmaxell/random-lib

As discussed in https://github.com/ramsey/uuid/issues/56


<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace ComPHPPuebla\Fixtures\Connections;

use Doctrine\DBAL\Connection as DbConnection;

class DBALConnection implements Connection
{
    /** @var DbConnection */
    protected $connection;

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

    public function insert(string $table, array $row): int
    {
        $this->connection->insert($table, $this->quoteIdentifiers($row));
        return $this->connection->lastInsertId();
    }

    private function quoteIdentifiers(array $row): array
    {
        $quoted = [];
        foreach ($row as $column => $value) {
            $quoted[$this->connection->quoteIdentifier($column)] = $value;
        }
        return $quoted;
    }

    public function getPrimaryKeyOf(string $table): string
    {
        $schema = $this->connection->getSchemaManager();
        return $schema->listTableDetails($table)->getPrimaryKeyColumns()[0];
    }
}

<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace ComPHPPuebla\Fixtures\Connections;

use Doctrine\DBAL\Connection as DbConnection;

class DBALConnection implements Connection
{
    /** @var DbConnection */
    protected $connection;

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

    public function insert(string $table, array $row): int
    {
        $this->connection->insert($table, $this->quoteIdentifiers($row));
        return $this->connection->lastInsertId();
    }

    private function quoteIdentifiers(array $row): array
    {
        $quoted = [];
        foreach ($row as $column => $value) {
            $quoted[$this->connection->quoteIdentifier($column)] = $value;
        }
        return $quoted;
    }

    public function getPrimaryKeyOf(string $table): string
    {
        $schema = $this->connection->getSchemaManager();
        return $schema->listTableDetails($table)->getPrimaryKeyColumns()[0];
    }

    public function registerPlatformType(string $platformType, string $dbalType)
    {
        $schema = $this->connection->getSchemaManager();
        $schema->getDatabasePlatform()->registerDoctrineTypeMapping($platformType, $dbalType);
    }
}

Add ability to configure a platform-specific type.


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

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

	<div <?php echo bgimage($page->images()->first(), array('class' => 'CoverImage FluidEmbed--3by2 FluidEmbed--large16by9 FluidEmbed--huge2by1')); ?>>

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

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

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

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

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

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

	<div <?php echo bgimage($page->images()->first(), array('class' => 'BgImage FluidEmbed--3by2 FluidEmbed--large16by9 FluidEmbed--huge2by1')); ?>>

		<div style="background-image:url(<?php echo thumb($page->images()->first(), array(), false); ?>);" class="BgImage FluidEmbed--3by2 FluidEmbed--large16by9 FluidEmbed--huge2by1">

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

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

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

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

Add <noscript> fallback to the lazyload background image example…

Work in progress!


<?php
/**
 * Text input field with validation for numeric values.
 *
 * @package forms
 * @subpackage fields-formattedinput
 */
class QuantityField extends NumericField
{

    public function Type()
    {
        return 'quantity numeric text';
    }

    /** PHP Validation **/
    public function validate($validator)
    {
        if ($this->value && !is_int(floatval(trim($this->value)))) {
            $validator->validationError(
                $this->name,
                _t(
                    'NumericField.VALIDATION', "'{value}' is not a valid number, only whole numbers can be accepted for this field",
                    array('value' => $this->value)
                ),
                "validation"
            );
            return false;
        } elseif (!$this->value) {
            $validator->validationError(
                $this->name,
                sprintf(_t('Form.FIELDISREQUIRED', '%s is required'), $this->title),
                "validation"
            );
            return false;
        } else {
            return true;
        }
    }

    public function dataValue()
    {
        return (is_numeric($this->value)) ? $this->value : 0;
    }
}

<?php
/**
 * Text input field with validation for numeric values.
 *
 * @package forms
 * @subpackage fields-formattedinput
 */
class QuantityField extends NumericField
{

    public function Type()
    {
        return 'quantity numeric text';
    }

    /** PHP Validation **/
    public function validate($validator)
    {
        // First check if value is numeric
        if ($this->value && $this->isNumeric()) {
            // Convert to a number to check
            $value = $this->value + 0;

            if(is_int($value)) {
                return true;
            }
        }

        $validator->validationError(
            $this->name,
            _t(
                'Checkout.VALIDATION', '{value} is not a valid number, only whole numbers can be accepted for this field',
                array('value' => $this->value)
            ),
            "validation"
        );
        return false;
    }

    public function dataValue()
    {
        return (is_numeric($this->value)) ? $this->value : 0;
    }
}

Fix validation issues with quantity field


@inject('registry', 'Despark\Cms\Javascript\Contracts\RegistryContract')
<script type="text/javascript">
    if (typeof Despark == 'undefined') {
        Despark = {};
    }
    Despark.js = Despark.js || {};
    Despark.js.registry = {
        'values': {!! json_encode($registry->getRegistry()) !!},
        'get': function (namespace, key) {
            if (typeof this.values[namespace] != 'undefined') {
                if (typeof key != 'undefined') {
                    if (typeof this.values[namespace][key] != 'undefined') {
                        return this.values[namespace][key]
                    }
                    var keys = key.split('.');
                    var found = this.values[namespace];
                    for (var i in keys) {
                        if (typeof found[keys[i]] != 'undefined') {
                            found = found[keys[i]];
                        } else {
                            return null;
                        }
                    }
                    return found;
                } else {
                    return this.values[namespace];
                }
            }
        }
    };
</script>

@inject('registry', 'Despark\Cms\Javascript\Contracts\RegistryContract')
<script type="text/javascript">
    if (typeof Despark == 'undefined') {
        Despark = {};
    }
    Despark.js = Despark.js || {};
    Despark.js.registry = {
        'values': {!! json_encode($registry->getRegistry()) !!},
        'get': function (namespace, key) {
            if (this.values && typeof this.values[namespace] != 'undefined') {
                if (typeof key != 'undefined') {
                    if (typeof this.values[namespace][key] != 'undefined') {
                        return this.values[namespace][key]
                    }
                    var keys = key.split('.');
                    var found = this.values[namespace];
                    for (var i in keys) {
                        if (typeof found[keys[i]] != 'undefined') {
                            found = found[keys[i]];
                        } else {
                            return null;
                        }
                    }
                    return found;
                } else {
                    return this.values[namespace];
                }
            }
        }
    };
</script>

Check if js registry is null

Check if js registry is null