<?php

/*
 * This file is part of the Sonata Project 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\Exporter\Test;

use Sonata\Exporter\Writer\TypedWriterInterface;

/**
 * @author Grégoire Paris <postmaster@greg0ire.fr>
 */
abstract class AbstractTypedWriterTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var WriterInterface
     */
    private $writer;

    protected function setUp(): void
    {
        $this->writer = $this->getWriter();
    }

    public function testFormatIsString(): void
    {
        $this->assertInternalType('string', $this->writer->getFormat());
    }

    public function testDefaultMimeTypeIsString(): void
    {
        $this->assertInternalType('string', $this->writer->getDefaultMimeType());
    }

    /**
     * Should return a very simple instance of the writer (no need for complex
     * configuration).
     *
     * @return WriterInterface
     */
    abstract protected function getWriter(): TypedWriterInterface;
}

<?php

/*
 * This file is part of the Sonata Project 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\Exporter\Test;

use PHPUnit\Framework\TestCase;
use Sonata\Exporter\Writer\TypedWriterInterface;

/**
 * @author Grégoire Paris <postmaster@greg0ire.fr>
 */
abstract class AbstractTypedWriterTestCase extends TestCase
{
    /**
     * @var WriterInterface
     */
    private $writer;

    protected function setUp(): void
    {
        $this->writer = $this->getWriter();
    }

    public function testFormatIsString(): void
    {
        $this->assertInternalType('string', $this->writer->getFormat());
    }

    public function testDefaultMimeTypeIsString(): void
    {
        $this->assertInternalType('string', $this->writer->getDefaultMimeType());
    }

    /**
     * Should return a very simple instance of the writer (no need for complex
     * configuration).
     *
     * @return WriterInterface
     */
    abstract protected function getWriter(): TypedWriterInterface;
}

Migrate public test to phpunit 5

Migrate public test to phpunit 5


<?php
require '../vendor/autoload.php';
namespace Mini\Twig\Extension;

class GeshiExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'geshi' => new \Twig_Filter_Method($this, 'geshiHighlight'),
        );
    }

    public function geshiHighlight($source, $language)
    {
        $geshi = new \GeSHi($source, $language);
        $geshi->enable_classes();

        return $geshi->parse_code();
    }

    public function getName()
    {
        return 'geshi_highlight';
    }
}
?>

<?php
namespace Mini\Twig\Extension;

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

class GeshiExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'geshi' => new \Twig_Filter_Method($this, 'geshiHighlight'),
        );
    }

    public function geshiHighlight($source, $language)
    {
        $geshi = new \GeSHi($source, $language);
        $geshi->enable_classes();

        return $geshi->parse_code();
    }

    public function getName()
    {
        return 'geshi_highlight';
    }
}
?>

Fix namespace in twig extension

Fix namespace in twig extension


<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Tests\Mapping\Driver;

use Doctrine\Bundle\MongoDBBundle\Mapping\Driver\XmlDriver;

class XmlDriverTest extends AbstractDriverTest
{
    /**
     * @return string
     */
    protected function getFileExtension()
    {
        return '.mongodb.xml';
    }

    /**
     * @return string
     */
    protected function getFixtureDir()
    {
        return __DIR__ . '/Fixtures/xml';
    }

    /**
     * @return XmlDriver
     */
    protected function getDriver(array $prefixes = [])
    {
        return new XmlDriver($prefixes, $this->getFileExtension());
    }
}

<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Tests\Mapping\Driver;

use Doctrine\Bundle\MongoDBBundle\Mapping\Driver\XmlDriver;

class XmlDriverTest extends AbstractDriverTest
{
    /**
     * @return string
     */
    protected function getFileExtension()
    {
        return '.mongodb.xml';
    }

    /**
     * @return string
     */
    protected function getFixtureDir()
    {
        return __DIR__ . '/Fixtures/xml';
    }

    /**
     * @return XmlDriver
     */
    protected function getDriver(array $paths = [])
    {
        return new XmlDriver($paths, $this->getFileExtension());
    }
}

Change param name to match parent

Change param name to match parent


<?php

namespace hceudevs\RateLimitBundle\Service\Storage;

use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;

class Redis implements StorageInterface
{
    /**
     * @var \Predis\Client
     */
    protected $client;

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

    public function getRateInfo($key)
    {
        $info = $this->client->hgetall($key);

        $rateLimitInfo = new RateLimitInfo();
        $rateLimitInfo->setLimit($info['limit']);
        $rateLimitInfo->setCalls($info['calls']);
        $rateLimitInfo->setResetTimestamp($info['reset']);

        return $rateLimitInfo;
    }

    public function limitRate($key)
    {
        if (! $this->client->hexists($key, 'limit')) {
            return false;
        }

        $this->client->hincrby($key, 'calls', 1);

        return $this->getRateInfo($key);
    }

    public function createRate($key, $limit, $period)
    {
        $this->client->hset($key, 'limit', $limit);
        $this->client->hset($key, 'calls', 1);
        $this->client->hset($key, 'reset', time() + $period);
        $this->client->expire($key, $period);

        return $this->getRateInfo($key);
    }

    public function resetRate($key)
    {
        $this->client->hdel($key);
        return true;
    }
}

<?php

namespace hceudevs\RateLimitBundle\Service\Storage;

use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;

class Redis implements StorageInterface
{
    /**
     * @var \Predis\Client
     */
    protected $client;

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

    public function getRateInfo($key)
    {
        $info = $this->client->hgetall($key);

        $rateLimitInfo = new RateLimitInfo();
        $rateLimitInfo->setLimit($info['limit']);
        $rateLimitInfo->setCalls($info['calls']);
        $rateLimitInfo->setResetTimestamp($info['reset']);

        return $rateLimitInfo;
    }

    public function limitRate($key)
    {
        if (! $this->client->hexists($key, 'limit')) {
            return false;
        }

        $this->client->hincrby($key, 'calls', 1);

        return $this->getRateInfo($key);
    }

    public function createRate($key, $limit, $period)
    {
        $this->client->hset($key, 'limit', $limit);
        $this->client->hset($key, 'calls', 1);
        $this->client->hset($key, 'reset', time() + $period);
        $this->client->expire($key, $period);

        return $this->getRateInfo($key);
    }

    public function resetRate($key)
    {
        $this->client->hdel($key);
        return true;
    }
}

Revert "Revert "update to remove client type hinting""

This reverts commit 4442314687fb05190a7dd6dfeb58ae4a6c4e87e9.


Move DB Str import to single line so it can be completely cleaned up on site generation


<?php

/**
 * Solr data helper
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{

}

<?php

/**
 * Solr data helper
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{

	public function getProductDocumentId($productId) {
		// TODO replace ### with site hash
		$documentId = '###/product/' . $productId;

		return $documentId;
	}

}

Add helper method to create document IDs


<?php

namespace Laracasts\Generators\Commands;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;

class SeedMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:seed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new database seed class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Seed';

    /**
     * Parse the name and format according to the root namespace.
     *
     * @param  string $name
     * @return string
     */
    protected function parseName($name)
    {
        return ucwords(camel_case($name)) . 'TableSeeder';
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/../stubs/seed.stub';
    }

    /**
     * Get the destination class path.
     *
     * @param  string $name
     * @return string
     */
    protected function getPath($name)
    {
        return base_path() . '/database/seeds/' . str_replace('\\', '/', $name) . '.php';
    }
}

<?php

namespace Laracasts\Generators\Commands;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;

class SeedMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:seed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new database seed class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Seed';

    /**
     * Parse the name and format according to the root namespace.
     *
     * @param  string $name
     * @return string
     */
    protected function parseName($name)
    {
        return ucwords(camel_case($name)) . 'TableSeeder';
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/../stubs/seed.stub';
    }

    /**
     * Build the class with the given name.
     *
     * @param  string $name
     * @return string
     */
    protected function buildClass($name = null)
    {
        $stub = $this->files->get($this->getStub());

        return $this->replaceClass($stub, $name);
    }

    /**
     * Replace the class name for the given stub.
     *
     * @param  string  $stub
     * @param  string  $name
     * @return string
     */
    protected function replaceClass($stub, $name)
    {
        $stub = str_replace('{{class}}', $name, $stub);

        return $stub;
    }

    /**
     * Get the destination class path.
     *
     * @param  string $name
     * @return string
     */
    protected function getPath($name)
    {
        return base_path() . '/database/seeds/' . str_replace('\\', '/', $name) . '.php';
    }
}

Replace curly brace class with name of seed


<?php

namespace Clippings\Freezable;

/**
 * @author    Haralan Dobrev <hkdobrev@gmail.com>
 * @copyright 2014, Clippings Ltd.
 * @license   http://spdx.org/licenses/BSD-3-Clause
 */
trait FreezableCollectionTrait
{
    use FreezableTrait;

    private static function ensureItemsAreTraversable($items)
    {
        if (! is_array($items) AND ! $items instanceof \Traversable) {
            throw new \UnexpectedValueException(
                'Collection returned from getItems() should be either an array or a Traversable object.'
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function performFreeze()
    {
        $items = $this->getItems();

        self::ensureItemsAreTraversable($items);

        foreach ($items as $item) {
            if (! method_exists($item, 'freeze')) {
                throw new \UnexpectedValueException('Item should use the FreezableTrait to be freezed');
            }

            $item->freeze();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function performUnfreeze()
    {
        $items = $this->getItems();

        self::ensureItemsAreTraversable($items);

        foreach ($items as $item) {
            if (! method_exists($item, 'unfreeze')) {
                throw new \UnexpectedValueException('Item should use the FreezableTrait to be unfreezed');
            }

            $item->unfreeze();
        }
    }

    /**
     * @return array|Traversable
     */
    abstract public function getItems();
}

<?php

namespace Clippings\Freezable;

/**
 * @author    Haralan Dobrev <hkdobrev@gmail.com>
 * @copyright 2014, Clippings Ltd.
 * @license   http://spdx.org/licenses/BSD-3-Clause
 */
trait FreezableCollectionTrait
{
    use FreezableTrait;

    private static function ensureItemsAreTraversable($items)
    {
        if (! is_array($items) and ! $items instanceof \Traversable) {
            throw new \UnexpectedValueException(
                'Collection returned from getItems() should be either an array or a Traversable object.'
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function performFreeze()
    {
        $items = $this->getItems();

        self::ensureItemsAreTraversable($items);

        foreach ($items as $item) {
            if (! method_exists($item, 'freeze')) {
                throw new \UnexpectedValueException('Item should use the FreezableTrait to be freezed');
            }

            $item->freeze();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function performUnfreeze()
    {
        $items = $this->getItems();

        self::ensureItemsAreTraversable($items);

        foreach ($items as $item) {
            if (! method_exists($item, 'unfreeze')) {
                throw new \UnexpectedValueException('Item should use the FreezableTrait to be unfreezed');
            }

            $item->unfreeze();
        }
    }

    /**
     * @return array|Traversable
     */
    abstract public function getItems();
}

Fix coding style - lowercase keywords

:lipstick: Fix coding style - lowercase keywords


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Db\Sql\Ddl\Column;

class Boolean extends Column
{
    /**
     * @var string specification
     */
    protected $specification = '%s TINYINT NOT NULL';

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

    /**
     * @return array
     */
    public function getExpressionData()
    {
        $spec   = $this->specification;
        $params = array($this->name);
        $types  = array(self::TYPE_IDENTIFIER);

        return array(array(
            $spec,
            $params,
            $types,
        ));
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Db\Sql\Ddl\Column;

class Boolean extends Column
{
    /**
     * @var string
     */
    protected $type = 'TINYINT';

    /**
     * @return array
     */
    public function getExpressionData()
    {
        $this->isNullable = false;

        return parent::getExpressionData();
    }
}

Reduce code duplication in Booloan Ddl column class

Purposely ignore $isNullable from parent by resetting it in
getExpressionData()


<?php

App::uses('AppModel', 'Model');

/**
 * TemplateElementAttribute Model
 *
*/
class TemplateElementAttribute extends AppModel {
	public $actsAs = array('Containable');
	public $belongsTo = array('TemplateElement');

	public $validate = array(
			'name' => array(
				'valueNotEmpty' => array(
					'rule' => array('valueNotEmpty'),
				),
			),
			'description' => array(
				'valueNotEmpty' => array(
					'rule' => array('valueNotEmpty'),
				),
				'message' => 'Please enter a Description',
			),
			'category' => array(
				'rule'    => array('comparison', '!=', 'Select Category'),
				'message' => 'Please choose a category.'
			),
			'type' => array(
				'rule'    => array('comparison', '!=', 'Select Type'),
				'message' => 'Please choose a type.'
			),
	);
	public function beforeValidate($options = array()) {
		parent::beforeValidate();
	}
}

<?php

App::uses('AppModel', 'Model');

/**
 * TemplateElementAttribute Model
 *
*/
class TemplateElementAttribute extends AppModel {
	public $actsAs = array('Containable');
	public $belongsTo = array('TemplateElement');

	public $validate = array(
			'name' => array(
				'valueNotEmpty' => array(
					'rule' => array('valueNotEmpty'),
				),
			),
			'description' => array(
				'valueNotEmpty' => array(
					'rule' => array('valueNotEmpty'),
				),
			),
			'category' => array(
				'rule'    => array('comparison', '!=', 'Select Category'),
				'message' => 'Please choose a category.'
			),
			'type' => array(
				'rule'    => array('comparison', '!=', 'Select Type'),
				'message' => 'Please choose a type.'
			),
	);
	public function beforeValidate($options = array()) {
		parent::beforeValidate();
	}
}

Fix to a bug in the template attribute creation


© Happy City

made with ♥ at HackTM 2015

© Happy City &midot; Privacy

made with ♥ at HackTM 2015

Add privacy link in footer

Add privacy link in footer


<?php

namespace spec\Eadrax\Core\Context;

trait Core {}

<?php

namespace spec\Eadrax\Core\Context;

trait Core {
    function it_is_a_core_context()
    {
        $this->shouldHaveType('\Eadrax\Core\Context\Core');
    }
}

Add tests for whether or not it is a context.


<?php

namespace Rogue\Http\Transformers;

use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;

class PhoenixGalleryTransformer extends TransformerAbstract
{
    /**
     * Transform resource data.
     *
     * @param \Rogue\Models\Photo $photo
     * @return array
     */
    public function transform(Post $post)
    {
        $signup = $post->signup;
        $result = [
            'id' => $post->postable_id,
            'status' => $post->status,
            'caption' => $post->caption,
            'uri' => $post->file_url,
            'media' => [
                'uri' => $post->file_url,
                'type' => 'image',
            ],
            'created_at' => $post->created_at->toIso8601String(),
            'reportback' => [
                'id' => $signup->id,
                'created_at' => $signup->created_at->toIso8601String(),
                'updated_at' => $signup->updated_at->toIso8601String(),
                'quantity' => $signup->quantity,
                'why_participated' => $signup->why_participated,
                'flagged' => 'false',
            ],
        ];

        return $result;
    }
}

<?php

namespace Rogue\Http\Transformers;

use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;

class PhoenixGalleryTransformer extends TransformerAbstract
{
    /**
     * Transform resource data.
     *
     * @param \Rogue\Models\Photo $photo
     * @return array
     */
    public function transform(Post $post)
    {
        $signup = $post->signup;
        $result = [
            'id' => $post->postable_id,
            'status' => $post->status,
            'caption' => $post->caption,
            // Add link to review reportback item in Rogue here once that page exists
            // 'uri' => 'link_goes_here'
            'media' => [
                'uri' => $post->file_url,
                'type' => 'image',
            ],
            'created_at' => $post->created_at->toIso8601String(),
            'reportback' => [
                'id' => $signup->id,
                'created_at' => $signup->created_at->toIso8601String(),
                'updated_at' => $signup->updated_at->toIso8601String(),
                'quantity' => $signup->quantity,
                'why_participated' => $signup->why_participated,
                'flagged' => 'false',
            ],
        ];

        return $result;
    }
}

Add note about admin review link

Add note about admin review link


<?php

namespace PHPCfg\Op\Terminal;

use PHPCfg\Block;
use PHPCfg\Operand;
use PHPCfg\Op\Terminal;

class StaticVar extends Terminal {
    public $var;
    public $default;
    public $defaultVar;

    public function __construct(Operand $var, Block $defaultBlock, Operand $defaultVar, array $attributes = array()) {
        parent::__construct($attributes);
        $this->var = $var;
        $this->defaultBlock = $defaultBlock;
        $this->defaultVar = $defaultVar;
    }

    public function getVariableNames() {
        return ['var', 'defaultVar'];
    }

    public function getSubBlocks() {
        return ['defaultBlock'];
    }
}

<?php

namespace PHPCfg\Op\Terminal;

use PHPCfg\Block;
use PHPCfg\Operand;
use PHPCfg\Op\Terminal;

class StaticVar extends Terminal {
    public $var;
    public $default;
    public $defaultVar;

    public function __construct(Operand $var, Block $defaultBlock = null, Operand $defaultVar = null, array $attributes = array()) {
        parent::__construct($attributes);
        $this->var = $var;
        $this->defaultBlock = $defaultBlock;
        $this->defaultVar = $defaultVar;
    }

    public function getVariableNames() {
        return ['var', 'defaultVar'];
    }

    public function getSubBlocks() {
        return ['defaultBlock'];
    }
}

Fix issue with static variables without initializers


<?php

namespace Emailme\Currency;

use Exception;
use Emailme\Debug\Debug;

/*
* CurrencyUtil
*/
class CurrencyUtil
{

    const SATOSHI = 100000000;

    ////////////////////////////////////////////////////////////////////////

    public static function numberToSatoshis($number) {
        return intval(round($number * self::SATOSHI));
    }

    public static function satoshisToNumber($satoshis, $places=null) {
        if (!strlen($satoshis)) { return $satoshis; }
        if ($places === null) { $places = 7; }
        $out = number_format($satoshis / self::SATOSHI, $places);
        if (strpos($out, '.') !== false) {
            $out = rtrim($out, '0');
            $out = rtrim($out, '.');
        }

        return $out;
    }

    public static function addTwigFilters($twig) {
        $filter = new \Twig_SimpleFilter('to_currency', function ($satoshis) {
            return CurrencyUtil::satoshisToNumber($satoshis);
        });
        $twig->addFilter($filter);

        return $twig;
    }

    ////////////////////////////////////////////////////////////////////////

}

<?php

namespace Emailme\Currency;

use Exception;
use Emailme\Debug\Debug;

/*
* CurrencyUtil
*/
class CurrencyUtil
{

    const SATOSHI = 100000000;

    ////////////////////////////////////////////////////////////////////////

    public static function numberToSatoshis($number) {
        return intval(round($number * self::SATOSHI));
    }

    public static function satoshisToNumber($satoshis, $places=null) {
        if (!strlen($satoshis)) { return $satoshis; }
        if ($places === null) { $places = 8; }
        $out = number_format($satoshis / self::SATOSHI, $places);
        if (strpos($out, '.') !== false) {
            $out = rtrim($out, '0');
            $out = rtrim($out, '.');
        }

        return $out;
    }

    public static function addTwigFilters($twig) {
        $filter = new \Twig_SimpleFilter('to_currency', function ($satoshis) {
            return CurrencyUtil::satoshisToNumber($satoshis);
        });
        $twig->addFilter($filter);

        return $twig;
    }

    ////////////////////////////////////////////////////////////////////////

}

Use all 8 decimal places currency details


<?php

namespace Backend\Modules\Error\Tests\Action;

use Backend\Core\Language\Language;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\HttpFoundation\Response;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNotNeeded(Client $client): void
    {
        $this->logout($client);

        self::assertHttpStatusCode($client, '/private/en/error/index', Response::HTTP_BAD_REQUEST);
        self::assertCurrentUrlEndsWith($client, '/private/en/error/index');
    }

    public function testModuleNotAllowed(Client $client): void
    {
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=module-not-allowed',
            [
                'You have insufficient rights for this module.',
            ],
            Response::HTTP_FORBIDDEN
        );
    }

    public function testActionNotAllowed(Client $client): void
    {
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=action-not-allowed',
            [
                'You have insufficient rights for this action.',
            ],
            Response::HTTP_FORBIDDEN
        );
    }

    public function testNotFound(Client $client): void
    {
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=not-found',
            [
                Language::err('NotFound', 'Error'),
            ],
            Response::HTTP_NOT_FOUND
        );
    }
}

<?php

namespace Backend\Modules\Error\Tests\Action;

use Backend\Core\Language\Language;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\HttpFoundation\Response;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNotNeeded(Client $client): void
    {
        $this->logout($client);

        self::assertHttpStatusCode($client, '/private/en/error/index', Response::HTTP_BAD_REQUEST);
        self::assertCurrentUrlEndsWith($client, '/private/en/error/index');
    }

    public function testModuleNotAllowed(Client $client): void
    {
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=module-not-allowed',
            [
                'You have insufficient rights for this module.',
            ],
            Response::HTTP_FORBIDDEN
        );
    }

    public function testActionNotAllowed(Client $client): void
    {
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=action-not-allowed',
            [
                'You have insufficient rights for this action.',
            ],
            Response::HTTP_FORBIDDEN
        );
    }

    public function testNotFound(Client $client): void
    {
        Language::setLocale('en');
        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/error/index?type=not-found',
            [
                Language::err('NotFound', 'Error'),
            ],
            Response::HTTP_NOT_FOUND
        );
    }
}

Fix translations not loaded in test

Fix translations not loaded in test


@section('orchestra/story::primary_menu')

<?php

use Illuminate\Support\Facades\HTML;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Fluent;
use Orchestra\Support\Facades\App; ?>

	<li class="<?php echo Request::is('*/resources/storycms.posts*') ? 'active' : ''; ?>">
		<a href="<?php echo resources('storycms.posts'); ?>">Posts

	<li class="<?php echo Request::is('*/resources/storycms.pages*') ? 'active' : ''; ?>">
		<a href="<?php echo resources('storycms.pages'); ?>">Pages

		<a href="<?php echo handles('orchestra/story::/'); ?>" target="_blank">View Website

@stop

<?php

$navbar = new Fluent(array(
	'id'    => 'story',
	'title' => 'Story CMS',
	'url'   => resources('storycms'),
	'menu'  => View::yieldContent('orchestra/story::primary_menu'),
)); ?>

@decorator('navbar', $navbar)

@section('orchestra/story::primary_menu')

<?php

use Illuminate\Support\Facades\HTML;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Fluent;
use Orchestra\Support\Facades\App; ?>

	<li class="<?php echo Request::is('*resources/storycms.posts*') ? 'active' : ''; ?>">
		<a href="<?php echo resources('storycms.posts'); ?>">Posts

	<li class="<?php echo Request::is('*resources/storycms.pages*') ? 'active' : ''; ?>">
		<a href="<?php echo resources('storycms.pages'); ?>">Pages

		<a href="<?php echo handles('orchestra/story::/'); ?>" target="_blank">View Website

@stop

<?php

$navbar = new Fluent(array(
	'id'    => 'story',
	'title' => 'Story CMS',
	'url'   => resources('storycms'),
	'menu'  => View::yieldContent('orchestra/story::primary_menu'),
)); ?>

@decorator('navbar', $navbar)

Update Request::is() to support subdomain handling

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


@extends('_layouts.main')

@section('content')

TORelay.com

            <form class="form-horizontal" action="{{ url('/') }}" method="GET">

                    <input type="text" class="form-control" id="url" name="url" placeholder="url" value="{{ \Request::get('url', $url) }}">

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

            </form>

                about

@stop

@extends('_layouts.main')

@section('content')

TORelay.com

            <form class="form-horizontal" action="{{ url('/') }}" method="GET">

                    <input type="text" class="form-control" id="url" name="url" placeholder="url" value="{{ \Request::get('url', $url) }}">

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

            </form>

                about

Run from the command line:

curl https://torelay.com?url=https://ipnumber.info/?format=json

@stop

Add run from command line help on the frontpage


<?php

return call_user_func(function () {
    $all_caps = json_decode(file_get_contents(__DIR__ . '/browsers.json'), true);
    return $all_caps;
});

<?php

return call_user_func(function () {
    $all_caps = json_decode(file_get_contents(__DIR__ . '/browsers.json'), true);

    foreach ($all_caps as $cap) {
        if ($cap['os'] == 'Windows' && $cap['os_version'] == 'XP') continue;
        yield $cap;
    }
});

Exclude Windows XP from testing

Exclude Windows XP from testing


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Resource;

final class ResourceActions
{
    public const SHOW = 'show';
    public const INDEX = 'index';
    public const CREATE = 'create';
    public const UPDATE = 'update';
    public const DELETE = 'delete';
    public const MASS_DELETE = 'mass_delete';

    private function __construct()
    {
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Resource;

final class ResourceActions
{
    public const SHOW = 'show';
    public const INDEX = 'index';
    public const CREATE = 'create';
    public const UPDATE = 'update';
    public const DELETE = 'delete';
    public const BULK_DELETE = 'bulk_delete';

    private function __construct()
    {
    }
}

Change mass to bulk action

Change mass to bulk action

Refactor bulk delete action

Fixes


<?php
/**
 * @package Swat
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @copyright silverorange 2004
 */
require_once('Swat/SwatControl.php');
require_once('Swat/SwatHtmlTag.php');

/**
 * A form submit button.
 */
class SwatButton extends SwatControl {

	/**
	 * The visible text on the button.
	 * @var string
	 */
	public $title;

	public function init() {
		$this->title = $this->getStockTitle('submit');
	}

	public function display() {
		$input_tag = new SwatHtmlTag('input');
		$input_tag->type = 'submit';
		$input_tag->name = $this->name;
		$input_tag->value = $this->title;

		$input_tag->display();
	}

	public function getStockTitle($id) {
		switch ($id) {
			case 'submit':
				return _S('Submit');

			case 'create':
				return _S('Create');

			case 'apply':
				return _S('Apply');
		}
	}
}

?>

<?php
/**
 * @package Swat
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @copyright silverorange 2004
 */
require_once('Swat/SwatControl.php');
require_once('Swat/SwatHtmlTag.php');

/**
 * A form submit button.
 */
class SwatButton extends SwatControl {

	/**
	 * The visible text on the button.
	 * @var string
	 */
	public $title;

	public function init() {
		$this->setTitleFromStock('submit');
	}

	public function display() {
		$input_tag = new SwatHtmlTag('input');
		$input_tag->type = 'submit';
		$input_tag->name = $this->name;
		$input_tag->value = $this->title;

		$input_tag->display();
	}

	/**
	 * Set a stock title.
	 * Lookup a stock title for the button and set it as the current title.
	 * @param id string The shortname of the stock title.
	 */
	public function setTitleFromStock($id) {
		switch ($id) {
			case 'submit':
				$this->title = _S('Submit');
				break;

			case 'create':
				$this->title = _S('Create');
				break;

			case 'apply':
				$this->title = _S('Apply');
				break;
		}
	}
}

?>

Refactor the stock titles for buttons.

Refactor the stock titles for buttons.

svn commit r187


<?php

use Illuminate\Support\Str;

class SupportStrTest extends PHPUnit_Framework_TestCase
{

	/**
	* Test the Str::words method.
	*
	* @group laravel
	*/
	public function testStringCanBeLimitedByWords()
	{
		$this->assertEquals('Taylor...', Str::words('Taylor Otwell', 1));
		$this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___'));
		$this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3));
	}

	public function testStringWithoutWordsDoesntProduceError()
	{
		$nbsp = chr(0xC2).chr(0xA0);
		$this->assertEquals('', Str::words(' '));
		$this->assertEquals('', Str::words($nbsp));
	}

	public function testStringMacros()
	{
		Illuminate\Support\Str::macro(__CLASS__, function() { return 'foo'; });
		$this->assertEquals('foo', Str::SupportStrTest());
	}

}

<?php

use Illuminate\Support\Str;

class SupportStrTest extends PHPUnit_Framework_TestCase
{

	/**
	* Test the Str::words method.
	*
	* @group laravel
	*/
	public function testStringCanBeLimitedByWords()
	{
		$this->assertEquals('Taylor...', Str::words('Taylor Otwell', 1));
		$this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___'));
		$this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3));
	}

	public function testBehaviorWithLeadingAndTrailingSpaces()
	{
		$this->assertEquals(' Taylor Otwell', Str::words(' Taylor Otwell ', 3));
		$this->assertEquals(' Taylor...', Str::words(' Taylor Otwell ', 1));
	}

	public function testStringWithoutWordsDoesntProduceError()
	{
		$nbsp = chr(0xC2).chr(0xA0);
		$this->assertEquals('', Str::words(' '));
		$this->assertEquals('', Str::words($nbsp));
	}

	public function testStringMacros()
	{
		Illuminate\Support\Str::macro(__CLASS__, function() { return 'foo'; });
		$this->assertEquals('foo', Str::SupportStrTest());
	}

}

Add test for current Str::words behavior with leading and trailing spaces.


<?php

namespace Kyranb\Footprints;

use Kyranb\Footprints\Facades\FootprintsFacade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class FootprintsServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot()
    {
        $this->publishes([
            realpath(__DIR__.'/config/footprints.php') => config_path('footprints.php'),
        ]);

        $this->publishes([
               __DIR__.'/database/migrations/migrations.stub' => database_path('/migrations/'.date('Y_m_d_His').'_create_visits_table.php'),
           ], 'migrations');

    }

    /**
     * Register any package services.
     */
    public function register()
    {
        // Bring in configuration values
        $this->mergeConfigFrom(
              __DIR__.'/config/footprints.php', 'footprints'
           );

        $this->app->singleton(Footprints::class, function () {
            return new Footprints();
        });

        // Define alias 'Footprints'
        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();

            $loader->alias('Footprints', FootprintsFacade::class);
        });
    }
}

<?php

namespace Kyranb\Footprints;

use Kyranb\Footprints\Facades\FootprintsFacade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class FootprintsServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot()
    {
        $this->publishConfig();
        $this->publishMigration();
    }

    /**
     * Publish Footprints configuration
     */
    protected function publishConfig()
    {
        // Publish config files
        $this->publishes([
            realpath(__DIR__.'/config/footprints.php') => config_path('footprints.php'),
        ]);
    }

    /**
     * Publish Footprints migration
     */
    protected function publishMigration()
    {
        $published_migration = glob( database_path( '/migrations/*_create_visits_table.php' ) );
        if( count( $published_migration ) === 0 )
        {
            $this->publishes([
                   __DIR__.'/database/migrations/migrations.stub' => database_path('/migrations/'.date('Y_m_d_His').'_create_visits_table.php'),
               ], 'migrations');
        }
    }

    /**
     * Register any package services.
     */
    public function register()
    {
        // Bring in configuration values
        $this->mergeConfigFrom(
              __DIR__.'/config/footprints.php', 'footprints'
           );

        $this->app->singleton(Footprints::class, function () {
            return new Footprints();
        });

        // Define alias 'Footprints'
        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();

            $loader->alias('Footprints', FootprintsFacade::class);
        });
    }
}

Check if migration exists before publishing


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Support Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Support Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Support\Http\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

class FormRequest extends BaseFormRequest
{
    /**
     * {@inheritdoc}
     */
    protected function getValidatorInstance()
    {
        if (method_exists($this, 'process')) {
            $this->replace($this->container->call([$this, 'process'], [$this->all()]));
        }

        return parent::getValidatorInstance();
    }
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Support Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Support Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Support\Http\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

class FormRequest extends BaseFormRequest
{
    /**
     * {@inheritdoc}
     */
    protected function getValidatorInstance()
    {
        if (method_exists($this, 'process')) {
            $this->replace($this->container->call([$this, 'process'], [$this->all()]));
        } else {
            $this->replace(array_filter(array_map(function ($item) {
                return is_string($item) ? trim($item) : $item;
            }, $this->all())));
        }

        return parent::getValidatorInstance();
    }
}

Add fallback array map trim for all input fields by default


<?php

namespace Gobie\Debug\Dumpers;

use Gobie\Debug\DumperManager\IDumperManager;
use Gobie\Debug\Helpers;

/**
 * Dumper řetězce.
 */
class StringDumper extends AbstractDumper
{

    /**
     * Nastaví typ proménné na 'string'.
     *
     * Zkontroluje dostupnost potřebné extenze.
     */
    public function __construct()
    {
        $this->setTypes(IDumperManager::T_STRING);
    }

    public function dump(&$var, $level = 1, $depth = 4)
    {
        $varEnc = Helpers::encodeString($var);
        $varLen = strlen($var);

        return "" . $varEnc . ""
               . ($varLen ? " (" . $varLen . ')' : '');
    }
}

<?php

namespace Gobie\Debug\Dumpers;

use Gobie\Debug\DumperManager\IDumperManager;
use Gobie\Debug\Helpers;

/**
 * Dumper řetězce.
 */
class StringDumper extends AbstractDumper
{

    /**
     * Nastaví typ proménné na 'string'.
     *
     * Zkontroluje dostupnost potřebné extenze.
     */
    public function __construct()
    {
        $this->setTypes(IDumperManager::T_STRING);
    }

    public function dump(&$var, $level = 1, $depth = 4)
    {
        $varEnc = Helpers::encodeString($var);
        $varLen = strlen($var);

        return '' . $varEnc . ''
               . ($varLen ? ' (' . $varLen . ')' : '');
    }
}

Consolidate quotation of HTML attributes in dumps


<?php

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

declare(strict_types=1);

namespace ActiveCollab\Payments\TaxRates;

interface TaxIdValidatorInterface
{
    public function isValid(string $tax_id): bool;
}

<?php

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

declare(strict_types=1);

namespace ActiveCollab\Payments\TaxRates;

interface TaxIdValidatorInterface
{
    public function canValidate(string $country_code): bool;

    public function isValid(string $country_code, string $tax_id): ? bool;
}

Handle cases where we can’t validate a tax ID


<?php

if ($service == 'core.css'){
	$minimizer = new OC_Minimizer_CSS();
	$files = $minimizer->findFiles(OC_Util::$core_styles);
	$minimizer->output($files);
}
else if ($service == 'core.js'){
	$minimizer = new OC_Minimizer_JS();
	$files = $minimizer->findFiles(OC_Util::$core_scripts);
	$minimizer->output($files);
}

<?php

OC_App::loadApps();

if ($service == 'core.css'){
	$minimizer = new OC_Minimizer_CSS();
	$files = $minimizer->findFiles(OC_Util::$core_styles);
	$minimizer->output($files);
}
else if ($service == 'core.js'){
	$minimizer = new OC_Minimizer_JS();
	$files = $minimizer->findFiles(OC_Util::$core_scripts);
	$minimizer->output($files);
}

Load apps before minimizing the core css and js


<?php
/**
 * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
namespace Amazon\Payment\Domain;

class AmazonAuthorizationStatus extends AbstractAmazonStatus
{
    const STATE_OPEN = 'Open';
    const STATE_PENDING = 'Pending';
    const STATE_DECLINED = 'Declined';
    const STATE_CLOSED = 'Closed';

    const REASON_INVALID_PAYMENT_METHOD = 'InvalidPaymentMethod';
    const REASON_PROCESSING_FAILURE = 'ProcessingFailure';
    const REASON_AMAZON_REJECTED = 'AmazonRejected';
    const REASON_TRANSACTION_TIMEOUT = 'TransactionTimedOut';
    const REASON_MAX_CAPTURES_PROCESSED = 'MaxCapturesProcessed';
    const REASON_SELLER_CLOSED = 'SellerClosed';
    const REASON_EXPIRED_UNUSED = 'ExpiredUnused';

    const CODE_HARD_DECLINE = 4273;
    const CODE_SOFT_DECLINE = 7638;
}

<?php
/**
 * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
namespace Amazon\Payment\Domain;

class AmazonAuthorizationStatus extends AbstractAmazonStatus
{
    const STATE_OPEN = 'Open';
    const STATE_PENDING = 'Pending';
    const STATE_DECLINED = 'Declined';
    const STATE_CLOSED = 'Closed';

    const REASON_INVALID_PAYMENT_METHOD = 'InvalidPaymentMethod';
    const REASON_PROCESSING_FAILURE = 'ProcessingFailure';
    const REASON_AMAZON_REJECTED = 'AmazonRejected';
    const REASON_TRANSACTION_TIMEOUT = 'TransactionTimedOut';
    const REASON_MAX_CAPTURES_PROCESSED = 'MaxCapturesProcessed';
    const REASON_SELLER_CLOSED = 'SellerClosed';
    const REASON_EXPIRED_UNUSED = 'ExpiredUnused';
}

Update - removed redundant constants from class


@title('Login')

@extends('layouts.small')

@section('small-content')
    {!! Form::open(['route' => 'login.post']) !!}
        @formGroup('username')
            {!! Form::label('username') !!}
            {!! Form::text('username', null, ['class' => 'form-control', 'required']) !!}
            @error('username')
        @endFormGroup

        @formGroup('password')
            {!! Form::label('password') !!}
            {!! Form::password('password', ['class' => 'form-control', 'required']) !!}
            @error('password')
        @endFormGroup

                {!! Form::checkbox('remember') !!}
                Remember login

        {!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}

             Github

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

@section('small-content-after')

        Forgot your password?
        Need an account?

@endsection

@title('Login')

@extends('layouts.small')

@section('small-content')
    {!! Form::open(['route' => 'login.post']) !!}
        @formGroup('username')
            {!! Form::label('username') !!}
            {!! Form::text('username', null, ['class' => 'form-control', 'required']) !!}
            @error('username')
        @endFormGroup

        @formGroup('password')
            {!! Form::label('password') !!}
            {!! Form::password('password', ['class' => 'form-control', 'required']) !!}
            @error('password')
        @endFormGroup

                {!! Form::checkbox('remember') !!}
                Remember login

        {!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}

             Github

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

@section('small-content-after')
    Forgot your password?
@endsection

Simplify the buttons beneath the login form


<?php

namespace Webtown\KunstmaanExtensionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CacheController extends Controller
{
    /**
     * @Route("/index", name="KunstmaanAdminBundle_cache")
     * @Template()
     */
    public function indexAction()
    {
        return [];
    }

    /**
     * @Route("/purge", name="KunstmaanAdminBundle_cache_purge")
     */
    public function purgeAction()
    {
        try {
            $this->get('webtown_kunstmaan_extension.cache_manager')->forcePurgeAll();
            $this->addFlash('success', $this->get('translator')->trans('kuma_admin.cache.flash.cache_purged'));
        } catch (\Exception $e) {
            $this->addFlash('error', $this->get('translator')->trans(
                'kuma_admin.cache.flash.cache_not_purged.%exception%',
                ['%exception%' => $e->getMessage()]
            ));
        }

        return $this->redirectToRoute('KunstmaanAdminBundle_cache');
    }
}

<?php

namespace Webtown\KunstmaanExtensionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CacheController extends Controller
{
    /**
     * @Route("/index", name="KunstmaanAdminBundle_cache")
     * @Template()
     */
    public function indexAction()
    {
        return [];
    }

    /**
     * @Route("/purge", name="KunstmaanAdminBundle_cache_purge")
     */
    public function purgeAction()
    {
        try {
            $this->get('webtown_kunstmaan_extension.cache_manager')->forcePurgeAll();
            if (defined('apc_clear_cache')) {
                apc_clear_cache();
                apc_clear_cache('user');
                apc_clear_cache('opcode');
            }
            $this->addFlash('success', $this->get('translator')->trans('kuma_admin.cache.flash.cache_purged'));
        } catch (\Exception $e) {
            $this->addFlash('error', $this->get('translator')->trans(
                'kuma_admin.cache.flash.cache_not_purged.%exception%',
                ['%exception%' => $e->getMessage()]
            ));
        }

        return $this->redirectToRoute('KunstmaanAdminBundle_cache');
    }
}

Add APC cache clean function

Add APC cache clean function


<?php

namespace fennecweb;

class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';

    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);

        $this->assertEquals($expected, $results);

        //Test for correct project
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
            array(
                "id" => "This is a Table ID",
                "import_date" => "2016-05-17 10:00:52.627236+00",
                "rows" => 10,
                "columns" => 5
            )
        );
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace fennecweb;

class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';

    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);

        $this->assertEquals($expected, $results);

        //Test for correct project
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
            array(
                "id" => "table_1",
                "import_date" => "2016-05-17 10:00:52.627236+00",
                "rows" => 10,
                "columns" => 5
            )
        );
        $this->assertEquals($expected, $results);
    }
}

Make the failing test pass

Make the failing test pass


<?php

namespace Bolt\Extension\BobdenOtter\Seo;

use Bolt\Application;
use Bolt\BaseExtension;

require_once('Seo.php');
require_once('src/SEO.php');

class Extension extends BaseExtension
{

    private $version = "v0.9.1";

    public function __construct(Application $app)
    {
        parent::__construct($app);
        $this->app['config']->getFields()->addField(new SEOField());
    }

    public function initialize() {

        $end = $this->app['config']->getWhichEnd();

        if ($end =='backend') {

            // For Bolt 2.0 - 2.2
            $this->app['htmlsnippets'] = true;

            // For Bolt 2.3 +
            $this->app->before(function(Request $request){
                $request->attributes->set('allow_snippets', true);
            });

            $this->addCss('assets/seo.css');
            // $this->addJavascript('assets/seo.js', true);
        }

        $this->app['twig.loader.filesystem']->prependPath(__DIR__."/twig");

        $this->app['twig']->addGlobal('seoconfig', $this->config);

        if ($end == 'frontend') {
            $seo = new SEO($this->app, $this->config, $this->version);
            $this->app['twig']->addGlobal('seo', $seo);
        }

    }

    public function getName()
    {
        return "seo";
    }

}

<?php

namespace Bolt\Extension\BobdenOtter\Seo;

use Bolt\Application;
use Bolt\BaseExtension;

require_once('Seo.php');
require_once('src/SEO.php');

class Extension extends BaseExtension
{

    private $version = "v0.9.2";

    public function __construct(Application $app)
    {
        parent::__construct($app);
        $this->app['config']->getFields()->addField(new SEOField());
    }

    public function initialize() {

        $end = $this->app['config']->getWhichEnd();

        if ($end =='backend') {

            $this->app['htmlsnippets'] = true;

            $this->addCss('assets/seo.css');
            // $this->addJavascript('assets/seo.js', true);
        }

        $this->app['twig.loader.filesystem']->prependPath(__DIR__."/twig");

        $this->app['twig']->addGlobal('seoconfig', $this->config);

        if ($end == 'frontend') {
            $seo = new SEO($this->app, $this->config, $this->version);
            $this->app['twig']->addGlobal('seo', $seo);
        }

    }

    public function getName()
    {
        return "seo";
    }

}

Make extension work on both 2.2 and 2.3

Make extension work on both 2.2 and 2.3


        {{ $currentTenant->name }}

 {{ trans('cortex/foundation::common.home') }}

            {!! Menu::render('managerarea.header') !!}

        {{ $currentTenant->title }}

 {{ trans('cortex/foundation::common.home') }}

            {!! Menu::render('managerarea.header') !!}

Replace tenant name by tenant title in page headers


<?php
require_once 'config.php';
require_once 'feature.php';
require_once 'vote.php';

Add vote.php to be included

Add vote.php to be included


@if ($item->$field_name != null && $item->$field_name != '')
	<img src="{!! Croppa::url_resize('uploads/' . $route_prefix . '/' . $item->$field_name, 180) !!}" />
@endif

@if ($item->$field_name != null && $item->$field_name != '')
	<img src="{!! Croppa::url_resize(
		'uploads/' . $route_prefix . '/' . $item->$field_name,
		array_key_exists('width', $field) ? $field['width'] : 180
	) !!}" />
@endif

Add support for configurable image width


<?php

namespace Pipe\Silex;

use Silex\Application;
use Silex\ServiceProviderInterface;

use Symfony\Component\HttpFoundation\Response;

class PipeServiceProvider implements ServiceProviderInterface
{
    function register(Application $app)
    {
        $app->register(new \Silex\Provider\UrlGeneratorServiceProvider());

        $app["pipe"] = $app->share(function($app) {
            return new PipeService($app);
        });

        $app->get("/_pipe/assets/{logicalPath}", function($logicalPath) use ($app) {
            $asset = $app["pipe"]->environment->find($logicalPath);

            if (!$asset) {
                return $app->abort(404, "Asset '$logicalPath' not found");
            }

            $res = new Response($asset->getBody(), 200);
            $res->headers->set("Content-Type", $asset->getContentType());
            $res->headers->set("Content-Length", strlen($asset->getBody()));

            if (isset($app["logger"]) and $app["logger"] !== null) {
                $app["logger"]->log("Pipe: Serving '$logicalPath'");
            }

            return $res;
        })
        ->assert("logicalPath", ".+")
        ->bind("pipe.assets");

        if (isset($app["twig"])) {
            $app["twig"]->addExtension(new PipeTwigExtension);
        }
    }

    function boot(Application $app)
    {}
}

<?php

namespace Pipe\Silex;

use Silex\Application;
use Silex\ServiceProviderInterface;

use Symfony\Component\HttpFoundation\Response;

class PipeServiceProvider implements ServiceProviderInterface
{
    function register(Application $app)
    {
        $app->register(new \Silex\Provider\UrlGeneratorServiceProvider());

        $app["pipe"] = $app->share(function($app) {
            return new PipeService($app);
        });

        $app->get("/_pipe/assets/{logicalPath}", function($logicalPath) use ($app) {
            $asset = $app["pipe"]->environment->find($logicalPath);

            if (!$asset) {
                return $app->abort(404, "Asset '$logicalPath' not found");
            }

            $res = new Response($asset->getBody(), 200);
            $res->headers->set("Content-Type", $asset->getContentType());
            $res->headers->set("Content-Length", strlen($asset->getBody()));

            if (isset($app["logger"]) and $app["logger"] !== null) {
                $app["logger"]->log("Pipe: Serving '$logicalPath'");
            }

            return $res;
        })
        ->assert("logicalPath", ".+")
        ->bind("pipe.assets");
    }

    function boot(Application $app)
    {
        if (isset($app["twig"])) {
            $app["twig"]->addExtension(new PipeTwigExtension);
        }
    }
}

Add Twig Extensions on boot

Add Twig Extensions on boot


<?php

namespace Troupe\Tests\Functional;

require_once realpath(__DIR__ . '/../../../bootstrap.php');

class StandardUseCaseTest extends \PHPUnit_Framework_TestCase {

  function setUp() {

  }

  function testBasicIntegration() {
    $data_dir = realpath(__DIR__ . '/../../../../data');
		$scope = new \Troupe\EnvironmentScope(
		  array(), getcwd(), $data_dir, array()
		);
		\Troupe\Injector::injectEnvironmentHelper($scope)->run();
  }

}

<?php

namespace Troupe\Tests\Functional;

require_once realpath(__DIR__ . '/../../../bootstrap.php');

class StandardUseCaseTest extends \PHPUnit_Framework_TestCase {

  function setUp() {
    $this->data_dir = realpath(__DIR__ . '/../../../../data');
  }

  function testBasicIntegration() {
    $args = array();
		$scope = new \Troupe\EnvironmentScope(
		  array(), getcwd(), $this->data_dir, $args
		);
		\Troupe\Injector::injectEnvironmentHelper($scope)->run();
  }

  function testSettingGlobalSettings() {
    $this->markTestIncomplete();
  }

}

Test placeholder in preparation for implementing setting global settings.


<?php

/**
 * Spiral Framework. Scaffolder
 *
 * @license MIT
 * @author  Valentin V (vvval)
 */

declare(strict_types=1);

namespace Spiral\Tests\Scaffolder;

use PHPUnit\Framework\TestCase;
use Spiral\Tests\Scaffolder\App\TestApp;
use Throwable;

abstract class BaseTest extends TestCase
{
    /** @var TestApp */
    protected $app;

    /**
     * @throws Throwable
     */
    public function setUp(): void
    {
        $this->app = TestApp::init([
            'root' => __DIR__ . '/App',
        ], null, false);
    }
}

<?php

/**
 * Spiral Framework. Scaffolder
 *
 * @license MIT
 * @author  Valentin V (vvval)
 */

declare(strict_types=1);

namespace Spiral\Tests\Scaffolder;

use PHPUnit\Framework\TestCase;
use Spiral\Tests\Scaffolder\App\TestApp;
use Throwable;

/**
 * @requires function \Spiral\Framework\Kernel::init
 */
abstract class BaseTest extends TestCase
{
    /** @var TestApp */
    protected $app;

    /**
     * @throws Throwable
     */
    public function setUp(): void
    {
        $this->app = TestApp::init([
            'root' => __DIR__ . '/App',
        ], null, false);
    }
}

Fix spiral/framework dependency in tests


<?php
/**
 * @LICENSE_TEXT
 */

namespace EventBand\Bundle\DependencyInjection\Compiler;

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

/**
 * Class InitBandPass
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class ReplaceDispatcherPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        $dispatcher = $container->getDefinition('event_dispatcher');
        $dispatcher->setPublic(false);

        $container->setDefinition('event_band.internal_dispatcher', $dispatcher);
        $container->setDefinition('event_dispatcher', $container->getDefinition('event_band.dispatcher'));
        $container->removeDefinition('event_band.dispatcher');
        $container->setAlias('event_band.dispatcher', 'event_dispatcher');
    }
}

<?php
/**
 * @LICENSE_TEXT
 */

namespace EventBand\Bundle\DependencyInjection\Compiler;

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

/**
 * Class InitBandPass
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class ReplaceDispatcherPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        if ($container->hasAlias('event_dispatcher')) {
            $container->setAlias('event_band.internal_dispatcher', $container->getAlias('event_dispatcher'));
        } else {
            $dispatcher = $container->getDefinition('event_dispatcher');
            $dispatcher->setPublic(false);

            $container->setDefinition('event_band.internal_dispatcher', $dispatcher);
        }

        $container->setDefinition('event_dispatcher', $container->getDefinition('event_band.dispatcher'));

        $container->removeDefinition('event_band.dispatcher');
        $container->setAlias('event_band.dispatcher', 'event_dispatcher');
    }
}

Fix event_dispatcher replacement in DependencyInjection


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UDB2;

use CultuurNet\Auth\TokenCredentials;

final class EntryAPIImprovedFactory
{
    /**
     * @var Consumer
     */
    private $consumer;

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

    /**
     * @param TokenCredentials $tokenCredentials
     * @return EntryAPI
     */
    public function withTokenCredentials(TokenCredentials $tokenCredentials)
    {
        return new EntryAPI(
            $this->consumer->getTargetUrl(),
            $this->consumer->getConsumerCredentials(),
            $tokenCredentials
        );
    }
}

<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UDB2;

use CultuurNet\Auth\TokenCredentials;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Plugin\Log\LogPlugin;

final class EntryAPIImprovedFactory
{
    /**
     * @var Consumer
     */
    private $consumer;

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

    /**
     * @param TokenCredentials $tokenCredentials
     * @return EntryAPI
     */
    public function withTokenCredentials(TokenCredentials $tokenCredentials)
    {
        $entryApi = new EntryAPI(
            $this->consumer->getTargetUrl(),
            $this->consumer->getConsumerCredentials(),
            $tokenCredentials
        );

        // Print request and response for debugging purposes.
        $adapter = new ClosureLogAdapter(function ($message, $priority, $extras) {
                // @todo handle $priority
                print $message;
            });

        $format = "\n\n# Request:\n{request}\n\n# Response:\n{response}\n\n# Errors: {curl_code} {curl_error}\n\n";
        $log = new LogPlugin($adapter, $format);

        $entryApi->getHttpClientFactory()->addSubscriber($log);

        return $entryApi;
    }
}

Print request and response to entry API

iii-97: Print request and response to entry API


<?php

class MapLayer extends DataObject {

	static $db = array(
		'Title' => 'Varchar(255)'
	);

	static $has_one = array(
		'KmlFile' => 'File'
	);

	function getCMSFields_forPopup() {
		$fields = new FieldSet();

		$fields->push(new TextField('Title'));
		$fields->push(new FileIFrameField('KmlFile'));

		return $fields;
	}

}

<?php

class MapLayer extends DataObject {

	static $db = array(
		'Title' => 'Varchar(255)'
	);

	static $has_one = array(
		'KmlFile' => 'File'
	);

}

FIX: Remove obsolete method that was for DataObjectManager


<?php

if ((!$loader = @include __DIR__.'/../../../autoload.php')
        && (!$loader = @include __DIR__.'/../vendor/autoload.php')
) {
    die('You must set up the project dependencies, run the following commands:'.PHP_EOL.
        'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
        'php composer.phar install'.PHP_EOL);
}

<?php

if (
    (!$loader = @include __DIR__.'/../../../autoload.php')
    && (!$loader = @include __DIR__.'/../vendor/autoload.php')
) {
    die('You must set up the project dependencies, run the following command:'.PHP_EOL.
        'composer install'.PHP_EOL);
}

Stop advising users to pipe a curl download directly into php.


<?php
/**
Plugin Name: Scrivener
Plugin URI: http://10up.com
Description: A WordPress plugin to enhance the post editor preview, mainly through proof of concept.
Version: 0.1.0
Author: 10up
Author URI: http://10up.com
License: GPLv2 or later
 */

if ( ! class_exists( '\\Composer\\Autoload\\ClassLoader' ) ) {
	// include our default customizer classes
	include_once( __DIR__ . '/classes/Customizer/Section.php' );
	include_once( __DIR__ . '/classes/Customizer/Core.php' );
	include_once( __DIR__ . '/classes/Scrivener/Core.php' );
}

<?php
/**
Plugin Name: Scrivener
Plugin URI: http://10up.com
Description: A WordPress plugin to enhance the post editor preview, mainly through proof of concept.
Version: 0.1.0
Author: 10up
Author URI: http://10up.com
License: GPLv2 or later
 */

if ( ! class_exists( '\\Composer\\Autoload\\ClassLoader' ) ) {
	// include our default customizer classes
	include_once( __DIR__ . '/classes/Customizer/Control.php' );
	include_once( __DIR__ . '/classes/Customizer/Section.php' );
	include_once( __DIR__ . '/classes/Customizer/Core.php' );
	include_once( __DIR__ . '/classes/Scrivener/Core.php' );
}

Include Control.php for non-autoloaded installs


<?php

namespace CommerceGuys\Platform\Cli\Command;

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

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Platform.sh Web UI');
        $this->addProjectOption()->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Check whether the user is logged in (do not require login).
        $this->loadConfig(false);
        if ($this->config) {
            // If the user is logged in, select the appropriate project and
            // environment, suppressing any errors.
            $this->validateInput($input, new NullOutput());
        }

        $url = 'https://platform.sh';
        if ($this->project) {
            $url = $this->project['uri'];
            if ($this->environment) {
                $url .= '/environments/' . $this->environment['id'];
            }
        }
        elseif ($this->config) {
            // If no project is selected, find the appropriate Web UI hostname
            // for the user's first project.
            // @todo update this when there is a unified UI domain
            $projects = $this->getProjects();
            $project = reset($projects);
            $parsed = parse_url($project['uri']);
            if (!$parsed) {
                throw new \RuntimeException("Failed to parse project URL");
            }
            $url = 'https://' . $parsed['host'];
        }

        $this->openUrl($url, $input, $output);
    }
}

<?php

namespace CommerceGuys\Platform\Cli\Command;

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

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Platform.sh Web UI');
        $this->addProjectOption()->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Check whether the user is logged in (do not require login).
        $this->loadConfig(false);
        if ($this->config) {
            // If the user is logged in, select the appropriate project and
            // environment, suppressing any errors.
            $this->validateInput($input, new NullOutput());
        }

        $url = 'https://marketplace.commerceguys.com/platform/login';
        if ($this->project) {
            $url = $this->project['uri'];
            if ($this->environment) {
                $url .= '/environments/' . $this->environment['id'];
            }
        }

        $this->openUrl($url, $input, $output);
    }
}

Add the new login / projects link.

Add the new login / projects link.


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, 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\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Group form type extension
 */
class GroupFormTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritDoc}
     */
    public function finishView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['darvin_admin_group'] = $options['darvin_admin_group'];
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefault('darvin_admin_group', null)
            ->setAllowedTypes('darvin_admin_group', ['string', 'null']);
    }

    /**
     * {@inheritDoc}
     */
    public static function getExtendedTypes(): iterable
    {
        yield FormType::class;
    }
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, 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\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Group form type extension
 */
class GroupFormTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritDoc}
     */
    public function finishView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['admin_group'] = $options['admin_group'];
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefault('admin_group', null)
            ->setAllowedTypes('admin_group', ['string', 'null']);
    }

    /**
     * {@inheritDoc}
     */
    public static function getExtendedTypes(): iterable
    {
        yield FormType::class;
    }
}

Implement group form type extension.

Implement group form type extension.


<?php namespace Laravel\Socialite\Two;

use Symfony\Component\HttpFoundation\RedirectResponse;

class GithubProvider extends AbstractProvider implements ProviderInterface
{

    /**
     * The scopes being requested.
     *
     * @var array
     */
    protected $scopes = ['user:email'];

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase('https://github.com/login/oauth/authorize', $state);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://github.com/login/oauth/access_token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get('https://api.github.com/user?access_token='.$token, [
            'headers' => [
                'Accept' => 'application/vnd.github.v3+json',
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User)->setRaw($user)->map([
            'id' => $user['id'], 'nickname' => $user['login'], 'name' => array_get($user, 'name'),
            'email' => isset($user['email']) ? $user['email'] : null, 'avatar' => $user['avatar_url'],
        ]);
    }
}

<?php namespace Laravel\Socialite\Two;

use Symfony\Component\HttpFoundation\RedirectResponse;

class GithubProvider extends AbstractProvider implements ProviderInterface
{

    /**
     * The scopes being requested.
     *
     * @var array
     */
    protected $scopes = ['user:email'];

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase('https://github.com/login/oauth/authorize', $state);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://github.com/login/oauth/access_token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get('https://api.github.com/user?access_token='.$token, [
            'headers' => [
                'Accept' => 'application/vnd.github.v3+json',
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User)->setRaw($user)->map([
            'id' => $user['id'], 'nickname' => $user['login'], 'name' => array_get($user, 'name'),
            'email' => array_get($user, 'email'), 'avatar' => $user['avatar_url'],
        ]);
    }
}

Change code to use array_helper

Change code to use array_helper


<?php

declare(strict_types=1);

namespace Tests\Feature;

use Tests\TestCase;

class SimpleRequestsTest extends TestCase
{
    /**
     * Test simple, non-CAS requests load without any authentication.
     */
    public function testUnauthenticatedRequests(): void
    {
        $response = $this->get('/privacy');
        $response->assertStatus(200);

        $response = $this->get('/attendance/kiosk');
        $response->assertStatus(200);
    }

    /**
     * Test that the home page loads successfully.
     */
    public function testHome(): void
    {
        $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/');
        $response->assertStatus(200);

        $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/');
        $response->assertStatus(200);
    }
}

<?php

declare(strict_types=1);

namespace Tests\Feature;

use Tests\TestCase;

class SimpleRequestsTest extends TestCase
{
    /**
     * Test simple, non-CAS requests load without any authentication.
     */
    public function testUnauthenticatedRequests(): void
    {
        $response = $this->get('/privacy');
        $response->assertStatus(200);

        $response = $this->get('/attendance/kiosk');
        $response->assertStatus(200);
    }

    /**
     * Test that the home page loads successfully.
     */
    public function testHome(): void
    {
        $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());
//        $response->assertStatus(200);

        $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());
//        $response->assertStatus(200);
    }
}

Add more detail to test failure message

Add more detail to test failure message


<?php

class AdditionTest extends \PHPUnit_Framework_TestCase
{
    public function testAddition()
    {
        $this->assertTrue(true);
    }
}

<?php

class AdditionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Verifies that 1 + 1 = 2
     */
    public function testAddition()
    {
        $numberCollectionGenerator = new NumberCollectionGenerator('NumberCollection');
        $numberCollection = $numberCollectionGenerator->generate();

        $numberReader = new NumberStringReader('1');
        $number = new Number($numberReader);

        $numberCollection->add(new Number(1));
        $numberCollection->add(new Number(1));

        $iterator = new CallbackIterator();
        $addition = new Addition($iterator);

        $operation = new ArithmeticOperation();
        $operation->setOperator($addition);

        $iterator = new CallbackIterator();
        $operationStream = new OperationStream($iterator);
        $operationStream->addOperation($operation);

        $engine = new Engine();
        $engine->setOperationStream($operationStream);

        $calcul = new Calcul();
        $calcul->setEngine($engine);
        $calcul->setNumberCollection($numberCollection);

        $runner = new CalculRunner();

        $result = $runner->run($calcul);
        $numericResult = $result->getNumericValue();

        $this->assertEquals(2, $numericResult);
    }
}

Add addition functional test. It fails.

Add addition functional test. It fails.


<?php

use Codeception\TestCase\Test;
use Faker\Factory;
use Illuminate\Contracts\Logging\Log;
use Mockery as m;

/**
 * Base UnitTest
 *
 * The core test-class for all unit tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class BaseUnitTest extends Test
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    /**
     * Instance of the faker generator
     *
     * @var \Faker\Generator
     */
    protected $faker;

    protected function _before()
    {
        $this->faker = Factory::create();
    }

    protected function _after()
    {
        m::close();
    }

    /********************************************************
     * Helpers
     *******************************************************/

    /**
     * Returns instance of a log mock
     *
     * @return m\MockInterface|Log
     */
    public function makeLogMock()
    {
        return m::mock(Log::class);
    }
}

<?php

use Codeception\TestCase\Test;
use Faker\Factory;
use Illuminate\Contracts\Logging\Log;
use Mockery as m;

/**
 * Base UnitTest
 *
 * The core test-class for all unit tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class BaseUnitTest extends Test
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    /**
     * Instance of the faker generator
     *
     * @var \Faker\Generator
     */
    protected $faker;

    protected function _before()
    {
        $this->faker = Factory::create();
    }

    protected function _after()
    {
        m::close();
    }

    /********************************************************
     * Helpers
     *******************************************************/

    /**
     * Returns instance of a log mock
     *
     * @return m\MockInterface|Log
     */
    public function makeLogMock()
    {
        return m::mock(Log::class);
    }

    /**
     * Returns random folder paths
     *
     * @param int $amount [optional]
     *
     * @return string[]
     */
    public function makeFolderPaths($amount = 3)
    {
        $output = [];

        while($amount--){
            $nested = mt_rand(1, 4);
            $path = [];

            while($nested--){
                $path[] = $this->faker->word;
            }

            $output[] = implode(DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR;
        }

        return $output;
    }
}

Add fake folder path generator to base unit test


<?php

use Common\Exception\LoginException;

class LoginExceptionTest extends \Codeception\TestCase\Test
{
    use Codeception\Specify;

    public function testLoginExceptionIsThrown()
    {
        $this->specify('', function() {
            throw new LoginException('I am a test');
        }, ['throws' => 'Common\Exception\LoginException']);
    }
}

<?php

use Common\Exception\LoginException;

class LoginExceptionTest extends \Codeception\TestCase\Test
{
    use Codeception\Specify;

    public function testLoginExceptionIsThrown()
    {
        $this->specify('Throw LoginException', function() {
            throw new LoginException('I am a test');
        }, ['throws' => 'Common\Exception\LoginException']);
    }
}

Add comment to test message

Add comment to test message


@extends('layout.dashboard')

@section('content')

             {{ Lang::get('cachet.dashboard.user') }}

                @if($updated = Session::get('updated'))

                    @if($updated)
                    Awesome. Profile updated.
                    @else
                    Whoops. Something went wrong when updating.
                    @endif

                @endif

                <form name='UserForm' class='form-vertical' role='form' action='/dashboard/user' method='POST'>
                    <fieldset>

                            Username
                            <input type='text' class='form-control' name='username' value='{{ Auth::user()->username }}' required />

                            Email Address
                            <input type='email' class='form-control' name='email' value='{{ Auth::user()->email }}' required />

                            Password
                            <input type='password' class='form-control' name='password' value='' />

                    </fieldset>

                    <button type="submit" class="btn btn-primary">Update profile</button>
                </form>

@stop

@extends('layout.dashboard')

@section('content')

             {{ Lang::get('cachet.dashboard.user') }}

                @if($updated = Session::get('updated'))

                    @if($updated)
                    Awesome. Profile updated.
                    @else
                    Whoops. Something went wrong when updating.
                    @endif

                @endif

                <form name='UserForm' class='form-vertical' role='form' action='/dashboard/user' method='POST'>
                    <fieldset>

                            Username
                            <input type='text' class='form-control' name='username' value='{{ Auth::user()->username }}' required />

                            Email Address
                            <input type='email' class='form-control' name='email' value='{{ Auth::user()->email }}' required />

                            Password
                            <input type='password' class='form-control' name='password' value='' />

                    </fieldset>

                    <button type="submit" class="btn btn-success">Update profile</button>
                </form>

@stop

Use success button for saving

Use success button for saving


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
    }
    public function index()
    {
        $user = array(
            'email' => $this->session->userdata('email'),
            'auth' => $this->session->userdata('is_auth')
            );

        $this->load->view('login', $user);
    }
}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->library('session');
        $user = array(
            'email' => $this->session->userdata('email'),
            'auth' => $this->session->userdata('is_auth')
        );
        if (empty($user)) {
            $user = NULL;
        }

        $this->load->view('login', $user);
    }
}

Check empty session about user

Check empty session about user


<?php
/*
	PufferPanel - A Minecraft Server Management Panel
	Copyright (c) 2013 Dane Everitt

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

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

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see http://www.gnu.org/licenses/.
*/
namespace PufferPanel\Core\API;

class Initalize {

	public function __construct() { }

	public function loadModule($module) {

		require __DIR__ . '/' . strtolower($module) . '.php';
		$controller = "PufferPanel\Core\API\\$module";

		return new $controller;

	}

}

<?php
/*
	PufferPanel - A Minecraft Server Management Panel
	Copyright (c) 2013 Dane Everitt

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

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

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see http://www.gnu.org/licenses/.
*/
namespace PufferPanel\Core\API;

class Initalize {

	public function __construct() { }

	public function loadModule($module, $namespace = "PufferPanel\Core\API\\") {

		require __DIR__ . '/' . strtolower($module) . '.php';

		$controller = $namespace.$module;
		return new $controller;

	}

}

Make API even more extendable

Make API even more extendable


<?php

namespace LaravelProfaneTests;

use LaravelProfane\ProfaneValidator;

class ProfaneValidatorBuilder
{
    /**
     * [$profaneValidator description]
     * @var [type]
     */
    protected $profaneValidator;

    /**
     * [__construct description]
     * @param [type] $dictionary [description]
     */
    public function __construct($dictionary = null)
    {
        $this->profaneValidator = new ProfaneValidator;

        if ($dictionary) {
            $this->profaneValidator->setDictionary($dictionary);
        }
    }

    /**
     * [validate description]
     * @param  array  $parameters [description]
     * @return [type]             [description]
     */
    public function validate(array $parameters)
    {
        list($attribute, $text, $parameters) = $parameters;

        return $this->build()->validate($attribute, $text, $parameters);
    }

    /**
     * [build description]
     * @return LaravelProfane\ProfaneValidator
     */
    public function build()
    {
        return $this->profaneValidator;
    }
}

<?php

namespace LaravelProfaneTests;

use LaravelProfane\ProfaneValidator;

class ProfaneValidatorBuilder
{
    /**
     * [$profaneValidator description]
     * @var [type]
     */
    protected $profaneValidator;

    /**
     * [__construct description]
     * @param [type] $dictionary [description]
     */
    public function __construct($dictionary = null)
    {
        $this->profaneValidator = new ProfaneValidator;

        if ($dictionary) {
            $this->profaneValidator->setDictionary($dictionary);
        }
    }

    /**
     * [validate description]
     * @param  array  $parameters [description]
     * @return [type]             [description]
     */
    public function validate(array $parameters)
    {
        list($attribute, $text, $dictionaries) = $parameters;

        return $this->build()->validate($attribute, $text, $dictionaries);
    }

    /**
     * [build description]
     * @return LaravelProfane\ProfaneValidator
     */
    public function build()
    {
        return $this->profaneValidator;
    }
}

Fix tests on PHP 5.6

Fix tests on PHP 5.6


<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.

$apcLoader = new ApcClassLoader('timmd909APC', $loader);
$loader->unregister();
$apcLoader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.

// $apcLoader = new ApcClassLoader('timmd909APC', $loader);
// $loader->unregister();
// $apcLoader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Remove APC loader because Pair is a pooper


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, 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\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param bool   $reloadPage Whether to reload page
     * @param array  $data       Additional data
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        $reloadPage = false,
        array $data = array(),
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        )), $status, $headers);
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, 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\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param array  $data       Additional data
     * @param bool   $reloadPage Whether to reload page
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        array $data = array(),
        $reloadPage = false,
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        )), $status, $headers);
    }
}

Reorder AJAX response class constructor arguments.


<?
defined('C5_EXECUTE') or die("Access Denied.");

$c = Page::getCurrentPage();
if (is_object($c)) {
    $cp = new Permissions($c);
    Loader::element('page_controls_footer', array('cp' => $cp, 'c' => $c));
}

$_trackingCodePosition = Config::get('concrete.seo.tracking.code_position');
if (empty($disableTrackingCode) && (empty($_trackingCodePosition) || $_trackingCodePosition === 'bottom')) {
	echo Config::get('concrete.seo.tracking.code');
}

$v = View::getInstance();
print $v->markFooterAssetPosition();

// user profile menu
Loader::element('account/menu');

<?
defined('C5_EXECUTE') or die("Access Denied.");

$c = Page::getCurrentPage();
if (is_object($c)) {
    $cp = new Permissions($c);
    View::element('page_controls_footer', array('cp' => $cp, 'c' => $c));
}

$_trackingCodePosition = Config::get('concrete.seo.tracking.code_position');
if (empty($disableTrackingCode) && (empty($_trackingCodePosition) || $_trackingCodePosition === 'bottom')) {
	echo Config::get('concrete.seo.tracking.code');
}

View::getInstance()->markFooterAssetPosition();

// user profile menu
View::element('account/menu');

Remove deprecated calls (Loader --> View)

Former-commit-id: baab1b8c1ded29c92f52cd29097a7118382a21f9
Former-commit-id: 08c6d71dfeb06190f7a54d38ebe3fdfbf2f66768


<?php

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

namespace Symfony\Component\HttpKernel\DataCollector;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * MemoryDataCollector.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class MemoryDataCollector extends DataCollector
{
    public function __construct()
    {
        $this->data = array('memory' => 0);
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->updateMemoryUsage();
    }

    /**
     * Gets the memory.
     *
     * @return integer The memory
     */
    public function getMemory()
    {
        return $this->data['memory'];
    }

    /**
     * Updates the memory usage data.
     */
    public function updateMemoryUsage()
    {
        $this->data['memory'] = memory_get_peak_usage(true);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'memory';
    }
}

<?php

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

namespace Symfony\Component\HttpKernel\DataCollector;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * MemoryDataCollector.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class MemoryDataCollector extends DataCollector
{
    public function __construct()
    {
        $this->data = array(
            'memory' => 0,
            'memory_limit' => rtrim(ini_get('memory_limit'), 'M')
        );
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->updateMemoryUsage();
    }

    /**
     * Gets the memory.
     *
     * @return integer The memory
     */
    public function getMemory()
    {
        return $this->data['memory'];
    }

    /**
     * Gets the PHP memory limit.
     *
     * @return integer The memory limit
     */
    public function getMemoryLimit()
    {
        return $this->data['memory_limit'];
    }

    /**
     * Updates the memory usage data.
     */
    public function updateMemoryUsage()
    {
        $this->data['memory'] = memory_get_peak_usage(true);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'memory';
    }
}

Add PHP memory_limit to WDT

Add PHP memory_limit to WDT