<?php

namespace Caffeinated\Modules\Console;

use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand;
use Illuminate\Support\Str;
use Module;

abstract class GeneratorCommand extends LaravelGeneratorCommand
{
    /**
     * Parse the name and format according to the root namespace.
     *
     * @param string $name
     *
     * @return string
     */
    protected function qualifyClass($name)
    {
        $rootNamespace = config('modules.namespace');

        if (Str::startsWith($name, $rootNamespace)) {
            return $name;
        }

        $name = str_replace('/', '\\', $name);

        return $this->qualifyClass(
            $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
        );
    }

    /**
     * Get the destination class path.
     *
     * @param string $name
     *
     * @return string
     */
    protected function getPath($name)
    {
        $slug = $this->argument('slug');

        // take everything after the module name in the given path (ignoring case)
        $key = array_search(strtolower($slug), explode('\\', strtolower($name)));
        if ($key === false) {
            $newPath = str_replace('\\', '/', $name);
        } else {
            $newPath = implode('/', array_slice(explode('\\', $name), $key + 1));
        }

        return module_path($slug, "$newPath.php");
    }
}

<?php

namespace Caffeinated\Modules\Console;

use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand;
use Illuminate\Support\Str;
use Module;

abstract class GeneratorCommand extends LaravelGeneratorCommand
{
    /**
     * Parse the name and format according to the root namespace.
     *
     * @param string $name
     *
     * @return string
     */
    protected function qualifyClass($name)
    {
        $rootNamespace = config('modules.namespace');

        if (Str::startsWith($name, $rootNamespace)) {
            return $name;
        }

        $name = str_replace('/', '\\', $name);

        return $this->qualifyClass(
            $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
        );
    }

    /**
     * Get the destination class path.
     *
     * @param string $name
     *
     * @return string
     */
    protected function getPath($name)
    {
        $slug = $this->argument('slug');
        $module = Module::where('slug', $slug);

        // take everything after the module name in the given path (ignoring case)
        $key = array_search(strtolower($module['basename']), explode('\\', strtolower($name)));
        if ($key === false) {
            $newPath = str_replace('\\', '/', $name);
        } else {
            $newPath = implode('/', array_slice(explode('\\', $name), $key + 1));
        }

        return module_path($slug, "$newPath.php");
    }
}

Correct path if slug contains "-"

Correct path if slug contains "-"


<?php

namespace OpenDominion\Events;

use OpenDominion\Contracts\Services\Analytics\AnalyticsEvent as EventContract;
use OpenDominion\Services\Analytics\AnalyticsEvent;
use OpenDominion\Services\Analytics\HasAnalyticsEvent;

class UserLoggedInEvent extends AbstractUserEvent implements HasAnalyticsEvent
{
    // todo: activityevent

    /**
     * {@inheritdoc}
     */
    public function getAnalyticsEvent(): EventContract
    {
        // todo: ioc
        return new AnalyticsEvent('user', 'login');
    }
}

<?php

namespace OpenDominion\Events;

use OpenDominion\Contracts\Services\Activity\ActivityEvent as ActivityEventContract;
use OpenDominion\Contracts\Services\Analytics\AnalyticsEvent as EventContract;
use OpenDominion\Services\Activity\ActivityEvent;
use OpenDominion\Services\Activity\HasActivityEvent;
use OpenDominion\Services\Analytics\AnalyticsEvent;
use OpenDominion\Services\Analytics\HasAnalyticsEvent;

class UserLoggedInEvent extends AbstractUserEvent implements HasActivityEvent, HasAnalyticsEvent
{
    /**
     * {@inheritdoc}
     */
    public function getActivityEvent(): ActivityEventContract
    {
        // todo: ioc
        return new ActivityEvent('user.login', ActivityEventContract::STATUS_SUCCESS);
    }

    /**
     * {@inheritdoc}
     */
    public function getAnalyticsEvent(): EventContract
    {
        // todo: ioc
        return new AnalyticsEvent('user', 'login');
    }
}

Add activity event to user logged in event


<?php

namespace Omnipay\Swish\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RequestInterface;

class PurchaseResponse extends AbstractResponse
{
    protected $statusCode;
    protected $response;

    public function __construct(RequestInterface $request, $response, $data, $statusCode)
    {
        parent::__construct($request, $data);
        $this->statusCode = $statusCode;
        $this->response = $response;
    }

    public function isSuccessful()
    {
        return ($this->getCode() == 200 || $this->getCode() == 201);
    }

    public function getTransactionReference()
    {
        if (!empty($location = $this->response->getHeader('location'))) {
            $urlParts = explode('/', $location);
            return end($urlParts);
        }

        return null;
    }

    public function getMessage()
    {
        if (isset($this->data[0]['errorMessage'])) {
            return $this->data[0]['errorMessage'];
        }

        return null;
    }

    public function getCode()
    {
        return $this->statusCode;
    }
}

<?php

namespace Omnipay\Swish\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RequestInterface;

class PurchaseResponse extends AbstractResponse
{
    protected $statusCode;
    protected $response;

    public function __construct(RequestInterface $request, $response, $data, $statusCode)
    {
        parent::__construct($request, $data);
        $this->statusCode = $statusCode;
        $this->response = $response;
    }

    public function isSuccessful()
    {
        return ($this->getCode() == 200 || $this->getCode() == 201);
    }

    public function getTransactionReference()
    {
        $location = $this->response->getHeader('location');
        if (!empty($location)) {
            $urlParts = explode('/', $location);
            return end($urlParts);
        }

        return null;
    }

    public function getMessage()
    {
        if (isset($this->data[0]['errorMessage'])) {
            return $this->data[0]['errorMessage'];
        }

        return null;
    }

    public function getCode()
    {
        return $this->statusCode;
    }
}

Fix tests for PHP < 5.5

Fix tests for PHP < 5.5


<?php
    $strFile = rawurldecode(@$_GET['url']);
	$strFile_array = explode('.' , $strFile);
    $strFileExt = end($strFile_array);

    if($strFileExt == 'jpg' or $strFileExt == 'jpeg') {
        header('Content-Type: image/jpeg');
    } elseif($strFileExt == 'png') {
        header('Content-Type: image/png');
    } elseif($strFileExt == 'gif') {
        header('Content-Type: image/gif');
    } else {
        die('not supported');
    }

    if($strFile != ''){
        $cache_expire = 60*60*24*365;
        header("Pragma: public");
        header("Cache-Control: maxage=". $cache_expire);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_expire).' GMT');
        echo file_get_contents($strFile);
    }

    exit;
?>

<?php
    $strFile = rawurldecode(@$_GET['url']);
	$strFile_array = explode('.' , $strFile);
    $strFileExt = end($strFile_array);

    if($strFileExt == 'jpg' or $strFileExt == 'jpeg') {
        header('Content-Type: image/jpeg');
    } elseif($strFileExt == 'png') {
        header('Content-Type: image/png');
    } elseif($strFileExt == 'gif') {
        header('Content-Type: image/gif');
    } else {
        die('not supported');
    }

    if($strFile != ''){

        $cache_expire = 60*60*24*365;
        header("Pragma: public");
        header("Cache-Control: maxage=". $cache_expire);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_expire).' GMT');

		$im = new Imagick($strFile);
		$im->thumbnailImage(250,250);
        echo $im;
    }

    exit;
?>

Compress images at the proxy

Compress images at the proxy


<?php namespace Orchestra\Auth;

use Orchestra\Authorization\Policy;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Auth\AuthServiceProvider as ServiceProvider;
use Orchestra\Contracts\Authorization\Factory as FactoryContract;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $this->registerPolicyAfterResolvingHandler();
    }

    /**
     * Register the service provider for Auth.
     *
     * @return void
     */
    protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function (Application $app) {
            // Once the authentication service has actually been requested by the developer
            // we will set a variable in the application indicating such. This helps us
            // know that we need to set any queued cookies in the after event later.
            $app['auth.loaded'] = true;

            return new AuthManager($app);
        });

        $this->app->singleton('auth.driver', function (Application $app) {
            return $app->make('auth')->driver();
        });
    }

    /**
     * Register the Policy after resolving handler.
     *
     * @return void
     */
    protected function registerPolicyAfterResolvingHandler()
    {
        $this->app->afterResolving(Policy::class, function (Policy $policy) {
            return $policy->setAuthorization($this->app->make(FactoryContract::class));
        });
    }
}

<?php namespace Orchestra\Auth;

use Orchestra\Authorization\Policy;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Auth\AuthServiceProvider as ServiceProvider;
use Orchestra\Contracts\Authorization\Factory as FactoryContract;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $this->registerPolicyAfterResolvingHandler();
    }

    /**
     * Register the service provider for Auth.
     *
     * @return void
     */
    protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function (Application $app) {
            // Once the authentication service has actually been requested by the developer
            // we will set a variable in the application indicating such. This helps us
            // know that we need to set any queued cookies in the after event later.
            $app['auth.loaded'] = true;

            return new AuthManager($app);
        });

        $this->app->singleton('auth.driver', function (Application $app) {
            return $app->make('auth')->guard();
        });
    }

    /**
     * Register the Policy after resolving handler.
     *
     * @return void
     */
    protected function registerPolicyAfterResolvingHandler()
    {
        $this->app->afterResolving(Policy::class, function (Policy $policy) {
            return $policy->setAuthorization($this->app->make(FactoryContract::class));
        });
    }
}

Use ->guard() instead of ->driver().

Use ->guard() instead of ->driver().

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
/**
 * The template used for displaying page content in page.php
 *
 * @package Flacso
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

		<?php the_title( '
', '
' ); ?>

		<?php the_content(); ?>
		<?php
			wp_link_pages( array(
				'before' => '
' . __( 'Pages:', 'flacso' ),
				'after'  => '
',
			) );
		?>

		<?php edit_post_link( __( 'Edit', 'flacso' ), '', '' ); ?>

Change header and title classes

Change header and title classes


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

namespace WellCommerce\Bundle\MediaBundle\Tests\Manager\Admin;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class MediaManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class MediaManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('media.manager');
    }
}

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

namespace WellCommerce\Bundle\MediaBundle\Tests\Manager\Admin;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class MediaManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class MediaManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('media.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php namespace VotingApp\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;

class Category extends Model implements SluggableInterface
{

    use SluggableTrait;

    public static function boot()
    {
        parent::boot();

        Category::saved(function ($category) {
            // Clear categories cache whenever model is updated
            \Cache::forget('categories');
        });
    }

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    /**
     * Configuration for generating slug with Eloquent-Sluggable.
     *
     * @var array
     */
    protected $sluggable = [
        'build_from' => 'name',
        'save_to' => 'slug'
    ];

    public function candidates()
    {
        return $this->hasMany('VotingApp\Models\Candidate')->orderBy('name', 'asc');
    }

}

<?php namespace VotingApp\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;

class Category extends Model implements SluggableInterface
{

    use SluggableTrait;

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    /**
     * Configuration for generating slug with Eloquent-Sluggable.
     *
     * @var array
     */
    protected $sluggable = [
        'build_from' => 'name',
        'save_to' => 'slug'
    ];

    /**
     * A category has many candidates.
     * @return mixed
     */
    public function candidates()
    {
        return $this->hasMany('VotingApp\Models\Candidate')->orderBy('name', 'asc');
    }

}

Remove old caching logic, and add missing docblock.


<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use BEAR\RepositoryModule\Annotation\AbstractCacheControl;
use BEAR\RepositoryModule\Annotation\Cacheable;
use BEAR\RepositoryModule\Annotation\Purge;
use BEAR\RepositoryModule\Annotation\Refresh;
use Ray\Di\AbstractModule;

class QueryRepositoryAopModule extends AbstractModule
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->bindPriorityInterceptor(
            $this->matcher->annotatedWith(Cacheable::class),
            $this->matcher->startsWith('onGet'),
            [CacheInterceptor::class]
        );
        $this->bindInterceptor(
            $this->matcher->annotatedWith(Cacheable::class),
            $this->matcher->logicalOr(
                $this->matcher->startsWith('onPost'),
                $this->matcher->logicalOr(
                    $this->matcher->startsWith('onPut'),
                    $this->matcher->logicalOr(
                        $this->matcher->startsWith('onPatch'),
                        $this->matcher->startsWith('onDelete')
                    )
                )
            ),
            [CommandInterceptor::class]
        );
        $this->bindInterceptor(
            $this->matcher->logicalNot(
                $this->matcher->annotatedWith(Cacheable::class)
            ),
            $this->matcher->logicalOr(
                $this->matcher->annotatedWith(Purge::class),
                $this->matcher->annotatedWith(Refresh::class)
            ),
            [RefreshInterceptor::class]
        );

        $this->bindInterceptor(
            $this->matcher->annotatedWith(AbstractCacheControl::class),
            $this->matcher->startsWith('onGet'),
            [HttpCacheInterceptor::class]
        );
    }
}

<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use BEAR\RepositoryModule\Annotation\AbstractCacheControl;
use BEAR\RepositoryModule\Annotation\Cacheable;
use BEAR\RepositoryModule\Annotation\Purge;
use BEAR\RepositoryModule\Annotation\Refresh;
use Ray\Di\AbstractModule;

class QueryRepositoryAopModule extends AbstractModule
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->bindPriorityInterceptor(
            $this->matcher->annotatedWith(Cacheable::class),
            $this->matcher->startsWith('onGet'),
            [CacheInterceptor::class]
        );
        $this->bindInterceptor(
            $this->matcher->annotatedWith(Cacheable::class),
            $this->matcher->logicalOr(
                $this->matcher->startsWith('onPut'),
                $this->matcher->logicalOr(
                    $this->matcher->startsWith('onPatch'),
                    $this->matcher->startsWith('onDelete')
                )
            ),
            [CommandInterceptor::class]
        );
        $this->bindInterceptor(
            $this->matcher->logicalNot(
                $this->matcher->annotatedWith(Cacheable::class)
            ),
            $this->matcher->logicalOr(
                $this->matcher->annotatedWith(Purge::class),
                $this->matcher->annotatedWith(Refresh::class)
            ),
            [RefreshInterceptor::class]
        );

        $this->bindInterceptor(
            $this->matcher->annotatedWith(AbstractCacheControl::class),
            $this->matcher->startsWith('onGet'),
            [HttpCacheInterceptor::class]
        );
    }
}

Remove post method from CommandInterceptor binding


<?php

namespace Gl3n\HttpQueryStringFilterBundle\ParameterType;

/**
 * Contains all parameter types
 */
class ParameterTypeChain
{
    /**
     * @var array
     */
    private $parameterTypes;

    /**
     * Adds a parameter type
     *
     * @param ParameterTypeInterface $parameterType
     * @param string                 $typeName
     */
    public function addParameterType(ParameterTypeInterface $parameterType, $typeName)
    {
        $this->parameterTypes[$typeName] = $parameterType;
    }

    /**
     * Gets a parameter type
     *
     * @param string $typeName
     *
     * @return ParameterTypeInterface
     */
    public function getType($typeName)
    {
        return $this->parameterTypes[$typeName];
    }
}

<?php

namespace Gl3n\HttpQueryStringFilterBundle\ParameterType;

/**
 * Contains all parameter types
 */
class ParameterTypeChain
{
    /**
     * @var array
     */
    private $parameterTypes;

    /**
     * Adds a parameter type
     *
     * @param ParameterTypeInterface $parameterType
     * @param string                 $typeName
     */
    public function addParameterType(ParameterTypeInterface $parameterType, $typeName)
    {
        $this->parameterTypes[$typeName] = $parameterType;
    }

    /**
     * Gets a parameter type
     *
     * @param string $typeName
     *
     * @return ParameterTypeInterface
     */
    public function getParameterType($typeName)
    {
        return $this->parameterTypes[$typeName];
    }
}

Rename method getType to getParameterType


<?php

namespace BinSoul\Test\Common\Measurement\SystemOfUnits;

use BinSoul\Common\Measurement\SystemOfUnits;
use BinSoul\Common\Measurement\Unit;
use BinSoul\Common\Measurement\Converter;

abstract class SystemOfUnitsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @return SystemOfUnits
     */
    abstract protected function buildUnits();

    public function test_can_build_all_units()
    {
        $units = $this->buildUnits();

        foreach ($units->getUnits() as $code) {
            $units = $this->buildUnits();
            $unit = $units->build($code);
            $this->assertInstanceOf(Unit::class, $unit, $code);
            $this->assertNotEmpty($unit->getQuantity(), $code);
            $this->assertNotEmpty($unit->getDimension()->getSymbol(), $code);
            $this->assertNotEmpty($unit->getStandardUnit()->getSymbol(), $code);
            $this->assertInstanceOf(Converter::class, $unit->toStandardUnit(), $code);
            $this->assertNotEmpty($unit->getBaseUnits()->getSymbol(), $code);
            $this->assertInstanceOf(Converter::class, $unit->toBaseUnits(), $code);
        }
    }
}

<?php

namespace BinSoul\Test\Common\Measurement\SystemOfUnits;

use BinSoul\Common\Measurement\SystemOfUnits;
use BinSoul\Common\Measurement\Unit;
use BinSoul\Common\Measurement\Converter;

abstract class SystemOfUnitsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @return SystemOfUnits
     */
    abstract protected function buildUnits();

    public function test_can_build_all_units()
    {
        $units = $this->buildUnits();

        foreach ($units->getUnits() as $code) {
            $units = $this->buildUnits();
            $unit = $units->build($code);
            $this->assertInstanceOf(Unit::class, $unit, $code);
            $this->assertNotEmpty($unit->getQuantity(), $code);
            $this->assertNotEmpty($unit->getDimension()->getSymbol(), $code);
            $this->assertNotEmpty($unit->getStandardUnit()->getSymbol(), $code);
            $this->assertInstanceOf(Converter::class, $unit->toStandardUnit(), $code);
            $this->assertNotEmpty($unit->getBaseUnits()->getSymbol(), $code);
            $this->assertInstanceOf(Converter::class, $unit->toBaseUnits(), $code);

            $this->assertSame($unit, $units->build($code));
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function test_throws_exception_for_invalid_unit()
    {
        $units = $this->buildUnits();
        $units->build('foobar');
    }
}

Add missing tests of SystemOfUnits

Add missing tests of SystemOfUnits


<?php
require_once ('mysql.php');

$benchID   = $_GET["bench"];
$format    = $_GET["format"];
$latitude  = $_GET["latitude"];
$longitude = $_GET["longitude"];
$radius    = $_GET["radius"];

if (null != $latitude && null != $longitude && null != $radius) {
	$geojson = get_nearest_benches($latitude, $longitude, $radius);
} else if (null != $benchID){
	$geojson = get_bench($benchID);
} else {
	$geojson = get_all_benches();
}

if ("raw" == $format) {
	header('Content-Type: application/json; charset=utf-8');
	echo json_encode($geojson, JSON_NUMERIC_CHECK);
} else {
	header('Content-type: text/javascript; charset=utf-8');
	echo "var benches = " . json_encode($geojson, JSON_NUMERIC_CHECK);
}

die();

<?php
ini_set( 'serialize_precision', -1 );	//	https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue
require_once ('mysql.php');

$benchID   = $_GET["bench"];
$format    = $_GET["format"];
$latitude  = $_GET["latitude"];
$longitude = $_GET["longitude"];
$radius    = $_GET["radius"];

if (null != $latitude && null != $longitude && null != $radius) {
	$geojson = get_nearest_benches($latitude, $longitude, $radius);
} else if (null != $benchID){
	$geojson = get_bench($benchID);
} else {
	$geojson = get_all_benches();
}

if ("raw" == $format) {
	header('Content-Type: application/json; charset=utf-8');
	echo json_encode($geojson, JSON_NUMERIC_CHECK);
} else {
	header('Content-type: text/javascript; charset=utf-8');
	echo "var benches = " . json_encode($geojson, JSON_NUMERIC_CHECK);
}

die();

Reduce precision of floats in JSON

Reduce precision of floats in JSON

Due to a https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue

Fixes #161


    getFilename() }}">

Upcoming Events

link }}" target="_blank" class="btn-small">See all events

			@foreach ($events->slice(0,6) as $event)

				<?php $section = $event->section ?: 'content'; ?>

				@include( $event->extends, [
					'page' => $page->merge($event),
					$section => $event->getContent()
				])

			@endforeach

    getFilename() }}">

Upcoming Events

link }}" target="_blank" class="btn-small">See all events

			<?php

				// Don't show events before current date
				$events = $events->filter( function( $event ) {
					return date("Y-m-d", $event->sortOrder) >= date("Y-m-d");
				});

			?>

			@foreach ($events->slice(0,6) as $event)

				<?php $section = $event->section ?: 'content'; ?>

				@include( $event->extends, [
					'page' => $page->merge($event),
					$section => $event->getContent()
				])

			@endforeach

Hide events before current date

Hide events before current date


<?php

namespace App\Jobs;

use App\Jobs\Job;
use Request;
use Illuminate\Contracts\Bus\SelfHandling;

class SetLocale extends Job implements SelfHandling
{
    /**
     * The availables languages.
     *
     * @array $languages
     */
    protected $languages = ['en','fr', 'br'];

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        if(!session()->has('locale'))
        {
            session()->put('locale', Request::getPreferredLanguage($this->languages));
        }

        app()->setLocale(session('locale'));
    }
}

<?php

namespace App\Jobs;

use App\Jobs\Job;
use Request;
use Illuminate\Contracts\Bus\SelfHandling;

class SetLocale extends Job implements SelfHandling
{
    /**
     * The availables languages.
     *
     * @array $languages
     */
    protected $languages = ['en','fr'];

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        if(!session()->has('locale'))
        {
            session()->put('locale', Request::getPreferredLanguage($this->languages));
        }

        app()->setLocale(session('locale'));
    }
}

ADD support to multiple languages from config/app.php config file


<?php
// kwtest library
require_once('kwtest/kw_web_tester.php');

class TestEnvTestCase extends KWWebTestCase
{
  function __construct()
    {
    parent::__construct();
    }

  function testTestEnv()
    {
    $s = '';

    global $cdashpath;
    $s = $s . "cdashpath=[".print_r($cdashpath, true)."]\n";

    global $configure;
    $s = $s . "configure=[".print_r($configure, true)."]\n";

    global $db;
    $s = $s . "db=[".print_r($db, true)."]\n";

    global $inBrowser;
    $s = $s . "inBrowser=[".print_r($inBrowser, true)."]\n";

    global $web_report;
    $s = $s . "web_report=[".print_r($web_report, true)."]\n";

    global $isWindows;
    $s = $s . "isWindows=[".print_r($isWindows, true)."]\n";

    global $isMacOSX;
    $s = $s . "isMacOSX=[".print_r($isMacOSX, true)."]\n";

    $s = $s . "\n";

    $this->assertTrue(true, $s);
    }

}
?>

<?php
// kwtest library
require_once('kwtest/kw_web_tester.php');

// comment only change to test dashboard svn update step...

class TestEnvTestCase extends KWWebTestCase
{
  function __construct()
    {
    parent::__construct();
    }

  function testTestEnv()
    {
    $s = '';

    global $cdashpath;
    $s = $s . "cdashpath=[".print_r($cdashpath, true)."]\n";

    global $configure;
    $s = $s . "configure=[".print_r($configure, true)."]\n";

    global $db;
    $s = $s . "db=[".print_r($db, true)."]\n";

    global $inBrowser;
    $s = $s . "inBrowser=[".print_r($inBrowser, true)."]\n";

    global $web_report;
    $s = $s . "web_report=[".print_r($web_report, true)."]\n";

    global $isWindows;
    $s = $s . "isWindows=[".print_r($isWindows, true)."]\n";

    global $isMacOSX;
    $s = $s . "isMacOSX=[".print_r($isMacOSX, true)."]\n";

    $s = $s . "\n";

    $this->assertTrue(true, $s);
    }

}
?>

STYLE: Comment only change to test dashboard svn update step.

git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@1911 91079597-3006-4846-9bd3-4f3fb3d139a7


<?php
/**
 * Erdiko Test Suite
 * Be sure to name your test cases MyClassTest.php where MyClass is the functionality being tested
 */

class AllTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ErdikoTests');
		$testFiles = $this->_getTestFiles();

		foreach ($testFiles as $file)
		{
			$suite->addTestFile($file);
		}

		return $suite;
	}

	private function _getTestFiles()
	{
		return glob( './*/*Test.php');
	}
}

<?php
/**
 * Erdiko Test Suite
 * Be sure to name your test cases MyClassTest.php where MyClass is the functionality being tested
 */

class AllTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ErdikoTests');
		$testFiles = AllTests::_getTestFiles();

		foreach ($testFiles as $file)
			$suite->addTestFile($file);

		return $suite;
	}

	private static function _getTestFiles()
	{
		return glob( './*/*Test.php');
	}
}

Fix to run the suite of tests

Fix to run the suite of tests


<?php

namespace SQLgreyGUI\Providers;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register any application services.
     */
    public function register()
    {
        // Register Service Providers for local development
        if ($this->app->environment('local')) {
            $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }
}

<?php

namespace SQLgreyGUI\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        // https://laravel.com/docs/master/migrations#creating-indexes
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     */
    public function register()
    {
        // Register Service Providers for local development
        if ($this->app->environment('local')) {
            $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }
}

Set database default string length

Set database default string length


<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Routing\Stack\Builder as Stack;
use Illuminate\Foundation\Support\Providers\AppServiceProvider as ServiceProvider;

class AppServiceProvider extends ServiceProvider {

	/**
	 * All of the application's route middleware keys.
	 *
	 * @var array
	 */
	protected $middleware = [
		'auth' => 'App\Http\Middleware\AuthMiddleware',
		'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
		'csrf' => 'App\Http\Middleware\CsrfMiddleware',
		'guest' => 'App\Http\Middleware\GuestMiddleware',
	];

	/**
	 * The application's middleware stack.
	 *
	 * @var array
	 */
	protected $stack = [
		'App\Http\Middleware\MaintenanceMiddleware',
		'Illuminate\Cookie\Middleware\Guard',
		'Illuminate\Cookie\Middleware\Queue',
		'Illuminate\Session\Middleware\Reader',
		'Illuminate\Session\Middleware\Writer',
		'Illuminate\View\Middleware\ErrorBinder',
	];

	/**
	 * Build the application stack based on the provider properties.
	 *
	 * @return void
	 */
	public function stack()
	{
		$this->app->stack(function(Stack $stack, Router $router)
		{
			return $stack
				->middleware($this->stack)->then(function($request) use ($router)
				{
					return $router->dispatch($request);
				});
			});
	}

}

<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Routing\Stack\Builder as Stack;
use Illuminate\Foundation\Support\Providers\AppServiceProvider as ServiceProvider;

class AppServiceProvider extends ServiceProvider {

	/**
	 * All of the application's route middleware keys.
	 *
	 * @var array
	 */
	protected $middleware = [
		'auth' => 'App\Http\Middleware\AuthMiddleware',
		'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
		'csrf' => 'App\Http\Middleware\CsrfMiddleware',
		'guest' => 'App\Http\Middleware\GuestMiddleware',
	];

	/**
	 * The application's middleware stack.
	 *
	 * @var array
	 */
	protected $stack = [
		'App\Http\Middleware\MaintenanceMiddleware',
		'Illuminate\Cookie\Middleware\Guard',
		'Illuminate\Cookie\Middleware\Queue',
		'Illuminate\Session\Middleware\Reader',
		'Illuminate\Session\Middleware\Writer',
		'Illuminate\View\Middleware\ErrorBinder',
		'App\Http\Middleware\CsrfMiddleware',
	];

	/**
	 * Build the application stack based on the provider properties.
	 *
	 * @return void
	 */
	public function stack()
	{
		$this->app->stack(function(Stack $stack, Router $router)
		{
			return $stack
				->middleware($this->stack)->then(function($request) use ($router)
				{
					return $router->dispatch($request);
				});
			});
	}

}

Add CSRF middleware to main app stack.

Add CSRF middleware to main app stack.


<?php

namespace App\Middleware;

use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;

/**
 * @property Twig view
 * @property Router router
 * @property Messages flash
 * @property Sentinel auth
 */
abstract class Middleware
{
    /**
     * Slim application container
     *
     * @var ContainerInterface
     */
    protected $container;

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

    public abstract function __invoke(Request $request, Response $response, callable $next);

    public function __get($property)
    {
        return $this->container->get($property);
    }
}

<?php

namespace App\Middleware;

use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;

/**
 * @property Twig view
 * @property Router router
 * @property Messages flash
 * @property Sentinel auth
 */
abstract class Middleware
{
    /**
     * Slim application container
     *
     * @var ContainerInterface
     */
    protected $container;

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

    abstract public function __invoke(Request $request, Response $response, callable $next);

    public function __get($property)
    {
        return $this->container->get($property);
    }
}

Put 'abstract' keyword before visibility to follow psr-2 standard


<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\TaxRatesForOrder;

use ActiveCollab\Payments\Order\OrderInterface;
use ActiveCollab\Payments\OrderItem\OrderItemInterface;

interface TaxRatesForOrderInterface
{
    public function getOrder(): OrderInterface;

    public function getTaxableAmount(): float;

    public function getTaxAmount(): float;

    public function getFirstTaxRateFor(OrderItemInterface $order_item): ?float;

    public function getSecondTaxRateFor(OrderItemInterface $order_item): ?float;

    public function getSecondTaxRateIsCompoundFor(OrderItemInterface $order_item): ?bool;
}

<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\TaxRatesForOrder;

use ActiveCollab\Payments\Order\OrderInterface;
use ActiveCollab\Payments\OrderItem\OrderItemInterface;

interface TaxRatesForOrderInterface
{
    public function getOrder(): OrderInterface;

    public function getTaxableAmount(): float;

    public function getTaxAmount(): float;

    public function getFirstTaxRateFor(OrderItemInterface $order_item): ?float;

    public function getSecondTaxRateFor(OrderItemInterface $order_item): ?float;

    public function getSecondTaxIsCompoundFor(OrderItemInterface $order_item): ?bool;
}

Fix incorrect coumpund tax flag method name


<?php
namespace PhpBrew\Tasks;

use PhpBrew\Utils;

class Patch64BitSupportTask extends BaseTask
{

    public function match($build)
    {
        $currentVersion = preg_replace('/[^\d]*(\d+).(\d+).*/i', '$1.$2', $build->version);

        return (Utils::support64bit() && version_compare($currentVersion, '5.3', '=='));
    }

    public function patch($build, $options)
    {
        $this->info("===> Checking if php-5.3 source is on 64bit machine");

        if ($this->match($build)) {
            // Then patch Makefile for PHP 5.3.x on 64bit system.
            $this->info("===> Applying patch file for php5.3.x on 64bit machine.");

            if (!$options->dryrun) {
                system('sed -i \'/^BUILD_/ s/\$(CC)/\$(CXX)/g\' Makefile');
                system('sed -i \'/EXTRA_LIBS = /s|$| -lstdc++|\' Makefile');
            }
        }
    }
}

<?php
namespace PhpBrew\Tasks;

use PhpBrew\Utils;

class Patch64BitSupportTask extends BaseTask
{

    public function match($build)
    {
        $currentVersion = preg_replace('/[^\d]*(\d+).(\d+).*/i', '$1.$2', $build->version);

        return (Utils::support64bit() && version_compare($currentVersion, '5.3', '=='));
    }

    public function patch($build, $options)
    {
        $this->info("===> Checking if php-5.3 source is on 64bit machine");

        if ($this->match($build)) {
            // Then patch Makefile for PHP 5.3.x on 64bit system.
            $this->info("===> Applying patch file for php5.3.x on 64bit machine.");

            if (!$options->dryrun) {
                system('sed -i.bak \'/^BUILD_/ s/\$(CC)/\$(CXX)/g\' Makefile');
                system('sed -i.bak \'/EXTRA_LIBS = /s|$| -lstdc++|\' Makefile');
            }
        }
    }
}

Fix sed command argument by appending -i.bak


<?php
/*
 * Copyright 2016 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Validator\Rule;

use Coast\Validator\Rule;

class Number extends Rule
{
	protected function _validate($value)
	{
		if (!is_numeric($value)) {
		 	$this->error();
		}
	}
}

<?php
/*
 * Copyright 2016 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Validator\Rule;

use Coast\Validator\Rule;

class Number extends Float
{}

Remove redundant number validator code

Remove redundant number validator code


<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

/**
 * @covers Email
 */
final class EmailTest extends TestCase
{
    public function testCanBeCreatedFromValidEmailAddress(): void
    {
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    // TODO: Enable when the problem with interface catching is solved
    // public function testCannotBeCreatedFromInvalidEmailAddress(): void
    // {
    //     $this->expectException(InvalidArgumentException::class);

    //     Email::fromString('invalid');
    // }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

/**
 * @covers Email
 */
final class EmailTest extends TestCase
{
    public function testCanBeCreatedFromValidEmailAddress(): void
    {
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    public function testCannotBeCreatedFromInvalidEmailAddress(): void
    {
        $this->expectException(InvalidArgumentException::class);

        Email::fromString('invalid');
    }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}

Enable PHPUnit exception expecting test

Enable PHPUnit exception expecting test


<?php
/**
 * This file is part of the ImboClientCli package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboClientCli\Command;

use ImboClient\Client as ImboClient,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface,
    RuntimeException;

/**
 * Command used to see if an image exist on an imbo server
 *
 * @package Commands
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class NumImages extends RemoteCommand {
    /**
     * Class constructor
     */
    public function __construct() {
        parent::__construct('num-images');

        $this->setDescription('Get the number of images on an imbo server');
        $this->setHelp('Get the number of images on an imbo server');
    }

    /**
     * Execute the command
     *
     * @see Symfony\Components\Console\Command\Command::execute()
     */
    protected function execute(InputInterface $input, OutputInterface $output) {
        $client = new ImboClient($this->server['url'], $this->server['publicKey'], $this->server['privateKey']);

        try {
            $num = $client->getNumImages();
        } catch (RuntimeException $e) {
            $output->writeln('An error occured. Could not complete the action.');
            return;
        }

        if ($num === false) {
            $output->writeln($this->server['name'] . ' did not respond correctly.');
        } else {
            $output->writeln($this->server['name'] . ' has ' . $num . ' images.');
        }
    }
}

<?php
/**
 * This file is part of the ImboClientCli package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboClientCli\Command;

use ImboClient\Client as ImboClient,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface,
    RuntimeException;

/**
 * Command used to see if an image exist on an imbo server
 *
 * @package Commands
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class NumImages extends RemoteCommand {
    /**
     * Class constructor
     */
    public function __construct() {
        parent::__construct('num-images');

        $this->setDescription('Get the number of images on an imbo server');
        $this->setHelp('Get the number of images on an imbo server');
    }

    /**
     * Execute the command
     *
     * @see Symfony\Components\Console\Command\Command::execute()
     */
    protected function execute(InputInterface $input, OutputInterface $output) {
        $num = $this->getClient()->getNumImages();
        $output->writeln('<info>' . $this->server['publicKey'] . '</info> has <info>' . $num . '</info> image' . ($num !== 1 ? 's' : '') . '.');
    }
}

Use the new API of the client

Use the new API of the client


<?php
/*
 * This file is part of JoliCi.
*
* (c) Joel Wurtz <jwurtz@jolicode.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Joli\JoliCi\Log;

use Monolog\Formatter\FormatterInterface;

class SimpleFormatter implements FormatterInterface
{

    /*
     * (non-PHPdoc) @see \Monolog\Formatter\FormatterInterface::format()
     */
    public function format(array $record)
    {
        return $record['message'];
    }

    /*
     * (non-PHPdoc) @see \Monolog\Formatter\FormatterInterface::formatBatch()
     */
    public function formatBatch(array $records)
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }

        return $message;
    }
}

<?php
/*
 * This file is part of JoliCi.
*
* (c) Joel Wurtz <jwurtz@jolicode.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Joli\JoliCi\Log;

use Monolog\Formatter\FormatterInterface;

class SimpleFormatter implements FormatterInterface
{
    private $static = array();

    /*
     * (non-PHPdoc) @see \Monolog\Formatter\FormatterInterface::format()
     */
    public function format(array $record)
    {
        $message = $record['message'];

        if (isset($record['context']['static']) && $record['context']['static']) {
            $id      = $record['context']['static-id'];

            if (!isset($this->static[$id])) {
                $this->static[$id] = array(
                    'current_line' => count($this->static),
                    'message'      => $message
                );

                $message = sprintf("\n%s", $message);
            } else {
                $diff                         = (count($this->static) - $this->static[$id]['current_line']) - 1;
                $lastMessage                  = $this->static[$id]['message'];
                $this->static[$id]['message'] = $message;

                //Add space to replace old string in message
                if (mb_strlen($lastMessage) > mb_strlen($message)) {
                    $message = str_pad($message, mb_strlen($lastMessage), " ", STR_PAD_RIGHT);
                }

                if ($diff > 0) {
                    $message = sprintf("\x0D\x1B[%sA%s\x1B[%sB", $diff, $message, $diff);
                } else {
                    $message = "\x0D".$message;
                }
            }
        }

        return $message;
    }

    /*
     * (non-PHPdoc) @see \Monolog\Formatter\FormatterInterface::formatBatch()
     */
    public function formatBatch(array $records)
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }

        return $message;
    }
}

Add static progress bar when getting image from docker


<?php
    define( 'DIRECTION_NONE', 0 );
    define( 'DIRECTION_NORTH', 1 );
    define( 'DIRECTION_EAST', 2 );
    define( 'DIRECTION_SOUTH', 3 );
    define( 'DIRECTION_WEST', 4 );
    define( 'ACTION_ATACK', 0 );
    define( 'ACTION_MOVE', 1 );
    class Intent {
        public $action;
        public $direction;

        public function __construct( $action, $direction ) {
            $this->direction = array(
                'DIRECTION_NONE' => DIRECTION_NONE,
                'DIRECTION_NORTH' => DIRECTION_NORTH,
                'DIRECTION_EAST' => DIRECTION_EAST,
                'DIRECTION_SOUTH' => DIRECTION_SOUTH,
                'DIRECTION_WEST' => DIRECTION_WEST
            )[ $direction ];
            $this->action = array(
                'ACTION_ATACK' => ACTION_ATACK,
                'ACTION_MOVE' => ACTION_MOVE
            )[ $action ];
        }
    }
?>

<?php
    define( 'DIRECTION_NONE', 0 );
    define( 'DIRECTION_NORTH', 1 );
    define( 'DIRECTION_EAST', 2 );
    define( 'DIRECTION_SOUTH', 3 );
    define( 'DIRECTION_WEST', 4 );
    define( 'ACTION_NONE', 0 );
    define( 'ACTION_MOVE', 1 );
    define( 'ACTION_ATACK', 2 );
    class Intent {
        public $action;
        public $direction;

        public function __construct( $action, $direction ) {
            $this->direction = array(
                'DIRECTION_NONE' => DIRECTION_NONE,
                'DIRECTION_NORTH' => DIRECTION_NORTH,
                'DIRECTION_EAST' => DIRECTION_EAST,
                'DIRECTION_SOUTH' => DIRECTION_SOUTH,
                'DIRECTION_WEST' => DIRECTION_WEST
            )[ $direction ];
            $this->action = array(
                'ACTION_NONE' => ACTION_NONE,
                'ACTION_MOVE' => ACTION_ATACK,
                'ACTION_ATACK' => ACTION_MOVE
            )[ $action ];
        }
    }
?>

Add ACTION_NONE to the definitions

Add ACTION_NONE to the definitions


<?php

final class PhabricatorEditEngineSubtypeTransaction
  extends PhabricatorEditEngineTransactionType {

  const TRANSACTIONTYPE = 'editengine.config.subtype';

  public function generateOldValue($object) {
    return $object->getSubtype();
  }

  public function applyInternalEffects($object, $value) {
    $object->setSubtype($value);
  }

  public function getTitle() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    return pht(
      '%s changed the subtype of this form from %s to %s.',
      $this->renderAuthor(),
      $this->renderOldValue(),
      $this->renderNewValue());
  }

  public function validateTransactions($object, array $xactions) {
    $map = $object->getEngine()
      ->setViewer($this->getActor())
      ->newSubtypeMap();

    $errors = array();
    foreach ($xactions as $xaction) {
      $new = $xaction->getNewValue();

      if ($map->isValidSubtype($new)) {
        continue;
      }

      $errors[] = $this->newInvalidError(
        pht('Subtype "%s" is not a valid subtype.', $new),
        $xaction);
    }

    return $errors;
  }

}

<?php

final class PhabricatorEditEngineSubtypeTransaction
  extends PhabricatorEditEngineTransactionType {

  const TRANSACTIONTYPE = 'editengine.config.subtype';

  public function generateOldValue($object) {
    return $object->getSubtype();
  }

  public function applyInternalEffects($object, $value) {
    $object->setSubtype($value);
  }

  public function getTitle() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    return pht(
      '%s changed the subtype of this form from %s to %s.',
      $this->renderAuthor(),
      $this->renderOldValue(),
      $this->renderNewValue());
  }

  public function validateTransactions($object, array $xactions) {
    $errors = array();

    if (!$xactions) {
      return $errors;
    }

    $engine = $object->getEngine();

    if (!$engine->supportsSubtypes()) {
      foreach ($xactions as $xaction) {
        $errors[] = $this->newInvalidError(
          pht(
            'Edit engine (of class "%s") does not support subtypes, so '.
            'subtype transactions can not be applied to it.',
            get_class($engine)),
          $xaction);
      }
      return $errors;
    }

    $map = $engine
      ->setViewer($this->getActor())
      ->newSubtypeMap();

    foreach ($xactions as $xaction) {
      $new = $xaction->getNewValue();

      if ($map->isValidSubtype($new)) {
        continue;
      }

      $errors[] = $this->newInvalidError(
        pht('Subtype "%s" is not a valid subtype.', $new),
        $xaction);
    }

    return $errors;
  }

}

Fix incorrect construction of subtype map when validating "subtype" transactions against non-subtypable objects

Summary:
Fixes T13389. Currently, we try to "newSubtypeMap()" unconditionally, even if the underlying object does not support subtypes.

  - Only try to build a subtype map if subtype transactions are actually being applied.
  - When subtype transactions are applied to a non-subtypable object, fail more explicitly.

Test Plan: Clicked "Make Editable" in a fresh Calendar transaction form, got an editable form instead of a fatal from "newSubtypeMap()". (Calendar events are not currently subtypable.)

Maniphest Tasks: T13389

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


<?php

/**
 * This file is part of the Heystack package
 *
 * @package Heystack
 */

/**
 * Core namespace
 */
namespace Heystack\Subsystem\Core;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Service store allows acess to the Symfony dependency injection container from SilverStripe code.
 *
 * SilverStripe services like controllers can't easily be created and accessed
 * by SilverStripe through the dependency injection component, and so, a global
 * store is made available for SilverStripe-centric classes that need to access
 * services
 *
 * @copyright  Heyday
 * @author Cam Spiers <cameron@heyday.co.nz>
 * @package Heystack
 *
 */
class ServiceStore
{
    /**
     * Stores the service container
     */
    private static $serviceContainer = null;

    /**
     * Returns the service container
     * @return Container
     */
    public static function get()
    {

        return self::$serviceContainer;

    }
    /**
     * Sets the service container
     * @param  Container $container
     * @return null
     */
    public static function set(Container $container)
    {

        self::$serviceContainer = $container;

    }
    /**
     * Gets a specific service by name from the service container
     * @param  string $service
     * @return mixed
     */
    public static function getService($service)
    {

        return self::$serviceContainer->get($service, ContainerInterface::NULL_ON_INVALID_REFERENCE);

    }

}

<?php

/**
 * This file is part of the Heystack package
 *
 * @package Heystack
 */

/**
 * Core namespace
 */
namespace Heystack\Subsystem\Core;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Service store allows acess to the Symfony dependency injection container from SilverStripe code.
 *
 * SilverStripe services like controllers can't easily be created and accessed
 * by SilverStripe through the dependency injection component, and so, a global
 * store is made available for SilverStripe-centric classes that need to access
 * services
 *
 * @copyright  Heyday
 * @author Cam Spiers <cameron@heyday.co.nz>
 * @package Heystack
 *
 */
class ServiceStore
{
    /**
     * Stores the service container
     */
    private static $serviceContainer = null;

    /**
     * Returns the service container
     * @return Container
     */
    public static function get()
    {

        return self::$serviceContainer;

    }
    /**
     * Sets the service container
     * @param  Container $container
     * @return null
     */
    public static function set(Container $container)
    {

        self::$serviceContainer = $container;

    }
    /**
     * Gets a specific service by name from the service container
     * @param  string $service
     * @return mixed
     */
    public static function getService($service)
    {

        return self::$serviceContainer instanceof Container ? self::$serviceContainer->get($service, ContainerInterface::NULL_ON_INVALID_REFERENCE) : null;

    }

}

BUGFIX: Check there is a service container before calling get on it.


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Admin / Controller
 */
namespace PH7;

class InfoController extends Controller
{

    private $sTitle;

    public function index()
    {
        Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get(PH7_ADMIN_MOD, 'info', 'software'));
    }

    public function language()
    {
        $this->sTitle = t('Php Information');
        $this->view->page_title = $this->sTitle;
        $this->view->h1_title = $this->sTitle;
        $this->output();
    }

    public function software()
    {
        $this->sTitle = t('%software_name% Information');
        $this->view->page_title = $this->sTitle;
        $this->view->h1_title = $this->sTitle;
        $this->view->release_date = $this->dateTime->get(Framework\Security\Version::KERNEL_RELASE_DATE)->date();
        $this->output();
    }

    public function __destruct()
    {
        unset($this->sTitle);
    }

}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Admin / Controller
 */
namespace PH7;

class InfoController extends Controller
{
    private $sTitle;

    public function index()
    {
        Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get(PH7_ADMIN_MOD, 'info', 'software'));
    }

    public function language()
    {
        $this->sTitle = t('PHP Information');
        $this->view->page_title = $this->sTitle;
        $this->view->h1_title = $this->sTitle;
        $this->output();
    }

    public function software()
    {
        $this->sTitle = t('%software_name% Information');
        $this->view->page_title = $this->sTitle;
        $this->view->h1_title = $this->sTitle;
        $this->view->release_date = $this->dateTime->get(Framework\Security\Version::KERNEL_RELASE_DATE)->date();
        $this->output();
    }
}

Set "PHP" word to uppercase!

Set "PHP" word to uppercase!


<?php

namespace FoF\Upload\Adapters;

use FoF\Upload\Contracts\UploadAdapter;
use FoF\Upload\File;
use FoF\Upload\Helpers\Settings;
use Illuminate\Support\Arr;

class AwsS3 extends Flysystem implements UploadAdapter
{
    protected function generateUrl(File $file)
    {
        /** @var Settings $settings */
        $settings = app()->make(Settings::class);

        if ($cdnUrl = $settings->get('cdnUrl')) {
            $file->url = sprintf('%s/%s', $cdnUrl, $file->url);
        } else {
            $region = $this->adapter->getClient()->getRegion();
            $bucket = $this->adapter->getBucket();

            $baseUrl = sprintf('https://%s.s3.%s.amazonaws.com/', $bucket, $region ?: 'us-east-1');

            $file->url = sprintf(
                $baseUrl . '%s',
                Arr::get($this->meta, 'path', $file->path)
            );
        }
    }
}

<?php

namespace FoF\Upload\Adapters;

use FoF\Upload\Contracts\UploadAdapter;
use FoF\Upload\File;
use FoF\Upload\Helpers\Settings;
use Illuminate\Support\Arr;

class AwsS3 extends Flysystem implements UploadAdapter
{
    protected function generateUrl(File $file)
    {
        /** @var Settings $settings */
        $settings = app()->make(Settings::class);

        $cdnUrl = $settings->get('cdnUrl');

        if (!$cdnUrl) {
            $region = $this->adapter->getClient()->getRegion();
            $bucket = $this->adapter->getBucket();

            $cdnUrl = sprintf('https://%s.s3.%s.amazonaws.com', $bucket, $region ?: 'us-east-1');
        }

        $file->url = sprintf('%s/%s', $cdnUrl, Arr::get($this->meta, 'path', $file->path));
    }
}

Fix url when using cdnUrl with S3. Null url was incorrectly used as path


<?php

/*

Plugin Name: Castlegate IT WP User Guide
Plugin URI: https://github.com/castlegateit/cgit-wp-user-guide
Description: Add a simple WordPress user guide to the admin panel.
Version: 5.4.3
Author: Castlegate IT
Author URI: https://www.castlegateit.co.uk/
License: MIT

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_USER_GUIDE_PLUGIN', __FILE__);
define('CGIT_USER_GUIDE_PLUGIN_URL', plugin_dir_url(__FILE__));

require_once __DIR__ . '/lib/parsedown/Parsedown.php';
require_once __DIR__ . '/classes/autoload.php';

$plugin = new \Cgit\UserGuide\Plugin();

do_action('cgit_user_guide_plugin', $plugin);
do_action('cgit_user_guide_loaded');

<?php

/*

Plugin Name: Castlegate IT WP User Guide
Plugin URI: https://github.com/castlegateit/cgit-wp-user-guide
Description: Add a simple WordPress user guide to the admin panel.
Version: 5.4.3
Author: Castlegate IT
Author URI: https://www.castlegateit.co.uk/
License: AGPL

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_USER_GUIDE_PLUGIN', __FILE__);
define('CGIT_USER_GUIDE_PLUGIN_URL', plugin_dir_url(__FILE__));

require_once __DIR__ . '/lib/parsedown/Parsedown.php';
require_once __DIR__ . '/classes/autoload.php';

$plugin = new \Cgit\UserGuide\Plugin();

do_action('cgit_user_guide_plugin', $plugin);
do_action('cgit_user_guide_loaded');

Switch license from MIT to AGPL in plugin file


<?php

namespace Fillet\Writer;

use Symfony\Component\Yaml\Dumper as YamlDumper;

/**
 * Generates a Post for Sculpin
 *
 * @package Fillet\Writer
 */
class PostWriter extends AbstractWriter
{
	/**
	 * Write out a set of data into a file
	 *
	 * @param array $data Data to use for constructing the page
	 */
    public function write($data)
    {
        $post_date_string = $data['post_date']->format('Y-m-d H:i:s');
        $slug = $this->generateSlug($data['title']);
        $filename = $data['post_date']->format('Y-m-d') . '-' . $slug;

		$headerData = [
			'title' => $data['title'],
			'date' => $post_date_string,
			'layout' => 'post',
			'slug' => $slug,
			'categories' => $data['categories'],
			'tags' => $data['tags'],
		];

		$dumper = new YamlDumper();
		$header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL;

        $filename = $this->destinationFolder . '/' . $filename;
        if ($this->isMarkdownEnabled()) {
            $filename .= '.md';
            $data['content'] = $this->toMarkdown($data['content']);
        } else {
            $filename .= '.html';
        }
        file_put_contents($filename, $header . PHP_EOL . $data['content']);
    }
}

<?php

namespace Fillet\Writer;

use Symfony\Component\Yaml\Dumper as YamlDumper;

/**
 * Generates a Post for Sculpin
 *
 * @package Fillet\Writer
 */
class PostWriter extends AbstractWriter
{
	/**
	 * Write out a set of data into a file
	 *
	 * @param array $data Data to use for constructing the page
	 */
    public function write($data)
    {
        $post_date_string = $data['post_date']->format('Y-m-d H:i:s');
        $slug = $this->generateSlug($data['title']);
        $filename = $data['post_date']->format('Y-m-d') . '-' . $slug;

		$headerData = [
			'title' => $data['title'],
			'date' => $post_date_string,
			'layout' => 'post',
			'slug' => $slug,
			'categories' => $data['categories'],
			'tags' => $data['tags'],
		];

		$dumper = new YamlDumper();
		$header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL;

        $filename = $this->destinationFolder . $filename;
        if ($this->isMarkdownEnabled()) {
            $filename .= '.md';
            $data['content'] = $this->toMarkdown($data['content']);
        } else {
            $filename .= '.html';
        }
        file_put_contents($filename, $header . PHP_EOL . $data['content']);
    }
}

Remove double slash in filename

Remove double slash in filename


<?php

namespace Admin\Controller;

use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    private $identity;

    public function initialize()
    {
        $this->identity = $this->di->get('auth')->getIdentity();

        if (!$this->identity) {
            $this->response->redirect('/admin/auth/login', true);
        }
    }

    /**
     * Dashboard
     */
    public function indexAction()
    {
        $this->view->setLayout('admin');
    }
}

<?php

namespace Admin\Controller;

use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    private $identity;

    public function initialize()
    {
        $this->identity = $this->di->get('auth')->getIdentity();

        if (!$this->identity) {
            $this->response->redirect('/admin/auth/login', true)->send();
        }
    }

    /**
     * Dashboard
     */
    public function indexAction()
    {
        $this->view->setLayout('admin');
    }
}

Send headers when redirect to avoid non identity bug


<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;

class CodeBlock extends Node implements NodeAcceptorInterface
{

    /**
     * @var Collection
     */
    protected $lines;

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

    public function __construct(Text $text, $language = null)
    {
        $this->lines = new Collection([$text]);
        $this->language = $language;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        $this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', ''));

        return $this;
    }

    public function acceptCodeBlock(CodeBlock $codeBlock)
    {
        $codeBlock->lines->each(function (Text $line) {
            $this->lines->add($line);
        });

        return $this;
    }

    public function getContent()
    {
        $content = new Text($this->lines->join("\n"));

        // Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline.
        $content->replace('/(\n[ ]*)*$/', '')->append("\n");

        return $content;
    }

    public function getLines()
    {
        return $this->lines;
    }

    public function hasLanguage()
    {
        return ! is_null($this->language);
    }

    public function getLanguage()
    {
        return $this->language;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->visitCodeBlock($this);
    }

}

<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;

class CodeBlock extends Node implements NodeAcceptorInterface
{

    /**
     * @var Collection
     */
    protected $lines;

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

    public function __construct(Text $text, $language = '')
    {
        $this->lines = new Collection([$text]);
        $this->language = $language;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        $this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', ''));

        return $this;
    }

    public function acceptCodeBlock(CodeBlock $codeBlock)
    {
        $codeBlock->lines->each(function (Text $line) {
            $this->lines->add($line);
        });

        return $this;
    }

    public function getContent()
    {
        $content = new Text($this->lines->join("\n"));

        // Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline.
        $content->replace('/(\n[ ]*)*$/', '')->append("\n");

        return $content;
    }

    public function getLines()
    {
        return $this->lines;
    }

    public function hasLanguage()
    {
        return ! empty($this->language);
    }

    public function getLanguage()
    {
        return $this->language;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->visitCodeBlock($this);
    }

}

Fix display of code block language where none is given.


<?php
/**
 * MustacheCake
 *
 * A Mustache implementation for CakePHP.
 *
 * @copyright     Copyright (c) Hanson Wong
 * @link          https://github.com/Dismounted/MustacheCake
 * @package       MustacheCake.Test.Case
 * @license       https://github.com/Dismounted/MustacheCake/blob/master/LICENSE Simplified BSD License
 */

/**
 * MustacheCake test suite.
 *
 * This suite runs all the available tests for MustacheCake.
 *
 * @package       MustacheCake.Test.Case
 */
class AllMustacheCakeTest extends CakeTestSuite {

}

<?php
/**
 * MustacheCake
 *
 * A Mustache implementation for CakePHP.
 *
 * @copyright     Copyright (c) Hanson Wong
 * @link          https://github.com/Dismounted/MustacheCake
 * @package       MustacheCake.Test.Case
 * @license       https://github.com/Dismounted/MustacheCake/blob/master/LICENSE Simplified BSD License
 */

/**
 * MustacheCake test suite.
 *
 * This suite runs all the available tests for MustacheCake.
 *
 * @package       MustacheCake.Test.Case
 */
class AllMustacheCakeTest extends CakeTestSuite {

	/**
	 * Define the tests for this suite.
	 *
	 * @return void
	 */
	public static function suite() {
		$path = CakePlugin::path('MustacheCake') . 'Test' . DS . 'Case';
		$suite = new CakeTestSuite('All MustacheCake Tests');
		$suite->addTestDirectoryRecursive($path);
		return $suite;
	}

}

Add test directories to suite definition.


<?php

namespace Forex\Bundle\EmailBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendEmailCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('email:send-email')
            ->setDescription('Sends an email')
            ->addArgument('email',    InputArgument::REQUIRED, 'The email address to send to')
            ->addArgument('template', InputArgument::REQUIRED, 'The template')
            ->addArgument('subject',  InputArgument::REQUIRED, 'The subject')
            ->addArgument('data',     InputArgument::OPTIONAL, 'The data for the template (JSON formatted)', '[]')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->getContainer()->get('forex.email_sender')
            ->sendToEmail(
                $input->getArgument('email'),
                $input->getArgument('subject'),
                $input->getArgument('template'),
                json_decode($input->getArgument('data'), true)
            );
    }
}

<?php

namespace Forex\Bundle\EmailBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendEmailCommand extends ContainerAwareCommand
{
    protected $manager;
    protected $em;

    protected function configure()
    {
        $this
            ->setName('email:send-email')
            ->setDescription('Sends an email')
            ->addArgument('email',    InputArgument::REQUIRED, 'The email address to send to')
            ->addArgument('template', InputArgument::REQUIRED, 'The template')
            ->addArgument('subject',  InputArgument::REQUIRED, 'The subject')
            ->addArgument('data',     InputArgument::OPTIONAL, 'The data for the template (JSON formatted)', '[]')
        ;
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();

        $this->em = $container->get('doctrine.orm.default_entity_manager');
        $this->manager = $container->get('forex.email_manager');
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->manager->sendToEmail(
            $input->getArgument('email'),
            $input->getArgument('subject'),
            $input->getArgument('template'),
            json_decode($input->getArgument('data'), true)
        );

        $this->em->flush();
    }
}

Update the send email command to use email manager


<?php
spl_autoload_register('webFrameworkAutoloader');

function webFrameworkAutoloader($class){

    $baseDir = str_replace("/include", "", dirname(__FILE__));

    if (file_exists($baseDir. "/include/misc/" . $class . ".class.php")){
        require_once $baseDir. "/include/misc/" . $class . ".class.php";
    }
}
?>

<?php
spl_autoload_register('webFrameworkAutoloader');

function webFrameworkAutoloader($className){

    $baseDir = str_replace("/include", "", dirname(__FILE__));

    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;

        $fileName = $fileName . $className . ".class.php";
    } else {
        $fileName = $className . ".class.php";
    }
    // $className = str_replace('_', DIRECTORY_SEPARATOR, $className);
    $fileName = $baseDir. "/include/misc/" . $fileName;

    require_once $fileName;
}
?>

Support for namespaces in local classes

Support for namespaces in local classes


<?php

namespace App\Actions;

use App\LaravelUi;
use App\Shell\Shell;

class ConfigureFrontendFramework
{
    use LamboAction;

    private $shell;

    private $laravelUi;

    public function __construct(Shell $shell, LaravelUi $laravelUi)
    {
        $this->shell = $shell;
        $this->laravelUi = $laravelUi;
    }

    public function __invoke()
    {
        if (! config('lambo.store.frontend')) {
            return;
        }

        $this->laravelUi->install();

        $this->logStep('Configuring frontend scaffolding');

        $process = $this->shell->execInProject('php artisan ui ' . config('lambo.store.frontend'));

        $this->abortIf(! $process->isSuccessful(), "Installation of UI scaffolding did not complete successfully.", $process);

        $this->info('UI scaffolding has been set to ' . config('lambo.store.frontend'));
    }
}

<?php

namespace App\Actions;

use App\Shell\Shell;

class ConfigureFrontendFramework
{
    use LamboAction;

    private $shell;

    private $laravelUi;

    public function __construct(Shell $shell, LaravelUi $laravelUi)
    {
        $this->shell = $shell;
        $this->laravelUi = $laravelUi;
    }

    public function __invoke()
    {
        if (! config('lambo.store.frontend')) {
            return;
        }

        $this->laravelUi->install();

        $this->logStep('Configuring frontend scaffolding');

        $process = $this->shell->execInProject('php artisan ui ' . config('lambo.store.frontend'));

        $this->abortIf(! $process->isSuccessful(), "Installation of UI scaffolding did not complete successfully.", $process);

        $this->info('UI scaffolding has been set to ' . config('lambo.store.frontend'));
    }
}

Fix improper namespace causing test to ignore App\Actions\LaravelUi and make no assertions against it.


<?php

require_once(__DIR__ . '/../GitHubObject.php');

class GitHubBranch extends GitHubObject
{
	/* (non-PHPdoc)
	 * @see GitHubObject::getAttributes()
	 */
	protected function getAttributes()
	{
		return array_merge(parent::getAttributes(), array(
			'name' => 'string'
		));
	}

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

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

<?php

require_once(__DIR__ . '/../GitHubObject.php');

class GitHubBranch extends GitHubObject
{
	/* (non-PHPdoc)
	 * @see GitHubObject::getAttributes()
	 */
	protected function getAttributes()
	{
		return array_merge(parent::getAttributes(), array(
			'name' => 'string',
			'commit' => 'GitHubCommit'
		));
	}

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

	/**
	 * @var GitHubGitCommit
	 */
	protected $commit;

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

	/**
	 * @return GitHubGitCommit
	 */
	public function getCommit()
	{
		return $this->commit;
	}
}

Add commit property to the Branch object


<?php
/**
 * Image Slider
 * ============
 * Build a Image Slider with Swipper.js
 */

// Default Vars
$classname = 'o-imageslider';
?>

<? // Build Element Block ?>
<figure class="<?= $classname; ?>" itemscope itemtype="http://schema.org/ImageGallery" role="presentation">
  <div class="<?= $classname; ?>__wrapper">
    <?php while( have_rows('photos') ) : the_row(); ?>
      <div class="<?= $classname; ?>__slide" itemscope itemtype="http://schema.org/ImageObject">
        <?php macro_mediaImageSet(get_sub_field('photo'), $classname.'__image', get_sub_field('ratio')); ?>

    <?php endwhile; ?>

  <div class="<?= $classname; ?>__pagination">

  <div class="<?= $classname; ?>__button-next">

  <div class="<?= $classname; ?>__button-prev">

<?php
/**
 * Image Slider
 * ============
 * Build a Image Slider with Swipper.js
 */

// Default Vars
$classname = 'o-imageslider';
$ratio = get_sub_field('ratio');
?>

<? // Build Element Block ?>
<figure class="<?= $classname; ?>" itemscope itemtype="http://schema.org/ImageGallery" role="presentation">
  <div class="<?= $classname; ?>__wrapper">
    <?php while( have_rows('photos') ) : the_row(); ?>
      <div class="<?= $classname; ?>__slide" itemscope itemtype="http://schema.org/ImageObject">
        <?php macro_mediaImageSet(get_sub_field('photo'), $classname.'__image', $ratio); ?>

    <?php endwhile; ?>

  <div class="<?= $classname; ?>__pagination">

  <div class="<?= $classname; ?>__button-next">

  <div class="<?= $classname; ?>__button-prev">

Fix Ratio Imageslider (wordpresss starter)


<?php

namespace Galileo\SettingBundle\Lib\Model;

interface SettingBagInterface
{
    /**
     * @param string $name
     * @param string|integer|boolean|null $default
     *
     * @return string
     *
     * @throws ValueCanNotBeAnObjectException When you add as $default object that can not be converted to string
     * @throws
     */
    public function get($name, $default = null);

    /**
     * @param string $name
     * @param string|integer|boolean|null $value
     *
     * @return void
     */
    public function set($name, $value);
}

Fix new line at the end of file

Fix new line at the end of file


<?php

namespace Keyteq\Keymedia\Util;

use Keyteq\Keymedia\API\Configuration;

class RequestBuilder
{
    public $config;

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

    public function buildRequest($url, $method = 'GET', array $parameters = array())
    {
        $request = new Request($this->config, new RequestSigner(), new RequestWrapper());
        $request->setMethod($method)->setUrl($url);

        foreach ($parameters as $name => $value) {
            $request->addQueryParameter($name, $value);
        }

        return $request;
    }
}

<?php

namespace Keyteq\Keymedia\Util;

use Keyteq\Keymedia\API\Configuration;
use Keyteq\Keymedia\API\Request;

class RequestBuilder
{
    public $config;

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

    public function buildRequest($url, $method = 'GET', array $parameters = array())
    {
        $request = new Request($this->config, new RequestSigner(), new RequestWrapper());
        $request->setMethod($method)->setUrl($url);

        foreach ($parameters as $name => $value) {
            $request->addQueryParameter($name, $value);
        }

        return $request;
    }
}

Add missing use statement for Request

Add missing use statement for Request


<?php

require_once("creature.php");
require_once("animal.php");

$a = new Animal();

<?php

// Autoloader
spl_autoload_register(function($className) {
    echo "autoloading $className\n";
    require_once("$className.php");
});

$a = new Animal();

Revert "no fatal when using require_once on creature and animal instead of"

Re-introduce fatal to HEAD

This reverts commit fcd7b50630fc353700988723631ceed8f8433d86.


<?php declare(strict_types=1);

namespace Symplify\PackageBuilder\Tests\Parameter\ParameterTypoProofreader;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symplify\PackageBuilder\Exception\Parameter\ParameterTypoException;
use Symplify\PackageBuilder\Tests\ContainerFactory;

final class ParameterTypoProofreaderTest extends TestCase
{
    /**
     * @var ContainerInterface
     */
    private $container;

    protected function setUp(): void
    {
        $this->container = (new ContainerFactory())->createWithConfig(__DIR__ . '/config.yml');
    }

    public function testConsole(): void
    {
        /** @var Application $application */
        $application = $this->container->get(Application::class);
        $application->setCatchExceptions(false);

        $this->expectException(ParameterTypoException::class);

        $application->run(new ArrayInput(['command' => 'list']));
    }
}

<?php declare(strict_types=1);

namespace Symplify\PackageBuilder\Tests\Parameter\ParameterTypoProofreader;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symplify\PackageBuilder\Exception\Parameter\ParameterTypoException;
use Symplify\PackageBuilder\Tests\ContainerFactory;

final class ParameterTypoProofreaderTest extends TestCase
{
    /**
     * @var ContainerInterface
     */
    private $container;

    protected function setUp(): void
    {
        $this->container = (new ContainerFactory())->createWithConfig(__DIR__ . '/config.yml');
    }

    public function testConsole(): void
    {
        /** @var Application $application */
        $application = $this->container->get(Application::class);
        $application->setCatchExceptions(false);

        $this->expectException(ParameterTypoException::class);
        $this->expectExceptionMessage('Parameter "parameters > typo" does not exist.
Use "parameters > correct" instead.');

        $application->run(new ArrayInput(['command' => 'list']));
    }
}

Improve param typo proofreader test

[PackageBuilder] Improve param typo proofreader test


<?php

namespace EasyRepository\t{{$mt=uniqid(true)}};

use PDO;
use EasySQL\Cursor;

@foreach ($files as $query)
class {{$query->getName()}}Repository
{
    protected $dbh;

    public function __construct(PDO $pdo)
    {
        $this->dbh = $pdo;
    }

    @foreach ($query->getMethods() as $name => $method)
    public function {{$name}}({{$method->getFunctionSignature()}})
    {
        $stmt = $this->dbh->prepare({{@$method->getSQL()}});
        $result = $stmt->execute({{$method->getCompact()}});
        @if ($method->isInsert())
            return $this->dbh->lastInsertId();
        @elif ($method->changeSchema())
            return true;
        @elif ($method->singleResult())
            @if ($method->mapAsObject())
                return $stmt->fetchObject({{ @$method->mapAsObject() }});
            @else
                return $stmt->fetch(PDO::FETCH_ASSOC);
            @end
        @else
            return new Cursor($stmt, {{ @$method->mapAsObject() }});
        @end
    }

    @end
}
@end

return function(PDO $pdo) {
    return [
        @foreach ($files as $query)
        {{@strtolower($query->getName())}} => new {{$query->getName()}}Repository($pdo),
        @end
    ];
};

<?php

namespace EasyRepository\t{{$mt=uniqid(true)}};

use PDO;
use EasySQL\Cursor;

@foreach ($files as $query)
class {{$query->getName()}}Repository
{
    protected $dbh;

    public function __construct(PDO $pdo)
    {
        $this->dbh = $pdo;
    }

    @foreach ($query->getMethods() as $name => $method)
    public function {{$name}}({{$method->getFunctionSignature()}})
    {
        $stmt = $this->dbh->prepare({{@$method->getSQL()}});
        $result = $stmt->execute({{$method->getCompact()}});
        @if ($method->isInsert())
            return $this->dbh->lastInsertId();
        @elif ($method->changeSchema())
            return true;
        @elif ($method->singleResult())
            @if ($method->mapAsObject())
                return $stmt->fetchObject({{ @$method->mapAsObject() }});
            @else
                return $stmt->fetch(PDO::FETCH_ASSOC);
            @end
        @else
            return $stmt;
        @end
    }

    @end
}
@end

return function(PDO $pdo) {
    return [
        @foreach ($files as $query)
        {{@strtolower($query->getName())}} => new {{$query->getName()}}Repository($pdo),
        @end
    ];
};

Return cursor instead of our own cursor

Return cursor instead of our own cursor


<?php
  if (is_guest()) {
    echo('
The guest account does not have a profile. If you register a personal account ');
    echo('you will be able to create you own quizzes and see your user information plus statistics here!
');
    echo('

');
    die;
  }

  # PREPROCESS INPUT
  $username = mysql_real_escape_string(canonical_username(get_client_username()));

  # EXECUTE QUERY
  $result = exec_query("SELECT * FROM qmtbl_users WHERE username='$username'");
  $profile = mysql_fetch_assoc($result);

?>

Profile

<a href="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>">
<img id="userImage" class="qmProfileImage" src="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>">

  Username

    <?php echo stripslashes($profile['username']) ?>

  Real name

    <?php echo stripslashes($profile['realname']) ?></span

  E-mail

    <?php echo stripslashes($profile['email']) ?>

<?php
  if (is_guest()) {
    echo('
The guest account does not have a profile. If you register a personal account ');
    echo('you will be able to create you own quizzes and see your user information plus statistics here!
');
    echo('

');
    die;
  }

  # PREPROCESS INPUT
  $username = mysql_real_escape_string(canonical_username(get_client_username()));

  # EXECUTE QUERY
  $result = exec_query("SELECT * FROM qmtbl_users WHERE username='$username'");
  $profile = mysql_fetch_assoc($result);

?>

Profile

<a href="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>">
<img id="userImage" class="qmProfileImage" src="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>">

  Username

    <?php echo stripslashes($profile['username']) ?>

  Real name

    <?php echo stripslashes($profile['realname']) ?>

  E-mail

    <?php echo stripslashes($profile['email']) ?>

Fix layout bug by properly closing SPAN element

The "E-mail" label ended up right of the "Real name" label earlier.


@extends(Config::get('Sentinel::config.layout'))

{{-- Web site Title --}}
@section('title')
@parent
Import People
@stop

{{-- Content --}}
@section('content')

Import People from CSV

Download sample CSV

        {{ Form::open(array('action' => 'PeopleController@import', 'files' => 'true')) }}

has('name')) ? 'has-error' : '' }}">
                {{ Form::label('csv', 'Import People') }}
                {{ Form::file('csv') }}

            {{ Form::submit('Upload', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}

@stop

@extends(Config::get('Sentinel::config.layout'))

{{-- Web site Title --}}
@section('title')
@parent
Import People
@stop

{{-- Content --}}
@section('content')

Import People from CSV

Download sample CSV

        {{ Form::open(array('action' => 'PeopleController@import', 'files' => 'true')) }}

has('csv')) ? 'has-error' : '' }}">
                {{ Form::label('csv', 'Import People') }}
                {{ Form::file('csv') }}

            {{ Form::submit('Upload', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}

@stop

Fix error check field name

Fix error check field name


<?php namespace GeneaLabs\LaravelGovernor\Listeners;

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

class CreatingListener
{
    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function handle(string $event, array $models)
    {
        collect($models)
            ->filter(function ($model) {
                return $model instanceof Model;
            })
            ->each(function ($model) {
                if (auth()->check()
                    && ! (property_exists($model, 'isGoverned')
                        && $model['isGoverned'] === false)
                ) {
                    $model->governor_created_by = auth()->user()->getKey();
                    $table = $model->getTable();

                    if (! Schema::hasColumn($table, 'governor_created_by')) {
                        Schema::table($table, function (Blueprint $table) {
                            $table->integer('governor_created_by')->unsigned()->nullable();
                        });
                    }
                }
            });
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Listeners;

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

class CreatingListener
{
    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function handle(string $event, array $models)
    {
        collect($models)
            ->filter(function ($model) {
                return $model instanceof Model;
            })
            ->each(function (Model $model) {
                if (auth()->check()
                    && ! (property_exists($model, 'isGoverned')
                        && $model['isGoverned'] === false)
                ) {
                    $model->governor_created_by = auth()->user()->getKey();
                    $table = $model->getTable();
                    $connection = $model
                        ->getConnection()
                        ->getName();

                    if (! Schema::connection($connection)->hasColumn($table, 'governor_created_by')) {
                        Schema::connection($connection)->table($table, function (Blueprint $table) {
                            $table->integer('governor_created_by')->unsigned()->nullable();
                        });
                    }
                }
            });
    }
}

Add functionality to work with models using different database connections


@extends('page::page-layouts.default')
@section('title', 'Laravel Pages')
@section('page')

@include('page::shared.header', ["class_name" => "landing bg-5"])

@include('page::shared.nav')

            Just add content...

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto.

@include('page::shared.footer')

@endsection

@push('styles')

@endpush
@push('scripts')

@endpush

@extends('page::page-layouts.default')
@section('title', 'Laravel Pages')
@section('body')

@include('page::shared.header', ["class_name" => "landing bg-5"])

@include('page::shared.nav')

            Just add content...

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto.

@include('page::shared.footer')

@endsection

@push('styles')

@endpush
@push('scripts')

@endpush

Change page section page - body

Change page section page - body


<?php

final class PhabricatorDivinerApplication extends PhabricatorApplication {

  public function getBaseURI() {
    return '/diviner/';
  }

  public function getFontIcon() {
    return 'fa-sun-o';
  }

  public function getName() {
    return pht('Diviner');
  }

  public function getShortDescription() {
    return pht('Documentation');
  }

  public function getTitleGlyph() {
    return "\xE2\x97\x89";
  }

  public function getRoutes() {
    return array(
      '/diviner/' => array(
        '' => 'DivinerMainController',
        'query/((?<key>[^/]+)/)?' => 'DivinerAtomListController',
        'find/' => 'DivinerFindController',
      ),
      '/book/(?P<book>[^/]+)/' => 'DivinerBookController',
      '/book/'.
        '(?P<book>[^/]+)/'.
        '(?P<type>[^/]+)/'.
        '(?:(?P<context>[^/]+)/)?'.
        '(?P<name>[^/]+)/'.
        '(?:(?P<index>\d+)/)?' => 'DivinerAtomController',
    );
  }

  public function getApplicationGroup() {
    return self::GROUP_UTILITIES;
  }

  public function getRemarkupRules() {
    return array(
      new DivinerSymbolRemarkupRule(),
    );
  }

}

<?php

final class PhabricatorDivinerApplication extends PhabricatorApplication {

  public function getBaseURI() {
    return '/diviner/';
  }

  public function getFontIcon() {
    return 'fa-sun-o';
  }

  public function getName() {
    return pht('Diviner');
  }

  public function getShortDescription() {
    return pht('Documentation');
  }

  public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
    return array(
      array(
        'name' => pht('Diviner User Guide'),
        'href' => PhabricatorEnv::getDoclink('Diviner User Guide'),
      ),
    );
  }

  public function getTitleGlyph() {
    return "\xE2\x97\x89";
  }

  public function getRoutes() {
    return array(
      '/diviner/' => array(
        '' => 'DivinerMainController',
        'query/((?<key>[^/]+)/)?' => 'DivinerAtomListController',
        'find/' => 'DivinerFindController',
      ),
      '/book/(?P<book>[^/]+)/' => 'DivinerBookController',
      '/book/'.
        '(?P<book>[^/]+)/'.
        '(?P<type>[^/]+)/'.
        '(?:(?P<context>[^/]+)/)?'.
        '(?P<name>[^/]+)/'.
        '(?:(?P<index>\d+)/)?' => 'DivinerAtomController',
    );
  }

  public function getApplicationGroup() {
    return self::GROUP_UTILITIES;
  }

  public function getRemarkupRules() {
    return array(
      new DivinerSymbolRemarkupRule(),
    );
  }

}

Add doclink for Diviner documentation

Add doclink for Diviner documentation

Summary: Fixes T7502.

Test Plan: Went to `/diviner/` and saw a link to the documentation at `/help/documentation/PhabricatorDivinerApplication/`.

Reviewers: #blessed_reviewers, epriestley

Reviewed By: #blessed_reviewers, epriestley

Subscribers: Korvin, epriestley

Maniphest Tasks: T7502

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


@extends('layouts.default')

@section('title')
Contact · Indiana Real Estate Exchangors, Inc.
@stop

@section('content')

    {{ Form::open(array('url' => 'contact')) }}

          Name:

          <input type="text" name="contact[name]" id="name" autofocus />

          E-Mail:

          <input type="email" name="contact[email]" id="email" required placeholder="example@example.com" />

          Subject:

          <input type="text" name="contact[subject]" id="subject" />

          Body:

          <textarea name="contact[comments]" id="comments" required></textarea>

        <input type="reset" value="Clear"> <input type="submit" value="Submit">

    {{ Form::close() }}

@stop

@extends('layouts.default')

@section('title')
Contact · Indiana Real Estate Exchangors, Inc.
@stop

@section('content')

    {{ Form::open(array('url' => 'contact')) }}

          Name:

          <input type="text" name="contact[name]" id="name" autofocus placeholder="Your Name"/>

          E-Mail:

          <input type="email" name="contact[email]" id="email" required placeholder="example@example.com" />

          Subject:

          <input type="text" name="contact[subject]" id="subject" placeholder="Subject of Contact Request (Can be left blank)." />

          Body:

          <textarea name="contact[comments]" id="comments" required placeholder="Details about your contact request."></textarea>

        <input type="reset" value="Clear"> <input type="submit" value="Submit">

    {{ Form::close() }}

@stop

Add some more placeholder text.

Add some more placeholder text.


<?php

namespace eien\Helpers;

use wataridori\SFS\SimpleFuzzySearch;

class BusSearch
{
    public function searchServices($query, Cached $cached)
    {
        $serviceObject = $cached->getAsArray('bus-services');

        $sfs = new SimpleFuzzySearch($serviceObject['services'], ['name']);
        $results = $sfs->search($query);

        return $results;
    }

    public function searchStops($query, Cached $cached)
    {
        $stopObject = $cached->getAsArray('bus-stops');

        $sfs = new SimpleFuzzySearch($stopObject, [
            'name',
            'no',
        ]);
        $results = $sfs->search($query);

        return $results;
    }
}

<?php

namespace eien\Helpers;

use wataridori\SFS\SimpleFuzzySearch;

class BusSearch
{
    public function searchServices($query, Cached $cached)
    {
        $serviceObject = $cached->getAsArray('bus-services');

        $sfs = new SimpleFuzzySearch($serviceObject['services'], [
            'name',
            'no',
        ]);
        $results = $sfs->search($query);

        return $results;
    }

    public function searchStops($query, Cached $cached)
    {
        $stopObject = $cached->getAsArray('bus-stops');

        $sfs = new SimpleFuzzySearch($stopObject, [
            'name',
            'no',
        ]);
        $results = $sfs->search($query);

        return $results;
    }
}

Allow no. to be searched as well

Allow no. to be searched as well


<?php

namespace App\Laravit;

interface SortableInterface
{
	public function scopeSort($query, $type);

    public function scopeHot($query);

    public function scopeNew($query);

    public function scopeOld($query);

    public function scopeTop($query);
}

Fix tab instead of spaces indent

Fix tab instead of spaces indent