<?php

namespace Spatie\Skeleton\Tests;

use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\Skeleton\SkeletonServiceProvider;

class TestCase extends Orchestra
{
    public function setUp(): void
    {
        parent::setUp();

        $this->withFactories(__DIR__.'/database/factories');
    }

    protected function getPackageProviders($app)
    {
        return [
            SkeletonServiceProvider::class,
        ];
    }

    public function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
        ]);

        /*
        include_once __DIR__.'/../database/migrations/create_skeleton_table.php.stub';
        (new \CreatePackageTable())->up();
        */
    }
}

<?php

namespace Spatie\Skeleton\Tests;

use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\Skeleton\SkeletonServiceProvider;

class TestCase extends Orchestra
{
    public function setUp(): void
    {
        parent::setUp();

        //
    }

    protected function getPackageProviders($app)
    {
        return [
            SkeletonServiceProvider::class,
        ];
    }

    public function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
        ]);

        /*
        include_once __DIR__.'/../database/migrations/create_skeleton_table.php.stub';
        (new \CreatePackageTable())->up();
        */
    }
}

Remove call to `withFactories` method

Remove call to `withFactories` method

See #66

I have kept the `setupUp` method in place for convenience.


@extends('layouts.app')

@section('content')

Dashboard

Create New Site

View Existing Sites

@endsection

Correct routing on home page

Correct routing on home page


<?php
/**
 * @version		$Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 * @copyright	Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.nooku.org
 */

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 */
class ComWeblinksControllerCategory extends ComDefaultControllerDefault
{
    protected function _actionGet(KCommandContext $context)
    {
        $view = $this->getView();

	    //Set the layout
        if($view instanceof KViewTemplate)
	    {
	        $layout = clone $view->getIdentifier();
	        $layout->package  = 'categories';
	        $layout->name     = $view->getLayout();

	        //Force re-creation of the filepath to load the category templates
	        $layout->filepath = '';

	        $view->setLayout($layout);
	    }

	    //Set the toolbar
	    if($this->isCommandable()) {
	        $this->setToolbar('admin::com.categories.controller.toolbar.'.$view->getName());
	    }

        return parent::_actionGet($context);
    }

    public function setModel($model)
    {
        $model = parent::setModel($model);
        $model->package = 'categories';

        return $model;
    }

	public function getRequest()
	{
		$this->_request['section'] = 'com_weblinks';
	    return $this->_request;
	}
}

<?php
/**
 * @version		$Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 * @copyright	Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.nooku.org
 */

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 */
class ComWeblinksControllerCategory extends ComCategoriesControllerCategory
{

}

Extend from new ComCategoriesControllerCategory controller.


<?php namespace Kyslik\ColumnSortable;

use Illuminate\Support\ServiceProvider;

class ColumnSortableServiceProvider extends ServiceProvider {

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([__DIR__ . '/../../config/columnsortable.php' => config_path('columnsortable.php')]);
        $this->mergeConfigFrom(__DIR__ . '/../../config/columnsortable.php', 'columnsortable');
        $this->registerBladeExtensions();
    }

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

    /**
     * Register Blade extensions.
     *
     * @return void
     */
    protected function registerBladeExtensions()
    {

        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();

        $blade->extend(function ($view, $compiler)
        {
            $pattern = $compiler->createMatcher('sortablelink');

            $replace = '<?php echo \Kyslik\ColumnSortable\Sortable::link(array $2);?>';

            return preg_replace($pattern, $replace, $view);
        });

    }

}

<?php namespace Kyslik\ColumnSortable;

use Illuminate\Support\ServiceProvider;

class ColumnSortableServiceProvider extends ServiceProvider {

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([__DIR__ . '/../../config/columnsortable.php' => config_path('columnsortable.php')]);
        $this->registerBladeExtensions();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../../config/columnsortable.php', 'columnsortable');
    }

    /**
     * Register Blade extensions.
     *
     * @return void
     */
    protected function registerBladeExtensions()
    {

        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();

        $blade->extend(function ($view, $compiler)
        {
            $pattern = $compiler->createMatcher('sortablelink');

            $replace = '<?php echo \Kyslik\ColumnSortable\Sortable::link(array $2);?>';

            return preg_replace($pattern, $replace, $view);
        });

    }

}

Move mergeConfigFrom to register method

Move mergeConfigFrom to register method

According to http://laravel.com/docs/5.0/packages#configuration it should be in register() and not in boot()


<?php

namespace Styleguide\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class HeroContainedTextController extends Controller
{
    /**
     * Display the full width hero view.
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        // Set this controller in the allowed controllers list
        config([
            'base.hero_text_controllers' => ['HeroContainedTextController'],
        ]);

        // Remove the link from hero images
        $request->data['hero'] = collect($request->data['hero'])
            ->transform(function ($item) {
                $item['link'] = '';

                return $item;
            })
            ->toArray();

        return view('styleguide-childpage', merge($request->data));
    }
}

<?php

namespace Styleguide\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class HeroContainedTextController extends Controller
{
    /**
     * Display the full width hero view.
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        // Set this controller in the allowed controllers list
        config([
            'base.hero_text_controllers' => ['HeroContainedTextController'],
        ]);

        // Remove the link from hero images
        $request->data['hero'] = collect($request->data['hero'])
            ->transform(function ($item) {
                $item['description'] = strip_tags($item['description'], 'a');

                return $item;
            })
            ->toArray();

        return view('styleguide-childpage', merge($request->data));
    }
}

Remove the link since it was added to the description now


<?php

require_once __DIR__.'/../example/init.inc.php';

<?php

(include_once __DIR__.'/../vendor/autoload.php') OR die(PHP_EOL.'ERROR: composer autoloader not found, run "composer install" or see README for instructions'.PHP_EOL);

Use composer autoloader (or complain if missing)


<?php
use ThibaudDauce\EloquentInheritanceStorage\ParentTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Foundation\Testing\TestCase;
use ThibaudDauce\EloquentInheritanceStorage\InheritanceStorage;
use ThibaudDauce\EloquentInheritanceStorage\Facades\InheritanceStorage as FacadeInheritanceStorage;

class InheritanceStorageTest extends TestCase {

  public $warrior;
  public $wizard;
  public $character;
  public $characterCustomStorage;

  /**
   * Creates the application.
   *
   * @return \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  public function createApplication()
  {
    $unitTesting = true;

    $testEnvironment = 'testing';

    return require __DIR__.'/../../../../../bootstrap/start.php';
  }

  public function setUp()
  {
    parent::setUp();

    // Build some objects for our tests
    $this->character              = new Character;
    $this->warrior                = new Warrior;
    $this->wizard                 = new Wizard;
    $this->characterCustomStorage = new CharacterCustomStorage;
  }

  public function tearDown()
  {
    //
  }

  public function testInheritanceStorageActivation()
  {
    $this->assertTrue(InheritanceStorage::$activated);
    FacadeInheritanceStorage::desactivate();
    $this->assertFalse(InheritanceStorage::$activated);
    FacadeInheritanceStorage::activate();
    $this->assertTrue(InheritanceStorage::$activated);
  }

  public function testActionOnStorage()
  {
    $storageTable = FacadeInheritanceStorage::actionOnStorage(function() {
      $character = new Character;
      return $character->getTable();
    });
    $this->assertEquals('characters_storage', $storageTable);

    $character = new Character;
    $notStorageTable = $character->getTable();
    $this->assertNotEquals('characters_storage', $notStorageTable);
  }
}

<?php
use ThibaudDauce\EloquentInheritanceStorage\InheritanceStorage;

class InheritanceStorageTest extends PHPUnit_Framework_TestCase {

  public $character;
  public $inheritanceStorage;

  public function setUp()
  {
    parent::setUp();

    // Build some objects for our tests
    $this->character          = new Character;
    $this->inheritanceStorage = new InheritanceStorage;
  }

  public function tearDown()
  {
    //
  }

  public function testInheritanceStorageActivation()
  {
    $this->assertTrue(InheritanceStorage::$activated);
    $this->inheritanceStorage->desactivate();
    $this->assertFalse(InheritanceStorage::$activated);
    $this->inheritanceStorage->activate();
    $this->assertTrue(InheritanceStorage::$activated);
  }

  public function testActionOnStorage()
  {
    $storageTable = $this->inheritanceStorage->actionOnStorage(function() {
      $character = new Character;
      return $character->getTable();
    });
    $this->assertEquals('characters_storage', $storageTable);

    $character = new Character;
    $notStorageTable = $character->getTable();
    $this->assertNotEquals('characters_storage', $notStorageTable);
  }
}

Fix test case, remove Facade use for travis


<?php

    use PHPUnit\Framework\TestCase;

    require_once realpath(dirname(__FILE__).'/../Opbeat/client.php');

    class ClientTest extends TestCase {

        public function testGetErrorLevel() {
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_WARNING), 'warning');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_COMPILE_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_NOTICE), 'notice');
        }

    }

<?php

    use PHPUnit\Framework\TestCase;

    require_once dirname(dirname(__FILE__)).'/Opbeat/client.php';

    class ClientTest extends TestCase {

        public function testGetErrorLevel() {
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_WARNING), 'warning');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_COMPILE_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_NOTICE), 'notice');
        }

    }

FIX wrong inclusion in test

FIX wrong inclusion in test


<?php

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
    {{ registerNamespaces }}
));
$loader->registerPrefixes(array(
    {{ registerPrefixes }}
));
$loader->registerPrefixFallbacks(array(
    __DIR__.'/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs',
));
$loader->registerNamespaceFallbacks(array(
    __DIR__.'/../src',
));
$loader->register();

AnnotationRegistry::registerLoader(function($class) use ($loader) {
    $loader->loadClass($class);
    return class_exists($class, false);
});
AnnotationRegistry::registerFile(__DIR__.'/../vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');

{{ swiftmailer_autoload }}

<?php

use Symfony\Component\ClassLoader\UniversalClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
    {{ registerNamespaces }}
));
$loader->registerPrefixes(array(
    {{ registerPrefixes }}
));
$loader->registerPrefixFallbacks(array(
    __DIR__.'/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs',
));
$loader->registerNamespaceFallbacks(array(
    __DIR__.'/../src',
));
$loader->register();

AnnotationRegistry::registerLoader(function($class) use ($loader) {
    $loader->loadClass($class);
    return class_exists($class, false);
});
AnnotationRegistry::registerFile(__DIR__.'/../vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');

{{ swiftmailer_autoload }}

Add Missing use. Thanks to Stof

Add Missing use. Thanks to Stof


<?php namespace Orchestra\Support\Traits;

use Orchestra\Support\Str;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

trait UploadableTrait {

    /**
     * Save uploaded file into directory
     *
     * @param  use Symfony\Component\HttpFoundation\File\UploadedFile
     * @param  string $path
     * @return string
     */
    protected function save(UploadedFile $file, $path)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = Str::random(10).".{$extension}";

        $file->move($path, $filename);

        return $filename;
    }

    /**
     * Delete uploaded from directory
     *
     * @param  string $file
     * @return bool
     */
    protected function delete($file)
    {
        return File::delete($file);
    }

}

<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Orchestra\Support\Str;

trait UploadableTrait
{
    /**
     * Save uploaded file into directory.
     *
     * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $file
     * @param  string                                               $path
     * @return string
     */
    protected function saveUploadedFile(UploadedFile $file, $path)
    {
        $file->move($path, $filename = $this->getUploadedFilename($file));

        return $filename;
    }

    /**
     * Delete uploaded from directory
     *
     * @param  string $file
     * @return bool
     */
    protected function deleteUploadedFile($file)
    {
        return File::delete($file);
    }

    /**
     * Get uploaded filename.
     *
     * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $file
     * @return string
     */
    protected function getUploadedFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();

        return Str::random(10).".{$extension}";
    }
}

Use verbose method name to avoid conflict with implementing class.

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


<?php

namespace Faker\Provider\nl_BE;

class Payment extends \Faker\Provider\Payment
{
    /**
     * International Bank Account Number (IBAN)
     * @link http://en.wikipedia.org/wiki/International_Bank_Account_Number
     * @param  string  $prefix      for generating bank account number of a specific bank
     * @param  string  $countryCode ISO 3166-1 alpha-2 country code
     * @param  integer $length      total length without country code and 2 check digits
     * @return string
     */
    public static function bankAccountNumber($prefix = '', $countryCode = 'BE', $length = null)
    {
        return static::iban($countryCode, $prefix, $length);
    }
}

<?php

namespace Faker\Provider\nl_BE;

class Payment extends \Faker\Provider\Payment
{
    /**
     * International Bank Account Number (IBAN)
     * @link http://en.wikipedia.org/wiki/International_Bank_Account_Number
     * @param  string  $prefix      for generating bank account number of a specific bank
     * @param  string  $countryCode ISO 3166-1 alpha-2 country code
     * @param  integer $length      total length without country code and 2 check digits
     * @return string
     */
    public static function bankAccountNumber($prefix = '', $countryCode = 'BE', $length = null)
    {
        return static::iban($countryCode, $prefix, $length);
    }

    /**
     * Value Added Tax (VAT)
     *
     * @example 'BE0123456789', ('spaced') 'BE 0123456789'
     *
     * @see http://ec.europa.eu/taxation_customs/vies/faq.html?locale=en#item_11
     * @see http://www.iecomputersystems.com/ordering/eu_vat_numbers.htm
     * @see http://en.wikipedia.org/wiki/VAT_identification_number
     *
     * @param bool $spacedNationalPrefix
     *
     * @return string VAT Number
     */
    public static function vat($spacedNationalPrefix = true)
    {
        $prefix = ($spacedNationalPrefix) ? "BE " : "BE";
        return sprintf("%s0%d", $prefix, self::randomNumber(9, true));
    }
}

Add vat to the nl_BE provider

Add vat to the nl_BE provider

This code was found in the be_BE locale.


<?php

namespace mcordingley\ProbabilityDistribution\Discrete;

use mcordingley\ProbabilityDistribution\AbstractProbabilityDistribution;

abstract class AbstractDiscreteProbabilityDistribution extends AbstractProbabilityDistribution
{
    /* These versions of getCdf and getPpf are guaranteed to be correct for
     * all discrete distributions. In the case of certain distributions, it's
     * possible to find these values analytically. Where possible, that is
     * the preferred method of finding the values, as they should be more
     * performance.
     */

	public function getCdf($x)
    {
		$sum = 0;

		for ($count = 0; $count <= $x; $count++) {
			$sum += $this->getPdf($count);
		}

		return $sum;
	}

    public function getPpf($x)
    {
        if ($x >= 1) return INF; //Prevents infinite loops.

        $i = 0;
        $cdf = 0;

        while ($cdf < $x) {
            $cdf += $this->getPdf($i);
            $i++;
        }

        return $i - 1;
    }
}

<?php

namespace mcordingley\ProbabilityDistribution\Discrete;

use InvalidArgumentException;
use mcordingley\ProbabilityDistribution\AbstractProbabilityDistribution;

abstract class AbstractDiscreteProbabilityDistribution extends AbstractProbabilityDistribution
{
    /* These versions of getCdf and getPpf are guaranteed to be correct for
     * all discrete distributions. In the case of certain distributions, it's
     * possible to find these values analytically. Where possible, that is
     * the preferred method of finding the values, as they should be more
     * performant.
     */

	public function getCdf($x)
    {
		$sum = 0;

		for ($count = 0; $count <= $x; $count++) {
			$sum += $this->getPdf($count);
		}

		return $sum;
	}

    public function getPpf($x)
    {
        if ($x > 1) {
            throw new InvalidArgumentException('Cannot ask for the percent-point function of greater than 100% probability.');
        }

        $i = 0;
        $cdf = 0;

        while ($cdf < $x) {
            $cdf += $this->getPdf($i);
            $i++;
        }

        return $i - 1;
    }
}

Fix typo and throw exception.

Fix typo and throw exception.


<?php
/*
 * Copyright (c)
 * Kirill chEbba Chebunin <iam@chebba.org>
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.
 */

namespace EventBand\Transport\Amqp\Definition;

/**
 * Queue builder
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://opensource.org/licenses/mit-license.php MIT
 */
class QueueBuilder extends ModelBuilder implements QueueDefinition
{
    private $exclusive;

    private $arguments = array();

    /**
     * @return $this Provides the fluent interface
     */
    public function exclusive()
    {
        $this->exclusive = true;

        return $this;
    }

    public function isExclusive()
    {
        return $this->exclusive;
    }

    /**
     * @param array $arguments
     * @return $this
     */
    public function arguments($arguments = array())
    {
        $this->arguments = $arguments;

        return $this;
    }

    public function getArguments()
    {
        return $this->arguments;
    }

    /**
     * {@inheritDoc}
     */
    public function jsonSerialize()
    {
        return array_merge(parent::jsonSerialize(), [
            'exclusive' => $this->exclusive,
            'arguments' => $this->arguments,
        ]);
    }
}

<?php
/*
 * Copyright (c)
 * Kirill chEbba Chebunin <iam@chebba.org>
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.
 */

namespace EventBand\Transport\Amqp\Definition;

/**
 * Queue builder
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://opensource.org/licenses/mit-license.php MIT
 */
class QueueBuilder extends ModelBuilder implements QueueDefinition
{
    private $exclusive;

    private $arguments;

    /**
     * @return $this Provides the fluent interface
     */
    public function exclusive()
    {
        $this->exclusive = true;

        return $this;
    }

    public function isExclusive()
    {
        return $this->exclusive;
    }

    /**
     * @param array $arguments
     * @return $this
     */
    public function arguments($arguments = null)
    {
        $this->arguments = $arguments;

        return $this;
    }

    public function getArguments()
    {
        return $this->arguments;
    }

    /**
     * {@inheritDoc}
     */
    public function jsonSerialize()
    {
        return array_merge(parent::jsonSerialize(), [
            'exclusive' => $this->exclusive,
            'arguments' => $this->arguments,
        ]);
    }
}

Change default value to `null` as in \PhpAmqpLib\Channel\AMQPChannel::queue_declare


<?php

namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table;

use Bolt\Storage\Database\Schema\Table\BaseTable;

/**
 * Account table.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Account extends BaseTable
{
    /**
     * @inheritDoc
     */
    protected function addColumns()
    {
        $this->table->addColumn('guid',        'guid',       []);
        $this->table->addColumn('username',    'string',     ['length' => 32]);
        $this->table->addColumn('email',       'string',     ['length' => 128]);
        $this->table->addColumn('lastseen',    'datetime',   ['default' => '1900-01-01 00:00:00']);
        $this->table->addColumn('lastip',      'string',     ['length' => 32, 'notnull' => false, 'default' => '']);
        $this->table->addColumn('displayname', 'string',     ['length' => 32, 'notnull' => false]);
        $this->table->addColumn('enabled',     'boolean',    ['default' => 0]);
        $this->table->addColumn('roles',       'json_array', ['length' => 1024, 'default' => '']);
    }

    /**
     * @inheritDoc
     */
    protected function addIndexes()
    {
        $this->table->addUniqueIndex(['username']);
        $this->table->addUniqueIndex(['email']);

        $this->table->addIndex(['enabled']);
    }

    /**
     * @inheritDoc
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['guid']);
    }
}

<?php

namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table;

use Bolt\Storage\Database\Schema\Table\BaseTable;

/**
 * Account table.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Account extends BaseTable
{
    /**
     * @inheritDoc
     */
    protected function addColumns()
    {
        $this->table->addColumn('guid',        'guid',       []);
        $this->table->addColumn('email',       'string',     ['length'  => 128]);
        $this->table->addColumn('displayname', 'string',     ['length'  => 32, 'notnull' => false]);
        $this->table->addColumn('enabled',     'boolean',    ['default' => 0]);
        $this->table->addColumn('roles',       'json_array', ['length'  => 1024, 'notnull' => false]);
        $this->table->addColumn('lastseen',    'datetime',   ['default' => '']);
        $this->table->addColumn('lastip',      'string',     ['length'  => 32, 'notnull' => false]);
    }

    /**
     * @inheritDoc
     */
    protected function addIndexes()
    {
        $this->table->addUniqueIndex(['email']);

        $this->table->addIndex(['enabled']);
    }

    /**
     * @inheritDoc
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['guid']);
    }
}

Drop username as it will be used/available in meta


<?php

namespace OpsWay\ZohoBooks\Tests\Api;

use OpsWay\ZohoBooks\Api\BaseApi;
use OpsWay\ZohoBooks\Client;
use PHPUnit\Framework\TestCase;

class BaseApiTest extends TestCase
{
    const ORG_ID = 1;
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $client;
    /**
     * @var BaseApi
     */
    private $baseApi;

    public function setUp()
    {
        $this->client = $this->createMock(Client::class);
        $this->baseApi = new BaseApi($this->client, self::ORG_ID);
    }

    public function testGetList()
    {
        $filter = ['test' => '123'];
        $this->client->expects($this->once())
            ->method('getList')
            ->with('', self::ORG_ID, $filter)
            ->willReturn([
                's' => [ // List of item
                    ['id' => 1],
                    ['id' => 2],
                    ['id' => 3]
                ],
            ]);
        $list = $this->baseApi->getList($filter);
        // Test iterable list
        $this->assertTrue(is_array($list) || $list instanceof \Traversable);
        // Test foreach list
        foreach ($list as $key => $item) {
            $this->assertEquals($key+1, $item['id']);
        }
        // Test directly access list by key
        $this->assertEquals(1, $list[0]['id']);
    }
}

<?php

namespace OpsWay\ZohoBooks\Tests\Api;

use OpsWay\ZohoBooks\Api\BaseApi;
use OpsWay\ZohoBooks\Client;
use PHPUnit\Framework\TestCase;

class BaseApiTest extends TestCase
{
    const ORG_ID = 1;
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $client;
    /**
     * @var BaseApi
     */
    private $baseApi;

    public function setUp()
    {
        $this->client = $this->createMock(Client::class);
        $this->baseApi = new BaseApi($this->client, self::ORG_ID);
    }

    public function testGetList()
    {
        $filter = ['test' => '123'];
        $this->client->expects($this->once())
            ->method('getList')
            ->with('', self::ORG_ID, $filter)
            ->willReturn([
                's' => [ // List of item
                    ['id' => 1],
                    ['id' => 2],
                    ['id' => 3]
                ],
                'page_context' => [
                    'page' => 1,
                ]
            ]);
        $list = $this->baseApi->getList($filter);
        // Test iterable list
        $this->assertTrue(is_array($list) || $list instanceof \Traversable);
        // Test foreach list
        foreach ($list as $key => $item) {
            $this->assertEquals($key+1, $item['id']);
        }
        // Test directly access list by key
        $this->assertEquals(1, $list[0]['id']);
    }
}

Fix for client mock api (specify page_context by documentation)


<?php
namespace ScriptaVolent\service;

use ScriptaVolent\ServiceFactory;

class ScriptumService {

    private $scriptaRepository;

    function __construct() {
        $this->scriptaRepository = ServiceFactory::ScriptumRepository();
    }

    public function createScriptum($scriptum) {
        $scriptum->ref = $this->generateRef();
        return $this->scriptaRepository->insert($scriptum);
    }

    private function generateRef() {
        $alphabet = 'azertyuiopqsdfghjklmwxcvbn1234567890';
        $ref = '';
        for ($i = 0; $i < REF_SIZE; $i++) {
            $ref .= $alphabet[mt_rand(0, strlen($alphabet) - 1)];
        }

        return $ref;
    }

    public function read($id, $ref) {
        $scriptum = $this->scriptaRepository->get($id);

        if ($scriptum != null && $scriptum->ref === $ref) {
            if ($scriptum->onelife) {
                $this->scriptaRepository->delete($scriptum);
            }
            return $scriptum;
        } else {
            return null;
        }
    }

}

<?php
namespace ScriptaVolent\service;

use ScriptaVolent\ServiceFactory;

class ScriptumService {

    private $scriptaRepository;

    function __construct() {
        $this->scriptaRepository = ServiceFactory::ScriptumRepository();
    }

    public function createScriptum($scriptum) {
        $scriptum->ref = $this->generateRef();
        return $this->scriptaRepository->insert($scriptum);
    }

    private function generateRef() {
        $alphabet = 'azertyuiopqsdfghjklmwxcvbn1234567890';
        $ref = '';
        for ($i = 0; $i < REF_SIZE; $i++) {
            $ref .= $alphabet[mt_rand(0, strlen($alphabet) - 1)];
        }

        return $ref;
    }

    public function read($id, $ref) {
        $scriptum = $this->scriptaRepository->get($id);
        if ($scriptum != null && $scriptum->ref === $ref) {
            if ($scriptum->onelife) { // Can read one time
                $this->scriptaRepository->delete($scriptum);
                return $scriptum;
            } elseif ($scriptum->destruction < date('Y-m-d 00:00:00')) { // Can't read anymore
                $this->scriptaRepository->delete($scriptum);
                return null;
            } else { // Can read
                return $scriptum;
            }
        } else { // Scriptum not found, or ref mismatch
            return null;
        }
    }

}

Destroy a scriptum when reading it after destroy time


<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->_helper->redirector('index', 'movie');
    }

}

<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
    	if (Default_Model_User::getCurrent())
    	{
    		$this->_helper->redirector('index', 'movie');
    	}
    	else
    	{
    		$this->_helper->redirector('index', 'feed');
    	}
    }

}

FIX default on activity page for non-logged user (to avoid displaying always the same first user's list)


<?php

namespace LaravelLb;

use LaravelLb\LogicBoxes;

class LogicBoxesContact extends LogicBoxes {

    public $resource;

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

        $this->resource = "contacts";
    }

    /**
     * Getting list of the Contacts using Customer Id .
     * https://manage.netearthone.com/kb/answer/793
     *
     * @param LogicBoxesContact
     */
    public function search($parameters)
    {
      $method = 'search';
      $response = $this->get($this->resource, $method, $parameters);
      return $this;
    }

    /**
     * Getting Details of the Contact using Contact Id .
     * https://manage.netearthone.com/kb/answer/792
     *
     * @param LogicBoxesContact
     */
    public function details($contactId)
    {
        $method = 'details';
        $variables = [
            "contact-id" => $contactId,
        ];

        $response = $this->get($this->resource, $method, $variables);
        return $this;
    }
}

<?php

namespace LaravelLb;

use LaravelLb\LogicBoxes;

class LogicBoxesContact extends LogicBoxes {

    public $resource;

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

        $this->resource = "contacts";
    }

    /**
     * Getting list of the Contacts using Customer Id .
     * https://manage.netearthone.com/kb/answer/793
     *
     * @param LogicBoxesContact
     * @return $this
     */
    public function search($parameters)
    {
      $method = 'search';
      $response = $this->get($this->resource, $method, $parameters);
      return $this;
    }

    /**
     * Getting Details of the Contact using Contact Id .
     * https://manage.netearthone.com/kb/answer/792
     *
     * @param LogicBoxesContact
     * @return $this
     */
    public function details($contactId)
    {
        $method = 'details';
        $variables = [
            "contact-id" => $contactId,
        ];

        $response = $this->get($this->resource, $method, $variables);
        return $this;
    }

    /**
     * Add a new contact
     * Ref: https://manage.netearthone.com/kb/answer/790
     *
     * @return \LaravelLb\LogicBoxes
     */
    public function add($variables)
    {
        $method = "add";

        $variables = $this->encodeVariables($variables);

        return $this->post($this->resource, $method, $variables);
    }
}

Add new method to create contact.

Add new method to create contact.


<?php

namespace Konsulting\Laravel\RuleRepository;

use Konsulting\Laravel\RuleRepository\Contracts\RuleRepository;
use Konsulting\Laravel\RuleRepository\Exceptions\NonExistentStateException;

class RepositoryManager
{
    /**
     * The repository instance.
     *
     * @var RuleRepository
     */
    protected $repository;

    /**
     * Set the repository instance.
     *
     * @param RuleRepository $repository
     */
    public function __construct(RuleRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Return the rules for the given state. Get the default state if not specified.
     *
     * @param string $state
     * @return array
     * @throws NonExistentStateException
     */
    public function getRules($state = null)
    {
        $method = camel_case($state ?: 'default');

        if ( ! method_exists($this->repository, $method)) {
            throw new NonExistentStateException($method);
        }

        return array_merge(
            $this->repository->default(),
            is_array($this->repository->$method()) ? $this->repository->$method() : []
        );
    }
}

<?php

namespace Konsulting\Laravel\RuleRepository;

use Illuminate\Support\Str;
use Konsulting\Laravel\RuleRepository\Contracts\RuleRepository;
use Konsulting\Laravel\RuleRepository\Exceptions\NonExistentStateException;

class RepositoryManager
{
    /**
     * The repository instance.
     *
     * @var RuleRepository
     */
    protected $repository;

    /**
     * Set the repository instance.
     *
     * @param RuleRepository $repository
     */
    public function __construct(RuleRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Return the rules for the given state. Get the default state if not specified.
     *
     * @param string $state
     * @return array
     * @throws NonExistentStateException
     */
    public function getRules($state = null)
    {
        $method = Str::camel($state ?: 'default');

        if ( ! method_exists($this->repository, $method)) {
            throw new NonExistentStateException($method);
        }

        return array_merge(
            $this->repository->default(),
            is_array($this->repository->$method()) ? $this->repository->$method() : []
        );
    }
}

Swap out global function for static Str::camel() method


<?php

namespace Croogo\Core\Core\Exception;

class Exception extends \Cake\Core\Exception\Exception {

}

<?php

namespace Croogo\Core\Exception;

class Exception extends \Cake\Core\Exception\Exception {

}

Fix: Remove extraneous 'Core' in namespace definition


<?php

/**
 * @copyright Copyright © Mooza, mooza.ru, 2016
 * @package yii2-widgets
 * @subpackage yii2-widget-ilyabirman-likely
 * @version 1.0.0
 */

namespace mooza\likely;

use yii\web\AssetBundle;

/**
 * Asset bundle for Likely Widget
 *
 * @author Mooza <info@mooza.ru>
 * @since 1.0
 */
class LikelyAsset extends AssetBundle
{
    /**
     * @inheritdoc
     */
    public $sourcePath = '@vendor/bower/ilyabirman-likely/release';

    /**
     * @inheritdoc
     */
    public $js = [
        'likely.js',
        'likely-commonjs.js',
    ];

    /**
     * @inheritdoc
     */
    public $css = [
        'likely.css',
    ];
}

<?php

/**
 * @copyright Copyright © Mooza, mooza.ru, 2016
 * @package yii2-widgets
 * @subpackage yii2-likely
 * @version 1.0.0
 */

namespace mooza\likely;

use yii\web\AssetBundle;

/**
 * Asset bundle for Likely Widget
 *
 * @author Mooza <info@mooza.ru>
 * @since 1.0
 */
class LikelyAsset extends AssetBundle
{
    /**
     * @inheritdoc
     */
    public $sourcePath = '@vendor/bower/ilyabirman-likely/release';

    /**
     * @inheritdoc
     */
    public $js = [
        'likely.js',
        'likely-commonjs.js',
    ];

    /**
     * @inheritdoc
     */
    public $css = [
        'likely.css',
    ];
}

Update widget name to "yii2-likely"

Update widget name to "yii2-likely"


<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Tools
 *
 * @ORM\Entity
 * @ORM\Table(name="tools")
 */
class Tool
{
	/**
	 * @var integer
	 *
	 * @ORM\Column(name="id", type="integer")
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	private $id;

	/**
	 * @ORM\Column(type="string")
	 */
	protected $name;

	/**
	 * @ORM\Column(type="string")
	 */
	protected $level;

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

	/* -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- */

	/**
	 * Set name
	 *
	 * @param string $name
	 * @return Language
	 */
	public function setName($name)
	{
		$this->name = $name;

		return $this;
	}

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

	/* -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- */

	/**
	 * Set level
	 *
	 * @param string $level
	 * @return Language
	 */
	public function setLevel($level)
	{
		$this->level = $level;

		return $this;
	}

	/**
	 * Get level
	 *
	 * @return string
	 */
	public function getLevel()
	{
		return $this->level;
	}
}

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Tools
 *
 * @ORM\Entity
 * @ORM\Table(name="tools")
 */
class Tool extends Skill
{
}

Revert "Fix skills and tools bug"

Revert "Fix skills and tools bug"

This reverts commit 49fccd214e8d148d370fc2bf56052133c96a38f3.

This commit wasn't necessary.


<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initViewHeadTitle()
    {
        $this->bootstrap('view');
        /* @var $view Zend_View_Abstract */
        $view = $this->getResource('view');
        $view->headTitle()->setSeparator(' :: ');
        $view->headTitle()->prepend('Postr');
    }

    protected function _initPagination()
    {
        Zend_View_Helper_PaginationControl::setDefaultViewPartial(
            'paginator.phtml'
        );
    }

    protected function _initNavigation()
    {
        $this->bootstrap('frontController');
        $pages = array(
            array(
                'label'         => 'Home',
                'id'            => 'index',
                'action'        => 'index',
                'controller'    => 'index',
            ),
            array(
                'label'         => 'Entries',
                'id'            => 'entry',
                'action'        => 'index',
                'controller'    => 'entry',
            ),
        );
        $resource = new Zend_Application_Resource_Navigation(
            array(
                'pages' => $pages,
            )
        );
        $resource->setBootstrap($this);
        return $resource->init();
    }
}

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initViewHeadTitle()
    {
        $this->bootstrap('view');
        /* @var $view Zend_View_Abstract */
        $view = $this->getResource('view');
        $view->headTitle()->setSeparator(' :: ');
        $view->headTitle()->prepend('Postr');
    }

    protected function _initPagination()
    {
        Zend_View_Helper_PaginationControl::setDefaultViewPartial(
            'paginator.phtml'
        );
    }

    protected function _initNavigation()
    {
        $this->bootstrap('frontController');
        $pages = array(
            array(
                'label'         => 'Home',
                'id'            => 'index',
                'action'        => 'index',
                'controller'    => 'index',
            ),
            array(
                'label'         => 'Entries',
                'id'            => 'entry',
                'action'        => 'index',
                'controller'    => 'entry',
                'pages'         => array(
                    array(
                        'action'        => 'get',
                        'controller'    => 'entry',
                        'visible'       => false,
                    ),
                    array(
                        'action'        => 'post',
                        'controller'    => 'entry',
                        'visible'       => false,
                    ),
                    array(
                        'action'        => 'put',
                        'controller'    => 'entry',
                        'visible'       => false,
                    ),
                    array(
                        'action'        => 'delete',
                        'controller'    => 'entry',
                        'visible'       => false,
                    ),
                ),
            ),
        );
        $resource = new Zend_Application_Resource_Navigation(
            array(
                'pages' => $pages,
            )
        );
        $resource->setBootstrap($this);
        return $resource->init();
    }
}

Add subordinate pages to Entry page in navigation.


<?php
/**
 * Ustream.php
 *
 * @package Providers
 * @author Michael Pratt <pratt@hablarmierda.net>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Providers;

/**
 * The ustream.tv|com Provider
 * @link http://ustream.tv
 */
class Ustream extends \Embera\Adapters\Service
{
    /** inline {@inheritdoc} */
    protected $apiUrl = 'http://www.ustream.tv/oembed';

    /** inline {@inheritdoc} */
    protected function validateUrl()
    {
        $this->url->stripLastSlash();
        $this->url->invalidPattern('ustream\.(?:com|tv)/(?:explore|howto|upcomming|our-company|services|premium-membership|search)$');

        return (preg_match('~ustream\.(?:com|tv)/channel/(?:[\w\d\-_]+)$~i', $this->url) ||
                preg_match('~ustream\.(?:com|tv)/(?:[\w\d\-_]+)$~i', $this->url));
    }
}

?>

<?php
/**
 * Ustream.php
 *
 * @package Providers
 * @author Michael Pratt <pratt@hablarmierda.net>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Providers;

/**
 * The ustream.tv|com Provider
 * @link http://ustream.tv
 */
class Ustream extends \Embera\Adapters\Service
{
    /** inline {@inheritdoc} */
    protected $apiUrl = 'http://www.ustream.tv/oembed';

    /** inline {@inheritdoc} */
    protected function validateUrl()
    {
        $this->url->stripLastSlash();
        $this->url->invalidPattern('ustream\.(?:com|tv)/(?:explore|howto|upcomming|our-company|services|premium-membership|search)$');

        return (preg_match('~ustream\.(?:com|tv)/channel/(?:[\w\d\-_]+)$~i', $this->url) ||
                preg_match('~ustream\.(?:com|tv)/recorded/(?:[\w\d\-_]+)$~i', $this->url) ||
                preg_match('~ustream\.(?:com|tv)/(?:[\w\d\-_]+)$~i', $this->url));
    }
}

Add support for UStream recorded schema

Add support for UStream recorded schema


<?php

/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */
class RoboFile extends \Robo\Tasks {

  /**
   * Run Behat Tests.
   */
  public function behat() {
    $this->taskBehat(__DIR__ . '/vendor/bin/behat')
         ->format( 'pretty' )
         ->config( __DIR__ . '/tests/behat-pantheon.yml' )
         ->colors()
         ->noInteraction()
         ->run();
  }

  /**
   * Run Unit Tests for all *custom* modules.
   */
  public function unit() {
    $this->taskPHPUnit(__DIR__ . '/vendor/bin/phpunit')
         ->configFile(__DIR__ . '/web/core/phpunit.xml.dist')
         ->files( __DIR__ . '/web/modules/custom/**/tests/' )
         ->run();
  }

  /**
   * Lint custom modules and themes with Drupal coding standards.
   */
  public function lint() {
    $this->taskExec(__DIR__ . '/vendor/bin/phpcbf')
         ->rawArg('--standard=Drupal')
         ->rawArg('--ignore=web/themes/custom/**/node_modules')
         ->rawArg('-n web/modules/custom/* web/themes/custom/*')
         ->run();
  }

  /**
   * Run *full* test suite.
   */
  public function test() {
    $this->lint();
    $this->unit();
    $this->behat();
  }
}

<?php

/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */
class RoboFile extends \Robo\Tasks {

  /**
   * Run Behat Tests.
   */
  public function behat() {
    $this->_exec(__DIR__ . '/vendor/bin/drush --root=./web cim -y');
    $this->_exec(__DIR__ . '/vendor/bin/drush --root=./web updb -y');
    $this->taskBehat(__DIR__ . '/vendor/bin/behat')
         ->format( 'pretty' )
         ->config( __DIR__ . '/tests/behat-pantheon.yml' )
         ->colors()
         ->noInteraction()
         ->run();
  }

  /**
   * Run Unit Tests for all *custom* modules.
   */
  public function unit() {
    $this->taskPHPUnit(__DIR__ . '/vendor/bin/phpunit')
         ->configFile(__DIR__ . '/web/core/phpunit.xml.dist')
         ->files( __DIR__ . '/web/modules/custom/**/tests/' )
         ->run();
  }

  /**
   * Lint custom modules and themes with Drupal coding standards.
   */
  public function lint() {
    $this->taskExec(__DIR__ . '/vendor/bin/phpcbf')
         ->rawArg('--standard=Drupal')
         ->rawArg('--ignore=web/themes/custom/**/node_modules')
         ->rawArg('-n web/modules/custom/* web/themes/custom/*')
         ->run();
  }

  /**
   * Run *full* test suite.
   */
  public function test() {
    $this->lint();
    $this->unit();
    $this->behat();
  }
}

Make sure config/db is up to date before running tests!


@component('mail::message')
# {{ trans('orchestra/foundation::email.register.title') }}

{{ trans('orchestra/foundation::email.register.message.intro') }}

{{ trans('orchestra/foundation::email.register.message.email', \compact('email')) }}

@unless(is_null($password))
{{ trans('orchestra/foundation::email.register.message.password', \compact('password')) }}
@endunless

Thanks,<br>
{{ memorize('site.name') }}
@endcomponent

@component('mail::message')
# {{ trans('orchestra/foundation::email.register.title') }}

{{ trans('orchestra/foundation::email.register.message.intro') }}

{{ trans('orchestra/foundation::email.register.message.email', \compact('email')) }}

@unless(is_null($password))
{{ trans('orchestra/foundation::email.register.message.password', \compact('password')) }}
@endunless

Thanks,

{{ memorize('site.name') }}
@endcomponent

Use <br> instead of <p>

Use
 instead of

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace Gl3n\SerializationGroupBundle;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Resolves groups and permissions
 */
class Resolver
{
    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var array
     */
    private $groups;

    /**
     * Constructor
     *
     * @param AuthorizationCheckerInterface $authorizationChecker
     * @param array                         $groups
     */
    public function __construct(AuthorizationCheckerInterface $authorizationChecker, array $groups)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->groups = $groups;
    }

    /**
     * Resolves group
     *
     * @param string $groupName
     *
     * @return array An array of group names
     */
    public function resolve($groupName)
    {
        $groupNames = [$groupName];

        if (isset($this->groups[$groupName])) {
            if (!$this->authorizationChecker->isGranted($this->groups[$groupName]['roles'])) {
                throw new AccessDeniedException(
                    sprintf('User has not the required role to use "%s" serialization group', $groupName)
                );
            }
            foreach ($this->groups[$groupName]['include'] as $includedGroupName) {
                $groupNames = array_merge($groupNames, $this->resolve($includedGroupName));
            }
        }

        return $groupNames;
    }
}

<?php

namespace Gl3n\SerializationGroupBundle;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Resolves groups and permissions
 */
class Resolver
{
    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var array
     */
    private $groups;

    /**
     * Constructor
     *
     * @param AuthorizationCheckerInterface $authorizationChecker
     * @param array                         $groups
     */
    public function __construct(AuthorizationCheckerInterface $authorizationChecker, array $groups)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->groups = $groups;
    }

    /**
     * Resolves group
     *
     * @param string $groupName
     *
     * @return array An array of group names
     */
    public function resolve($groupName)
    {
        $groupNames = [$groupName];

        if (isset($this->groups[$groupName])) {
            if (0 < count($this->groups[$groupName]['roles']) && !$this->authorizationChecker->isGranted($this->groups[$groupName]['roles'])) {
                throw new AccessDeniedException(
                    sprintf('User has not the required role to use "%s" serialization group', $groupName)
                );
            }
            foreach ($this->groups[$groupName]['include'] as $includedGroupName) {
                $groupNames = array_merge($groupNames, $this->resolve($includedGroupName));
            }
        }

        return $groupNames;
    }
}

Fix authorisation checking when 'roles' is empty


<?php
if (!defined('3DS_DEPOT')) die('Private area.');

// Define DB Constants
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', '3ds_depot');

// Define secure constants
define('COOKIE_PRIV', "");

// Define folder paths
define('SITE_ROOT', '');
define('TEMPLATES_ROOT', '')

// Define URL config
define('HTTP_SITE', '3ds-depot.dev');
define('FORCE_HTTPS', true); // Set this to false if you terminate SSL early.

Add new config constants for future proofing.


<?php

define( 'BOLT_BASE_DIR', dirname( __DIR__ ) );
define( 'BOLT_CONFIG_DIR', BOLT_BASE_DIR.'/config' );

require_once( '../vendor/bobdenotter/bolt/index.php' );

<?php

require_once( '../vendor/bobdenotter/bolt/index.php' );

Fix for latest version of Bolt

Fix for latest version of Bolt


<?php

namespace Coreplex\Navigator;

use ReflectionClass;
use Illuminate\Support\ServiceProvider;

class NavigatorServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/navigator.php' => config_path('navigator.php'),
        ]);

        $this->mergeConfigFrom(__DIR__ . '/../config/navigator.php', 'navigator');
    }

    /**
     * Regsiter the service provider.
     */
    public function register()
    {
        $this->registerStore();
        $this->registerNavigator();
    }

    /**
     * Register the data store to be used by navigator.
     */
    protected function registerStore()
    {
        $this->app['Coreplex\Navigator\Contracts\Store'] = $this->app->share(function ($app) {
            return (new ReflectionClass($app['config']['navigator']['store']))->newInstanceArgs([$app['config']['navigator']['menus']]);
        });
    }

    /**
     * Register the navigator instance.
     */
    protected function registerNavigator()
    {
        $this->app['Coreplex\Navigator\Contracts\Navigator'] = $this->app->share(function ($app) {
            return new Navigator(
                $app['Coreplex\Core\Contracts\Renderer'],
                $app['Coreplex\Navigator\Contracts\Store'],
                $app['config']['navigator']
            );
        });
    }
}

<?php

namespace Coreplex\Navigator;

use ReflectionClass;
use Illuminate\Support\ServiceProvider;

class NavigatorServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/navigator.php' => config_path('navigator.php'),
        ]);

        $this->mergeConfigFrom(__DIR__ . '/../config/navigator.php', 'navigator');
    }

    /**
     * Regsiter the service provider.
     */
    public function register()
    {
        $this->registerStore();
        $this->registerNavigator();
    }

    /**
     * Register the data store to be used by navigator.
     */
    protected function registerStore()
    {
        $this->app->singleton('Coreplex\Navigator\Contracts\Store', function($app) {
            return (new ReflectionClass($app['config']['navigator']['store']))->newInstanceArgs([$app['config']['navigator']['menus']]);
        });
    }

    /**
     * Register the navigator instance.
     */
    protected function registerNavigator()
    {
        $this->app->singleton('Coreplex\Navigator\Contracts\Navigator', function($app) {
            return new Navigator(
                $app['Coreplex\Core\Contracts\Renderer'],
                $app['Coreplex\Navigator\Contracts\Store'],
                $app['config']['navigator']
            );
        });
    }
}

Change shares to singleton in service provider


<?php

namespace Refinery29\ApiOutput\Resource;

use Refinery29\ApiOutput\Resource\Error\Error;
use Refinery29\ApiOutput\Resource\Error\ErrorCollection;
use Refinery29\ApiOutput\Resource\Link\LinkCollection;

abstract class ResourceFactory
{
    /**
     * @param array $data
     *
     * @return Result
     */
    public static function result(array $data)
    {
        return new Result($data);
    }

    /**
     * @return ErrorCollection
     */
    public static function errorCollection()
    {
        return new ErrorCollection();
    }

    /**
     * @param string $title
     * @param string $code
     *
     * @return Error
     */
    public static function error($title, $code)
    {
        return new Error($title, $code);
    }

    /**
     * @return LinkCollection
     */
    public static function linkCollection()
    {
        return new LinkCollection();
    }
}

<?php

namespace Refinery29\ApiOutput\Resource;

use Refinery29\ApiOutput\Resource\Error\Error;
use Refinery29\ApiOutput\Resource\Error\ErrorCollection;
use Refinery29\ApiOutput\Resource\Link\LinkCollection;

abstract class ResourceFactory
{
    /**
     * @param array $data
     *
     * @return Result
     */
    public static function result(array $data)
    {
        return new Result($data);
    }

    /**
     * @param array $errors
     * @return ErrorCollection
     */
    public static function errorCollection(array $errors = [])
    {
        return new ErrorCollection($errors);
    }

    /**
     * @param string $title
     * @param string $code
     *
     * @return Error
     */
    public static function error($title, $code)
    {
        return new Error($title, $code);
    }

    /**
     * @return LinkCollection
     */
    public static function linkCollection()
    {
        return new LinkCollection();
    }
}

Fix resource factory to reflect ErrorCollection constructor


<?php

declare(strict_types = 1);

/*
 * This file is part of the skeleton package.
 *
 * (c) Gennady Knyazkin <dev@gennadyx.tech>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gennadyx\Skeleton\Action;

use Gennadyx\Skeleton\Action\Traits\FilesystemAwareTrait;
use Gennadyx\Skeleton\Action\Traits\VarAwareTrait;
use Gennadyx\Skeleton\VarAwareInterface;

/**
 * Class CreateSourceDirectories
 *
 * @author Gennady Knyazkin <dev@gennadyx.tech>
 */
final class CreateSourceDirectories implements ActionInterface, VarAwareInterface
{
    use VarAwareTrait,
        FilesystemAwareTrait;

    /**
     * Execute action
     *
     * @return void
     * @throws \RuntimeException
     */
    public function execute()
    {
        foreach (['src', 'tests'] as $name) {
            $directory = $this->vars['root'].'/'.$name;

            if (!is_dir($directory)) {
                $this->fs->mkdir($directory);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority(): int
    {
        return 5;
    }
}

<?php

declare(strict_types = 1);

/*
 * This file is part of the skeleton package.
 *
 * (c) Gennady Knyazkin <dev@gennadyx.tech>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gennadyx\Skeleton\Action;

use Gennadyx\Skeleton\Action\Traits\FilesystemAwareTrait;
use Gennadyx\Skeleton\Action\Traits\VarAwareTrait;
use Gennadyx\Skeleton\VarAwareInterface;

/**
 * Class CreateSourceDirectories
 *
 * @author Gennady Knyazkin <dev@gennadyx.tech>
 */
final class CreateSourceDirectories implements ActionInterface, VarAwareInterface
{
    use VarAwareTrait,
        FilesystemAwareTrait;

    /**
     * Execute action
     *
     * @return void
     * @throws \RuntimeException
     */
    public function execute()
    {
        foreach (['src', 'tests'] as $name) {
            $directory = $this->vars['root'].'/'.$name;

            if (!is_dir($directory)) {
                $this->fs->mkdir($directory);
                $this->fs->touch(sprintf('%s/.gitkeep', $directory));
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority(): int
    {
        return 5;
    }
}

Add .gitkeep to /src and /tests directories


<?php
/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Component\Subscriber;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

class ORMInheritanceSubscriber implements EventSubscriber
{
    protected $map = array();

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

    public function getSubscribedEvents()
    {
        return array(
            'loadClassMetadata'
        );
    }

    public function loadClassMetadata($eventArgs)
    {
        $metadata = $eventArgs->getClassMetadata();

        if ($metadata->name !== 'Application\Sonata\ProductBundle\Entity\Product') {
            return;
        }

        $metadata->setDiscriminatorColumn(array('name' => 'type', 'type' => 'string', 'length' => 64));
        $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE);
        $metadata->setDiscriminatorMap($this->map);
    }
}

<?php
/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Component\Subscriber;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

class ORMInheritanceSubscriber implements EventSubscriber
{
    protected $map = array();

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

    public function getSubscribedEvents()
    {
        return array(
            'loadClassMetadata'
        );
    }

    public function loadClassMetadata($eventArgs)
    {
        $metadata = $eventArgs->getClassMetadata();

        if ($metadata->name !== 'Application\Sonata\ProductBundle\Entity\Product') {
            return;
        }

        $metadata->setDiscriminatorColumn(array('name' => 'product_type', 'type' => 'string', 'length' => 64));
        $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE);
        $metadata->setDiscriminatorMap($this->map);
    }
}

Rename type property in product_type

Rename type property in product_type


<?php

return [

    /*
     * Discord API token
     */
    'token' => '##API_TOKEN##',

    /*
     * Database path
     */
    'db_path' => __DIR__ . '/../storage/db.json',

    /*
     * Bot administrators
     */
    'admin' => [
        //
    ],

    /*
     * Channels used for broadcasting
     */
    'broadcast' => [
        '##GUILD_1_ID##' => [
            '##CHANNEL_1_ID##',
            '##CHANNEL_2_ID##',
        ],
    ],

    /*
     * Emojis
     *
     * The blank emoji is a transparent emoji used for alignments
     */
    'emojis' => [
        '##GUILD_1_ID##' => [
            ':rank1:' => '##ID##',
            ':rank2:' => '##ID##',
            ':rank3:' => '##ID##',
            ':rank4:' => '##ID##',
            ':rank5:' => '##ID##',
            ':rank6:' => '##ID##',
            ':rank7:' => '##ID##',
            ':blank:' => '##ID##',
        ],
    ],

];

<?php

return [

    /*
     * Discord API token
     */
    'token' => '##API_TOKEN##',

    /*
     * Database path
     */
    'db_path' => __DIR__ . '/../storage/db.json',

    /*
     * Bot administrators
     */
    'admin' => [
        //
    ],

    /*
     * Channels used for broadcasting
     */
    'broadcast' => [
        '##GUILD_1_ID##' => [
            '##CHANNEL_1_ID##',
            '##CHANNEL_2_ID##',
        ],
    ],

    /*
     * Emojis
     *
     * The blank emoji is a transparent emoji used for alignments
     *
     * To get the ID of an emoji, write it in any Discord chat prefixed with a backslash.
     * Example: \:rank1:
     */
    'emojis' => [
        '##GUILD_1_ID##' => [
            ':rank1:' => '##ID##',
            ':rank2:' => '##ID##',
            ':rank3:' => '##ID##',
            ':rank4:' => '##ID##',
            ':rank5:' => '##ID##',
            ':rank6:' => '##ID##',
            ':rank7:' => '##ID##',
            ':blank:' => '##ID##',
        ],
    ],

];

Comment about how to retrieve an emoji's ID


<?php
namespace Concrete\Package\VividStore\Controller\SinglePage\Checkout;
use Page;
use PageController;
use Core;
use \Concrete\Core\Localization\Service\CountryList;
use View;
use Package;
use User;

use \Concrete\Package\VividStore\Src\VividStore\Orders\Order as VividOrder;
use \Concrete\Package\VividStore\Src\VividStore\Customer\Customer as Customer;

defined('C5_EXECUTE') or die(_("Access Denied."));
class Complete extends PageController
{
    public function view()
    {
        $customer = new Customer();
        $order = VividOrder::getByID($customer->getLastOrderID());

        if(is_object($order)){
            $this->set("order",$order);
        } else {
            $this->redirect("/cart");
        }
        $pkg = Package::getByHandle('vivid_store');
        $packagePath = $pkg->getRelativePath();
        $this->addFooterItem(Core::make('helper/html')->javascript($packagePath.'/js/vivid-store.js','vivid-store'));
        $this->addHeaderItem(Core::make('helper/html')->css($packagePath.'/css/vivid-store.css','vivid-store'));
    }

}

<?php
namespace Concrete\Package\VividStore\Controller\SinglePage\Checkout;
use Page;
use PageController;
use Core;
use \Concrete\Core\Localization\Service\CountryList;
use View;
use Package;
use User;

use \Concrete\Package\VividStore\Src\VividStore\Orders\Order as VividOrder;
use \Concrete\Package\VividStore\Src\VividStore\Customer\Customer as Customer;

defined('C5_EXECUTE') or die(_("Access Denied."));
class Complete extends PageController
{
    public function view()
    {
        $customer = new Customer();
        $order = VividOrder::getByID($customer->getLastOrderID());

        if(is_object($order)){
            $this->set("order",$order);
        } else {
            $this->redirect("/cart");
        }
        $this->addFooterItem(Core::make('helper/html')->javascript('vivid-store.js','vivid_store'));
        $this->addHeaderItem(Core::make('helper/html')->css('vivid-store.css','vivid_store'));
    }

}

Fix asset path in checkout page

Fix asset path in checkout page


<?php

namespace Eschmar\TimeAgoBundle\DependencyInjection;

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

/**
 * {@inheritDoc}
 */
class Configuration implements ConfigurationInterface
{
    const ROOT_NODE = 'eschmar_time_ago';

    /**
     * {@inheritdoc}
     */
    public function getConfigiBuilder()
    {
        $treeBuilder = new TreeBuilder(static::ROOT_NODE);

        // BC layer for symfony/config 4.1 and older
        if (! \method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->root(static::ROOT_NODE);
        } else {
            $rootNode = $treeBuilder->getRootNode();
        }

        $treeBuilder->getRootNode()
            ->children()
                ->scalarNode('format')
                    ->defaultValue('r')
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Eschmar\TimeAgoBundle\DependencyInjection;

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

/**
 * {@inheritDoc}
 */
class Configuration implements ConfigurationInterface
{
    const ROOT_NODE = 'eschmar_time_ago';

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder(static::ROOT_NODE);

        // BC layer for symfony/config 4.1 and older
        if (! \method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->root(static::ROOT_NODE);
        } else {
            $rootNode = $treeBuilder->getRootNode();
        }

        $treeBuilder->getRootNode()
            ->children()
                ->scalarNode('format')
                    ->defaultValue('r')
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Update to new naming scheme

Update to new naming scheme


<?php

namespace League\Tactician\Tests\Handler\MethodNameInflector;

use League\Tactician\Handler\MethodNameInflector\ClassNameInflector;
use League\Tactician\Tests\Fixtures\Command\CompleteTaskCommand;
use League\Tactician\Tests\Fixtures\Handler\ConcreteMethodsHandler;
use CommandWithoutNamespace;
use PHPUnit\Framework\TestCase;

class ClassNameInflectorTest extends TestCase
{
    /**
     * @var ClassNameInflector
     */
    private $inflector;

    /**
     * @var object
     */
    private $mockHandler;

    protected function setUp()
    {
        $this->inflector = new ClassNameInflector();
        $this->handler = new ConcreteMethodsHandler();
    }

    public function testHandlesClassesWithoutNamespace()
    {
        $command = new CommandWithoutNamespace();

        $this->assertEquals(
            'commandWithoutNamespace',
            $this->inflector->inflect($command, $this->mockHandler)
        );
    }

    public function testHandlesNamespacedClasses()
    {
        $command = new CompleteTaskCommand();

        $this->assertEquals(
            'completeTaskCommand',
            $this->inflector->inflect($command, $this->mockHandler)
        );
    }
}

<?php

namespace League\Tactician\Tests\Handler\MethodNameInflector;

use League\Tactician\Handler\MethodNameInflector\ClassNameInflector;
use League\Tactician\Tests\Fixtures\Command\CompleteTaskCommand;
use League\Tactician\Tests\Fixtures\Handler\ConcreteMethodsHandler;
use CommandWithoutNamespace;
use PHPUnit\Framework\TestCase;

class ClassNameInflectorTest extends TestCase
{
    /**
     * @var ClassNameInflector
     */
    private $inflector;

    /**
     * @var object
     */
    private $mockHandler;

    protected function setUp()
    {
        $this->inflector = new ClassNameInflector();
        $this->mockHandler = new ConcreteMethodsHandler();
    }

    public function testHandlesClassesWithoutNamespace()
    {
        $command = new CommandWithoutNamespace();

        $this->assertEquals(
            'commandWithoutNamespace',
            $this->inflector->inflect($command, $this->mockHandler)
        );
    }

    public function testHandlesNamespacedClasses()
    {
        $command = new CompleteTaskCommand();

        $this->assertEquals(
            'completeTaskCommand',
            $this->inflector->inflect($command, $this->mockHandler)
        );
    }
}

Fix a test for class name inflector

Fix a test for class name inflector


<?php
/*
 * This file is part of Conversion.
 *
 * (c) 2013 Christoffer Niska
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Crisu83\Conversion\Quantity\DigitalInformation;

use Crisu83\Conversion\Quantity\Quantity;

/**
 * Class DigitalInformation
 * @package Crisu83\Conversion\Quantity\DigitalInformation
 */
class DigitalInformation extends Quantity
{
    /**
     * @var string native unit name
     */
    protected static $native = Unit::BYTE;

    /**
     * @var array conversion map (unit => native unit)
     */
    protected static $conversionMap = array(
        Unit::BIT       => 0.00012207,
        Unit::BYTE      => 0.000976563,
        Unit::KILOBIT   => 0.125,
        Unit::KILOBYTE  => 1,
        Unit::MEGABIT   => 128,
        Unit::MEGABYTE  => 1024,
        Unit::GIGABIT   => 131072,
        Unit::GIGABYTE  => 1.049e+6,
        Unit::TERABIT   => 1.342e+8,
        Unit::TERABYTE  => 1.074e+9,
        Unit::PETABIT   => 1.374e+11,
        Unit::PETABYTE  => 1.1e+12,
    );
}

<?php
/*
 * This file is part of Conversion.
 *
 * (c) 2013 Christoffer Niska
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Crisu83\Conversion\Quantity\DigitalInformation;

use Crisu83\Conversion\Quantity\Quantity;

/**
 * Class DigitalInformation
 * @package Crisu83\Conversion\Quantity\DigitalInformation
 */
class DigitalInformation extends Quantity
{
    /**
     * @var string native unit name
     */
    protected static $native = Unit::KILOBYTE;

    /**
     * @var array conversion map (unit => native unit)
     */
    protected static $conversionMap = array(
        Unit::BIT       => 0.00012207,
        Unit::BYTE      => 0.000976563,
        Unit::KILOBIT   => 0.125,
        Unit::KILOBYTE  => 1,
        Unit::MEGABIT   => 128,
        Unit::MEGABYTE  => 1024,
        Unit::GIGABIT   => 131072,
        Unit::GIGABYTE  => 1.049e+6,
        Unit::TERABIT   => 1.342e+8,
        Unit::TERABYTE  => 1.074e+9,
        Unit::PETABIT   => 1.374e+11,
        Unit::PETABYTE  => 1.1e+12,
    );
}

Fix native unit for the digital information quantity


<?php

final class PhabricatorSearchDateField
  extends PhabricatorSearchField {

  protected function newControl() {
    return new AphrontFormTextControl();
  }

  protected function getValueFromRequest(AphrontRequest $request, $key) {
    return $request->getStr($key);
  }

  public function getValueForQuery($value) {
    return $this->parseDateTime($value);
  }

  protected function validateControlValue($value) {
    if (!strlen($value)) {
      return;
    }

    $epoch = $this->parseDateTime($value);
    if ($epoch) {
      return;
    }

    $this->addError(
      pht('Invalid'),
      pht('Date value for "%s" can not be parsed.', $this->getLabel()));
  }

  protected function parseDateTime($value) {
    if (!strlen($value)) {
      return null;
    }

    return PhabricatorTime::parseLocalTime($value, $this->getViewer());
  }

  protected function newConduitParameterType() {
    return new ConduitEpochParameterType();
  }

}

<?php

final class PhabricatorSearchDateField
  extends PhabricatorSearchField {

  protected function newControl() {
    return new AphrontFormTextControl();
  }

  protected function getValueFromRequest(AphrontRequest $request, $key) {
    return $request->getStr($key);
  }

  public function getValueForQuery($value) {
    return $this->parseDateTime($value);
  }

  protected function validateControlValue($value) {
    if (!strlen($value)) {
      return;
    }

    $epoch = $this->parseDateTime($value);
    if ($epoch) {
      return;
    }

    $this->addError(
      pht('Invalid'),
      pht('Date value for "%s" can not be parsed.', $this->getLabel()));
  }

  protected function parseDateTime($value) {
    if (!strlen($value)) {
      return null;
    }

    // If this appears to be an epoch timestamp, just return it unmodified.
    // This assumes values like "2016" or "20160101" are "Ymd".
    if (is_int($value) || ctype_digit($value)) {
      if ((int)$value > 30000000) {
        return (int)$value;
      }
    }

    return PhabricatorTime::parseLocalTime($value, $this->getViewer());
  }

  protected function newConduitParameterType() {
    return new ConduitEpochParameterType();
  }

}

Correct an issue with epoch timestamps in Conduit

Summary:
Fixes T11375. Some validation code was mishandling raw epoch timestamps.

For numeric values larger than 29999999 (e.g., 2999-12-25, christmas 2999), assume the value is a timestamp.

Test Plan: Used `maniphest.search` to query for `modifiedStart`, got a better result set and saw the `dateModified` constraint in the query.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T11375

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


<?php
  use_helper('FrontEnd', 'Widgets');
  $num_stories = StoriesPeer::getStoriesCounts($sf_user->getUserId());
?>

My Stories

  <?php echo $num_stories->private ?> private
,
  <?php echo $num_stories->public ?> public

  (<?php echo $num_stories->total ?> total)

    <?php echo _bs_button_with_icon('Export to CSV', 'study/export', ['icon' => 'fa-file']) ?>

  <?php include_component('study', 'MyStoriesTable', ['stories_uid' => $sf_user->getUserId(), 'profile_page' => false]) ?>

<?php
  kk_globals_put('MYSTORIES_SORT_ACTIVE', $sort_active);
  kk_globals_put('MYSTORIES_SORT_OPTIONS', $sort_options);
?>

<?php
  use_helper('FrontEnd', 'Widgets');
  $num_stories = StoriesPeer::getStoriesCounts($sf_user->getUserId());
?>

My Stories

<?php if ($num_stories->total === 0): ?>

    This page will let you browse all the kanji stories you have edited in the <?= link_to('Study page', 'study/index'); ?>.

<?php else: ?>

    <?= $num_stories->private; ?> private
,
    <?= $num_stories->public; ?> public

    (<?= $num_stories->total; ?> total)

      <?= _bs_button_with_icon('Export to CSV', 'study/export', ['icon' => 'fa-file']); ?>

    <?php include_component('study', 'MyStoriesTable', [
      'stories_uid' => $sf_user->getUserId(),
      'profile_page' => false,
    ]); ?>

<?php endif; ?>

<?php
  kk_globals_put('MYSTORIES_SORT_ACTIVE', $sort_active);
  kk_globals_put('MYSTORIES_SORT_OPTIONS', $sort_options);
?>

Add empty state to My Stories (don't show empty table) + php-cs-fixer


<?php

class ChildProductSelectField extends OptionsetField {

    public function Field($properties = array()) {
		$source = $this->getSource();
		$odd = 0;
		$options = array();

		if($source) {
			foreach($source as $item) {
                $price = new Currency("Price");
                $price->setValue($item->Price);

                $price_diff = new Currency("PriceDiff");
                $price_diff->setValue($item->PriceDiff);

				$options[] = new ArrayData(array(
					'ID' => $item->ID,
					'Name' => $this->name,
					'Value' => $item->ID,
					'Title' => $item->Title,
					'isChecked' => $item->ID == $this->value,
					'isDisabled' => $this->disabled || in_array($item->ID, $this->disabledItems),
                    'Price' => $price,
                    'PriceDiff' => $price_diff
				));
			}
		}

		$properties = array_merge($properties, array(
			'Options' => new ArrayList($options)
		));

		return $this->customise($properties)->renderWith(
			$this->getTemplates()
		);
	}

}

<?php

class ChildProductSelectField extends OptionsetField {

    public function Field($properties = array()) {
		$source = $this->getSource();
		$odd = 0;
		$options = array();

		if($source) {
			foreach($source as $item) {
                $price = new Currency("Price");
                $price->setValue($item->Price);

                $price_diff = new Currency("PriceDiff");
                $price_diff->setValue($item->PriceDiff);

				$options[] = new ArrayData(array(
					'ID' => $item->ID,
					'Name' => $this->name,
					'Value' => $item->ID,
					'Title' => $item->Title,
					'isChecked' => $item->ID == $this->value,
					'isDisabled' => $this->disabled || in_array($item->ID, $this->disabledItems),
                    'Price' => $price,
                    'PriceDiff' => $price_diff
				));
			}
		}

		$properties = array_merge($properties, array(
			'Options' => new ArrayList($options)
		));

		return $this->customise($properties)->renderWith(
			$this->getTemplates()
		);
	}

	/**
	 * Get the source of this field as an array
	 *
	 * @return array
	 */
	public function getSourceAsArray()
	{
		$source = $this->getSource();
		if (is_array($source)) {
			return $source;
		} else {
			$sourceArray = array();
			foreach ($source as $item) {
				$sourceArray[$item->ID] = $item->Title;
			}
		}

		return $sourceArray;
	}

	/**
	 * {@inheritdoc}
	 */
	public function validate($validator) {
		if (!$this->value) {
			return true;
		}

		return parent::validate($validator);
	}

}

Update source array to fix issues caused by latest validator


<?php
namespace Devture\Bundle\LocalizationBundle\Translation;

use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;

class JsonFileLoader extends ArrayLoader implements LoaderInterface {

	public function load($resource, $locale, $domain = 'messages') {
		$messages = json_decode(file_get_contents($resource), 1);

		// empty file
		if (null === $messages) {
			$messages = array();
		}

		// not an array
		if (!is_array($messages)) {
			throw new \InvalidArgumentException(sprintf('The file "%s" must contain a JSON array.', $resource));
		}

		$catalogue = parent::load($messages, $locale, $domain);
		$catalogue->addResource(new FileResource($resource));

		return $catalogue;
	}

}

<?php
namespace Devture\Bundle\LocalizationBundle\Translation;

use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;

class JsonFileLoader extends ArrayLoader implements LoaderInterface {

	public function load($resource, $locale, $domain = 'messages') {
		$contents = file_get_contents($resource);

		$messages = array();
		if ($contents !== '') {
			$messages = json_decode($contents, 1);

			if (json_last_error() !== JSON_ERROR_NONE) {
				throw new \InvalidArgumentException(sprintf(
					'The file "%s" cannot be JSON-decoded: %s.',
					$resource,
					json_last_error_msg()
				));
			}
		}

		if (!is_array($messages)) {
			throw new \InvalidArgumentException(sprintf('The file "%s" must contain a JSON array.', $resource));
		}

		$catalogue = parent::load($messages, $locale, $domain);
		$catalogue->addResource(new FileResource($resource));

		return $catalogue;
	}

}

Throw friendly exception on unparseable JSON files

PHP 7 has become a little more picky about JSON parsing,
which made me stumble into a bug.

Some old file was somewhat-incorrectly encoded
(contained some long-space character or something),
which made PHP 7's JSON parser break.

The failure was silently ignored and the translation file
was not loaded, which shouldn't be the case.


<?php

namespace tests\Hateoas\Configuration;

use Hateoas\Configuration\Relation as RelationTested;
use tests\Test;

class Relation extends Test
{
    public function testConstructor()
    {
        $relation = new RelationTested('self', 'user_get');

        $this
            ->then()
                ->object($relation)
                    ->isInstanceOf('Hateoas\Configuration\Relation')
                ->string($relation->getName())
                    ->isEqualTo('self')
                ->string($relation->getHref())
                    ->isEqualTo('user_get')
                ->array($relation->getAttributes())
                    ->isEmpty()
        ;
    }
}

<?php

namespace tests\Hateoas\Configuration;

use tests\Test;
use Hateoas\Configuration\Relation as TestedRelation;

class Relation extends Test
{
    public function testConstructor()
    {
        $relation = new TestedRelation('self', 'user_get');

        $this
            ->object($relation)
                ->isInstanceOf('Hateoas\Configuration\Relation')
            ->string($relation->getName())
                ->isEqualTo('self')
            ->string($relation->getHref())
                ->isEqualTo('user_get')
            ->array($relation->getAttributes())
                ->isEmpty()
        ;
    }
}

Make the test feel a bit better

Make the test feel a bit better


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2017, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Add resolve target entities compiler pass
 */
class AddResolveTargetEntitiesPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasExtension('doctrine')) {
            return;
        }

        $resolveTargetEntities = [];

        foreach ($container->getExtensionConfig('darvin_admin') as $config) {
            if (!isset($config['entity_override'])) {
                continue;
            }
            foreach ($config['entity_override'] as $target => $replacement) {
                foreach (class_implements($target) as $interface) {
                    if ($interface === $target.'Interface') {
                        $resolveTargetEntities[$interface] = $replacement;
                    }
                }
            }
        }
        if (!empty($resolveTargetEntities)) {
            $container->prependExtensionConfig('doctrine', [
                'orm' => [
                    'resolve_target_entities' => $resolveTargetEntities,
                ],
            ]);
        }
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2017, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Add resolve target entities to resolve target entity listener compiler pass
 */
class AddResolveTargetEntitiesPass implements CompilerPassInterface
{
    const RESOLVE_TARGET_ENTITY_LISTENER_ID = 'doctrine.orm.listeners.resolve_target_entity';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition(self::RESOLVE_TARGET_ENTITY_LISTENER_ID)) {
            return;
        }

        $listenerDefinition = $container->getDefinition(self::RESOLVE_TARGET_ENTITY_LISTENER_ID);

        foreach ($container->getExtensionConfig('darvin_admin') as $config) {
            if (!isset($config['entity_override'])) {
                continue;
            }
            foreach ($config['entity_override'] as $target => $replacement) {
                foreach (class_implements($target) as $interface) {
                    if ($interface === $target.'Interface') {
                        $listenerDefinition->addMethodCall('addResolveTargetEntity', [
                            $interface,
                            $replacement,
                            [],
                        ]);
                    }
                }
            }
        }
    }
}

Add resolve target entity to listener instead of configuration in the add resolve target entities compiler pass.


<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        $ret = str_replace("src='/", "src='" . $domain . '/', $ret);
        $up = Kwf_Config::getValue('uniquePrefix');
        $up = $up ? $up.'-' : '';
        $class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
        $ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
        return $ret;
    }
}

<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        $ret = str_replace("src='/", "src='" . $domain . '/', $ret);
        $ret = str_replace('action="/', 'action="' . $domain . '/', $ret);
        $up = Kwf_Config::getValue('uniquePrefix');
        $up = $up ? $up.'-' : '';
        $class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
        $ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
        return $ret;
    }
}

Replace form action in integrator template

Used when having a search box without live search in Master Template


<?php

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

$app = new Silex\Application();

$app['debug'] = OPEN_BADGES_DEBUG_MODE;
$app->run();

<?php

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

$app = new Silex\Application();

$app['debug'] = OPEN_BADGES_DEBUG_MODE;
$app->run();

Use frontend-specific autoloader in front controller


<?php

use hipanel\helpers\Url;
use hipanel\modules\client\widgets\combo\SellerCombo;
use hipanel\widgets\PasswordInput;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin([
    'id' => 'client-form',
    'enableClientValidation' => true,
    'validateOnBlur' => true,
    'enableAjaxValidation' => true,
    'validationUrl' => Url::toRoute(['validate-form', 'scenario' => $model->isNewRecord ? 'create' : 'update']),
]);
?>

<?= $form->field($model, "client")->textInput() ?>
<?= $form->field($model, "email")->textInput() ?>
<?= $form->field($model, "password")->widget(PasswordInput::className()) ?>
<?= $form->field($model, "seller_id")->widget(SellerCombo::classname()) ?>

<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-default']) ?>

<?= Html::button(Yii::t('app', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
<?php $form->end() ?>

<?php

use hipanel\helpers\Url;
use hipanel\modules\client\widgets\combo\SellerCombo;
use hipanel\widgets\PasswordInput;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin([
    'id' => 'client-form',
    'enableClientValidation' => true,
    'validateOnBlur' => true,
    'enableAjaxValidation' => true,
    'validationUrl' => Url::toRoute(['validate-form', 'scenario' => $model->isNewRecord ? 'create' : 'update']),
]);
?>

<?= $form->field($model, "client")->textInput() ?>
<?= $form->field($model, "email")->textInput() ?>
<?= $form->field($model, "password")->widget(PasswordInput::className()) ?>
<?= $form->field($model, "seller_id")->widget(SellerCombo::classname()) ?>

<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>

<?= Html::button(Yii::t('app', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
<?php $form->end() ?>

Change color Save button in Client form

Change color Save button in Client form


#!/usr/bin/php -q
<?php
/**
 * Command-line code generation utility to automate programmer chores.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Console
 * @since         CakePHP(tm) v 1.2.0.5012
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
$root = dirname(dirname(dirname(__DIR__)));

// Default app directory layout
if (file_exists($root . '/App/Config/bootstrap.php')) {
	require $root . '/App/Config/bootstrap.php';
}
// TODO read ARGV for -app flag, and bootstrap that application.
return Cake\Console\ShellDispatcher::run($argv);

#!/usr/bin/php -q
<?php
/**
 * Command-line code generation utility to automate programmer chores.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Console
 * @since         CakePHP(tm) v 1.2.0.5012
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
$root = dirname(dirname(dirname(__DIR__)));
$loaded = false;

$appIndex = array_search('-app', $argv);
if ($appIndex !== false) {
	$loaded = true;
	$dir = $argv[$appIndex + 1];
	require $dir . '/Config/bootstrap.php';
}
// Default app directory layout
if (!$loaded && file_exists($root . '/App/Config/bootstrap.php')) {
	require $root . '/App/Config/bootstrap.php';
}
unset($root, $loaded, $appIndex, $dir);
return Cake\Console\ShellDispatcher::run($argv);

Make -app parameter work again.

Make -app parameter work again.


<?php
/**
 * Jetpack Compatibility File
 * See: http://jetpack.me/
 *
 * @package: _s
 */

/**
 * Add theme support for Infinite Scroll.
 * See: http://jetpack.me/support/infinite-scroll/
 */
function _s_infinite_scroll_setup() {
	add_theme_support( 'infinite-scroll', array(
		'container' => 'content',
		'footer'    => 'page',
	) );
}
add_action( 'after_setup_theme', '_s_infinite_scroll_setup' );

<?php
/**
 * Jetpack Compatibility File
 * See: http://jetpack.me/
 *
 * @package _s
 */

/**
 * Add theme support for Infinite Scroll.
 * See: http://jetpack.me/support/infinite-scroll/
 */
function _s_infinite_scroll_setup() {
	add_theme_support( 'infinite-scroll', array(
		'container' => 'content',
		'footer'    => 'page',
	) );
}
add_action( 'after_setup_theme', '_s_infinite_scroll_setup' );

Remove colon from @package DocBlock

Remove colon from @package DocBlock


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

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

return [
    'up' => function (Builder $schema) {
        $schema->create('posts_likes', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->primary(['post_id', 'user_id']);
        });
    },

    'down' => function (Builder $schema) {
        $schema->drop('posts_likes');
    }
];

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

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

return Migration::createTable(
    'posts_likes',
    function (Blueprint $table) {
        $table->integer('post_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->primary(['post_id', 'user_id']);
    }
);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php
namespace AppZap\PHPFramework\SignalSlot;

class CoreSlots {

  public function addFrameworkSignatureToOutput(&$output) {
    $output = preg_replace("/<head( (.)*?|)>/u", "<head$1>\n\t<!-- Powered by PHPFramework (https://github.com/app-zap/PHPFramework) -->", $output);
  }

}

<?php
namespace AppZap\PHPFramework\SignalSlot;

use AppZap\PHPFramework\Configuration\Configuration;

class CoreSlots {

  public static function addFrameworkSignatureToOutput(&$output) {
    if (Configuration::get('phpframework', 'powered_by', TRUE)) {
      $output = preg_replace("/<head( (.)*?|)>/u", "<head$1>\n\t<!-- Powered by PHPFramework (https://github.com/app-zap/PHPFramework) -->", $output);
    }
  }

}

Make inserting the PHPFramework html comment configurable


<?php

namespace Sober\Controller;

class Blade
{
    protected $data;

    /**
     * Set Data
     *
     * Remove other array items should last item not include tree
     */
    protected function setBladeData($data)
    {
        // Get __blade/__debugger key
        $this->data = $data['__data']['__blade'];

        // Get first item from data array
        $first = reset($this->data);

        // Get last item from data array
        if (count($this->data) > 1) {
            $last = end($this->data);
        }

        // If last item does not inherit tree and first class is App
        if (!$last->tree && $first->class === 'App') {
            // Rewrite $this->data with first (App) and last item in array
            $this->data = [$first, $last];
        // Else if $last does not inherit tree
        } elseif (!$last->tree) {
            // Rewrite $this->data with last item in array
            $this->data = $last;
        }

        return $this;
    }
}

<?php

namespace Sober\Controller;

class Blade
{
    protected $data;

    /**
     * Set Data
     *
     * Remove other array items should last item not include tree
     */
    protected function setBladeData($data)
    {
        // Get __blade/__debugger key
        $this->data = $data['__data']['__blade'];

        // Only worry about rewriting data if we have more than one class
        if (count($this->data) > 1) {
            // Get first item from data array
            $first = reset($this->data);

            // Get last item from data array
            $last = end($this->data);

            // If last item does not inherit tree and first class is App
            if (!$last->tree && $first->class === 'App') {
                // Rewrite $this->data with first (App) and last item in array
                $this->data = [$first, $last];
            // Else if $last does not inherit tree
            } elseif (!$last->tree) {
                // Rewrite $this->data with last item in array
                $this->data = $last;
            }
        }

        return $this;
    }
}

Move checking for tree inheritance inside count > 1 conditional to prevent issues when debugging with a single class