<?php

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

class stationTest extends TestCase
{
    public function testStation()
    {
        $response = $this->call('GET', '/stations');
        $this->assertEquals(302, $response->status());
    }

    public function testStationNmbs()
    {
        $responseNMBS = $this->call('GET', '/stations/NMBS');
        $responsenmbs = $this->call('GET', '/stations/nmbs');

        $this->assertEquals(200, $responseNMBS->status());
        $this->assertEquals(200, $responsenmbs->status());
    }

    public function testSpecificStation()
    {
        $response = $this->call('GET', '/stations/NMBS/008727100');
        $this->assertEquals(200, $response->status());
    }

    public function testSpecificTrainDepartures()
    {
        $response = $this->call('GET', '/stations/NMBS/008727100/departures');
        $this->assertEquals(200, $response->status());
    }
}

<?php

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

class stationTest extends TestCase
{
    public function testStation()
    {
        $response = $this->call('GET', '/stations');
        $this->assertEquals(302, $response->status());
    }

    public function testStationNmbs()
    {
        $responseNMBS = $this->call('GET', '/stations/NMBS');
        $responsenmbs = $this->call('GET', '/stations/nmbs');

        $this->assertEquals(200, $responseNMBS->status());
        $this->assertEquals(200, $responsenmbs->status());
    }

    public function testSpecificStation()
    {
        $response = $this->call('GET', '/stations/NMBS/008727100');
        $this->assertEquals(200, $response->status());
    }

    public function testSpecificTrainDepartures()
    {
        $urlCapitalCasing = $this->call('GET', '/stations/NMBS/008727100/departures');
        $urlLowerCasing   = $this->call('GET', '/stations/nmbs/008727100/departures');

        $this->assertEquals(200, $urlCapitalCasing->status());
        $this->assertEquals(200, $urlLowerCasing->status());
    }
}

Add test for lowercased route

Add test for lowercased route


<?php

/*
 * This file is part of PsySH
 *
 * (c) 2012 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Formatter;

use Psy\Formatter\RecursiveFormatter;

/**
 * A pretty-printer for arrays..
 */
class ArrayFormatter extends RecursiveFormatter
{
    /**
     * Format the array.
     *
     * @param array $array
     *
     * @return string
     */
    public static function format(array $array)
    {
        if (empty($array)) {
            return '[]';
        }

        $formatted = array_map(array(__CLASS__, 'formatValue'), $array);
        $template  = sprintf('[%s%s%%s%s   ]', PHP_EOL, str_repeat(' ', 7), PHP_EOL);
        $glue      = sprintf(',%s%s', PHP_EOL, str_repeat(' ', 7));

        return sprintf($template, implode($glue, $formatted));
    }

    /**
     * Format a reference to the array.
     *
     * @param array $array
     *
     * @return string
     */
    public static function formatRef(array $array)
    {
        return sprintf('Array(%d)', count($array));
    }
}

<?php

/*
 * This file is part of PsySH
 *
 * (c) 2012 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Formatter;

use Psy\Formatter\RecursiveFormatter;

/**
 * A pretty-printer for arrays..
 */
class ArrayFormatter extends RecursiveFormatter
{
    /**
     * Format the array.
     *
     * @param array $array
     *
     * @return string
     */
    public static function format($array)
    {
        if (empty($array)) {
            return '[]';
        }

        $formatted = array_map(array(__CLASS__, 'formatValue'), $array);
        $template  = sprintf('[%s%s%%s%s   ]', PHP_EOL, str_repeat(' ', 7), PHP_EOL);
        $glue      = sprintf(',%s%s', PHP_EOL, str_repeat(' ', 7));

        return sprintf($template, implode($glue, $formatted));
    }

    /**
     * Format a reference to the array.
     *
     * @param array $array
     *
     * @return string
     */
    public static function formatRef($array)
    {
        return sprintf('Array(%d)', count($array));
    }
}

Fix Strict error again :)

Fix Strict error again :)


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
$base = Config::get("app.base", "");
# Index.
Route::get($base . '/', 'Home@showHome');

# News - aggregate + single
Route::get($base . '/news', 'News@showNews');
Route::get($base . '/news/{id}', 'News@showSingleNews')
	->where('id', '[0-9]+');

# Stats
Route::get($base . '/stats', 'Stats@showGraphs');
Route::get($base . '/stats.json', 'Stats@getGraphsAjax');

# IRC
Route::get($base . '/irc', 'IRC@show');

# Search
Route::any($base . '/search/{search?}', 'Search@showResults');

# Admin controller; adds extra auth + security
Route::controller($base . '/admin', 'Admin');

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

# Index.
Route::get('/', 'Home@showHome');

# News - aggregate + single
Route::get('/news', 'News@showNews');
Route::get('/news/{id}', 'News@showSingleNews')
	->where('id', '[0-9]+');

# Stats
Route::get('/stats', 'Stats@showGraphs');
Route::get('/stats.json', 'Stats@getGraphsAjax');

# IRC
Route::get('/irc', 'IRC@show');

# Search
Route::any('/search/{search?}', 'Search@showResults');

# Admin controller; adds extra auth + security
Route::controller('/admin', 'Admin');

Revert "Make routing work properly this time."

This reverts commit fa971ecfadf9b27ae797b3aa6913378de74dc01c.


<?php namespace Modules\Block\Tests\Integration;

class BlockRepositoryTest extends BaseBlockTest
{
    /** @test */
    public function it_creates_blocks()
    {
        $block = $this->block->create(['name' => 'testBlock', 'en' => ['body' => 'lorem en'], 'fr' => ['body' => 'lorem fr']]);
        $blocks = $this->block->all();

        $this->assertCount(1, $blocks);
        $this->assertEquals('testBlock', $block->name);
        $this->assertEquals('lorem en', $block->translate('en')->body);
        $this->assertEquals('lorem fr', $block->translate('fr')->body);
    }
}

<?php namespace Modules\Block\Tests\Integration;

use Faker\Factory;

class BlockRepositoryTest extends BaseBlockTest
{
    /** @test */
    public function it_creates_blocks()
    {
        $block = $this->block->create(['name' => 'testBlock', 'en' => ['body' => 'lorem en'], 'fr' => ['body' => 'lorem fr']]);
        $blocks = $this->block->all();

        $this->assertCount(1, $blocks);
        $this->assertEquals('testBlock', $block->name);
        $this->assertEquals('lorem en', $block->translate('en')->body);
        $this->assertEquals('lorem fr', $block->translate('fr')->body);
    }

    /** @test */
    public function it_gets_only_online_blocks()
    {
        $this->createRandomBlock();
        $this->createRandomBlock(true, true);
        $this->createRandomBlock(true, true);
        $this->createRandomBlock(true, false);

        $allBlocks = $this->block->all();
        $onlineBlocksFr = $this->block->allOnlineInLang('fr');
        $onlineBlocksEn = $this->block->allOnlineInLang('en');

        $this->assertCount(4, $allBlocks);
        $this->assertCount(2, $onlineBlocksFr);
        $this->assertCount(3, $onlineBlocksEn);
    }

    /**
     * Create a block with random properties
     * @param bool $statusEn
     * @param bool $statusFr
     * @return mixed
     */
    private function createRandomBlock($statusEn = false, $statusFr = false)
    {
        $factory = Factory::create();

        $data = [
            'name' => $factory->word,
            'en' => [
                'body' => $factory->text,
                'online' => $statusEn,
            ],
            'fr' => [
                'body' => $factory->text,
                'online' => $statusFr,
            ],
        ];

        return $this->block->create($data);
    }
}

Test for getting all blocks in given language


<?php
/*
Template Name: Kontakt
*/
?>

        <?php while (have_posts()) : the_post(); ?>
        <?php get_template_part('templates/page', 'header'); ?>

                <?php echo do_shortcode( '[contact-form-7 id="117" title="Kontaktformular"]' ); ?>

                <?php get_template_part('templates/content', 'page'); ?>
                <?php endwhile ?>

<?php
/*
Template Name: Kontakt
*/
?>

        <?php while (have_posts()) : the_post(); ?>
        <?php get_template_part('templates/page', 'header'); ?>

                <?php get_template_part('templates/content', 'page'); ?>
                <?php endwhile ?>

                <?php the_field('contact_col2'); ?>

Change contact template to extra column.


<?php
    namespace DB;

    include (SYSTEM_PATH . 'db/IDriver.php');

    class DB
    {
        private $dbDriver;

        public function __construct()
        {
            $config =& loadClass('Config', 'Core');
            $cfg = $config->load('DB');

            if ($cfg !== false)
            {
                $this->driver($cfg['driver']);
                $this->connect($cfg['host'], $cfg['user'], $cfg['password']);
                $this->database($cfg['database'], false);
            }
        }

        public function driver($name)
        {
            $loader =& loadClass('Loader', 'Core');
            $this->dbDriver = $loader->dbDriver($name);
        }

        public function connect($host, $user, $password='')
        {
            $this->dbDriver->connect($host, $user, $password);
        }

        public function database($name, $create=false)
        {
            $this->dbDriver->database($name);
        }

        public function query($sql, $data=[])
        {

        }
    }

?>

<?php
    namespace DB;

    include (SYSTEM_PATH . 'db/IDriver.php');

    class DB
    {
        private $dbDriver;

        public function __construct()
        {
            $config =& loadClass('Config', 'Core');
            $cfg = $config->load('DB');

            if ($cfg !== false)
            {
                $this->driver($cfg['driver']);
                $this->connect($cfg['host'], $cfg['user'], $cfg['password']);
                $this->database($cfg['database'], false);
            }
        }

        public function driver($name)
        {
            $loader =& loadClass('Loader', 'Core');
            $this->dbDriver = $loader->dbDriver($name);
        }

        public function connect($host, $user, $password='')
        {
            $this->dbDriver->connect($host, $user, $password);
        }

        public function database($name, $create=false)
        {
            $this->dbDriver->database($name);
        }

        public function query($sql, $data=[])
        {
            if (count($data) > 0)
            {
                return $this->dbDriver->bind($sql, $data);
            }
            else
            {
                return $this->dbDriver->query($sql);
            }
        }
    }

?>

Use normal query if no data is passed or using bind method if there is data passed


<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array|null
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error('GraphQL request failed.', [
                'query' => $query,
                'variables' => $variables,
                'exception' => $exception->getMessage(),
            ]);

            return null;
        }

        return $response ? $response->getData() : null;
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array|null
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables);
    }
}

<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error('GraphQL request failed.', [
                'query' => $query,
                'variables' => $variables,
                'exception' => $exception->getMessage(),
            ]);

            return [];
        }

        return $response ? $response->getData() : [];
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables);
    }
}

Return array consistently from query method


<?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\Promotion\Model;

use Sylius\Component\Resource\Model\ResourceInterface;

interface CatalogPromotionActionInterface extends ResourceInterface
{
    public const TYPE_PERCENTAGE_DISCOUNT = 'percentage_product_discount';

    public function setType(?string $type): void;

    public function setConfiguration(array $configuration): void;

    public function setCatalogPromotion(?CatalogPromotionInterface $catalogPromotion): void;

    public function getType(): ?string;

    public function getConfiguration(): array;

    public function getCatalogPromotion(): ?CatalogPromotionInterface;
}

<?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\Promotion\Model;

use Sylius\Component\Resource\Model\ResourceInterface;

interface CatalogPromotionActionInterface extends ResourceInterface
{
    public const TYPE_PERCENTAGE_DISCOUNT = 'percentage_discount';

    public function setType(?string $type): void;

    public function setConfiguration(array $configuration): void;

    public function setCatalogPromotion(?CatalogPromotionInterface $catalogPromotion): void;

    public function getType(): ?string;

    public function getConfiguration(): array;

    public function getCatalogPromotion(): ?CatalogPromotionInterface;
}

Change action configuration amount to float


<?php
namespace NZTim\Mailchimp;

use Illuminate\Support\ServiceProvider;

class MailchimpServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function boot()
    {
        $this->app->bind(Mailchimp::class, function () {
            return new Mailchimp(env('MC_KEY'));
        });
        $this->publishes([
            __DIR__.'/../config/mailchimp.php' => config_path('mailchimp.php'),
        ]);
    }

    public function register()
    {
        $this->app->bind('mailchimp', function () {
            return $this->app->make(Mailchimp::class);
        });
        $this->mergeConfigFrom(__DIR__.'/../config/mailchimp.php', 'mailchimp');
    }
}

<?php
namespace NZTim\Mailchimp;

use Illuminate\Support\ServiceProvider;

class MailchimpServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function boot()
    {
        $this->app->bind(Mailchimp::class, function () {
            return new Mailchimp(config('mailchimp.apikey'));
        });
        $this->publishes([
            __DIR__.'/../config/mailchimp.php' => config_path('mailchimp.php'),
        ]);
    }

    public function register()
    {
        $this->app->bind('mailchimp', function () {
            return $this->app->make(Mailchimp::class);
        });
        $this->mergeConfigFrom(__DIR__.'/../config/mailchimp.php', 'mailchimp');
    }
}

Use config instead of env value directly


<?php
chdir(dirname(__DIR__));
require_once 'vendor/ZendFramework/library/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array('Zend\Loader\StandardAutoloader' => array()));

$appConfig = include 'config/application.config.php';

$listenerOptions  = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']);
$defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions);
$defaultListeners->getConfigListener()->addConfigGlobPath('config/autoload/*.config.php');

$moduleManager = new Zend\Module\Manager($appConfig['modules']);
$moduleManager->events()->attachAggregate($defaultListeners);
$moduleManager->loadModules();

// Create application, bootstrap, and run
$bootstrap   = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig());
$application = new Zend\Mvc\Application;
$bootstrap->bootstrap($application);
$application->run()->send();

<?php
chdir(dirname(__DIR__));
require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array('Zend\Loader\StandardAutoloader' => array()));

$appConfig = include 'config/application.config.php';

$listenerOptions  = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']);
$defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions);
$defaultListeners->getConfigListener()->addConfigGlobPath('config/autoload/*.config.php');

$moduleManager = new Zend\Module\Manager($appConfig['modules']);
$moduleManager->events()->attachAggregate($defaultListeners);
$moduleManager->loadModules();

// Create application, bootstrap, and run
$bootstrap   = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig());
$application = new Zend\Mvc\Application;
$bootstrap->bootstrap($application);
$application->run()->send();

Check for ZF2_PATH env var when including ZF2 AutoloaderFactory


<?php
/**
 * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

class Test_Avatar extends PHPUnit_Framework_TestCase {

	public function testAvatar() {

		$avatar = new \OC_Avatar(\OC_User::getUser());

		$this->assertEquals(false, $avatar->get());

		$expected = new OC_Image(\OC::$SERVERROOT.'/tests/data/testavatar.png');
		$expected->resize(64);
		$avatar->set($expected->data());
		$this->assertEquals($expected->data(), $avatar->get()->data());

		$avatar->remove();
		$this->assertEquals(false, $avatar->get());
	}

	public function testAvatarApi() {
		$avatarManager = \OC::$server->getAvatarManager();
		$avatar = $avatarManager->getAvatar(\OC_User::getUser());

		$this->assertEquals(false, $avatar->get());

		$expected = new OC_Image(\OC::$SERVERROOT.'/tests/data/testavatar.png');
		$expected->resize(64);
		$avatar->set($expected->data());
		$this->assertEquals($expected->data(), $avatar->get()->data());

		$avatar->remove();
		$this->assertEquals(false, $avatar->get());
	}
}

<?php

/**
 * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */
class Test_Avatar extends PHPUnit_Framework_TestCase {

	private $user;

	public function setUp() {
		$this->user = uniqid();
		$storage = new \OC\Files\Storage\Temporary(array());
		\OC\Files\Filesystem::mount($storage, array(), '/' . $this->user . '/');
	}

	public function testAvatar() {

		$avatar = new \OC_Avatar($this->user);

		$this->assertEquals(false, $avatar->get());

		$expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png');
		$expected->resize(64);
		$avatar->set($expected->data());
		$this->assertEquals($expected->data(), $avatar->get()->data());

		$avatar->remove();
		$this->assertEquals(false, $avatar->get());
	}

	public function testAvatarApi() {
		$avatarManager = \OC::$server->getAvatarManager();
		$avatar = $avatarManager->getAvatar($this->user);

		$this->assertEquals(false, $avatar->get());

		$expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png');
		$expected->resize(64);
		$avatar->set($expected->data());
		$this->assertEquals($expected->data(), $avatar->get()->data());

		$avatar->remove();
		$this->assertEquals(false, $avatar->get());
	}
}

Make OC_Avatar unit tests independent of currently loggedin user


<?php

namespace FluxBB;

use Illuminate\Support\Facades\Facade;
use Config;

class Core extends Facade
{
    protected static function getFacadeAccessor()
    {
        return static::$app;
    }

    public static function isInstalled()
    {
        $app = static::$app;
        // TODO: Use Config::has('fluxbb') once this issue is resolved:
        // https://github.com/laravel/framework/issues/63
        return file_exists($app['path'].'/config/fluxbb.php');
    }

    public static function version()
    {
        return '2.0.0-alpha1';
    }
}

<?php

namespace FluxBB;

use Illuminate\Support\Facades\Facade;
use Config;

class Core extends Facade
{
    protected static function getFacadeAccessor()
    {
        return static::$app;
    }

    public static function isInstalled()
    {
        return static::$app['config']->hasGroup('fluxbb');
    }

    public static function version()
    {
        return '2.0.0-alpha1';
    }
}

Use Config::hasGroup() to detect where our config has been created.


<?php

require_once 'Twig/Autoloader.php';

Twig_Autoloader::register();

class TwigWrapper
{
  private $loader;
  private $twig;
  private $template;
  private $data;

  public function __construct($template_directory, $filename)
  {
    $this->loader = new Twig_Loader_Filesystem($template_directory);
    $this->twig = new Twig_Environment($this->loader);
    $this->template = $this->twig->loadTemplate($filename);

    $this->data = array();
  }

  public function assign($key, $value)
  {
    $this->data[$key] = $value;
  }

  public function display()
  {
    $this->template->display($this->data);
  }
}

?>

<?php

require_once 'Twig/Autoloader.php';

Twig_Autoloader::register();

class TwigWrapper
{
  protected $loader;
  protected $twig;
  protected $template;
  protected $data;

  public function __construct($template_directory, $filename)
  {
    $this->loader = new Twig_Loader_Filesystem($template_directory);
    $this->twig = new Twig_Environment($this->loader);
    $this->template = $this->twig->loadTemplate($filename);

    $this->data = array();
  }

  public function assign($key, $value)
  {
    $this->data[$key] = $value;
  }

  public function display()
  {
    $this->template->display($this->data);
  }
}

?>

Change variables to be protected so that subclasses can access them.


<?php

return array (

    /*
     * Directory to log to
     */
    'path' => __DIR__ . '/../storage/logs',

    /*
     * Name of log file
     */
    'name' => 'tomahawk_' . date('Y_m_d'),

);

<?php

return array (

    /*
     * Directory to log to
     */
    'path' => __DIR__ . '/../storage/logs',

    /*
     * Name of log file
     */
    'name' => 'tomahawk.log',

);

Add missing extension and remove date from log name


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Helpers\Helper;

class RandomController extends Controller
{
    /**
     * Picks a random number between min and max.
     *
     * @param  Request $request
     * @param  integer $min     The minimum number
     * @param  integer $max     The maximum number
     * @return Response
     */
    public function number(Request $request, $min = 0, $max = 100)
    {
        $min = intval($min);
        $max = intval($max);

        return Helper::text(rand($min, $max));
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Helpers\Helper;

class RandomController extends Controller
{
    /**
     * Picks a random number between min and max.
     *
     * @param  Request $request
     * @param  string  $number
     * @param  integer $min     The minimum number
     * @param  integer $max     The maximum number
     * @return Response
     */
    public function number(Request $request, $number, $min = 0, $max = 100)
    {
        $min = intval($min);
        $max = intval($max);

        return Helper::text(rand($min, $max));
    }
}

Fix issue with /random/number where it parsed route as number


<?php
/*
 * This file is part of the ws/array-field-type-extension package.
 *
 * (c) Benjamin Georgeault <github@wedgesama.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Bolt\Extension\WS\ArrayFieldExtension;

use Bolt\Field\FieldInterface;

/**
 * ArrayField
 *
 * @author Benjamin Georgeault <github@wedgesama.fr>
 */
class ArrayField implements FieldInterface
{
    public function getName()
    {
        return 'array';
    }

    public function getTemplate()
    {
        return '_array.twig';
    }

    public function getStorageType()
    {
        return 'array';
    }

    public function getStorageOptions()
    {
        return array(
            'children' => array(),
            'default' => ''
        );
    }
}

<?php
/*
 * This file is part of the ws/array-field-type-extension package.
 *
 * (c) Benjamin Georgeault <github@wedgesama.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Bolt\Extension\WS\ArrayFieldExtension;

use Bolt\Field\FieldInterface;

/**
 * ArrayField
 *
 * @author Benjamin Georgeault <github@wedgesama.fr>
 */
class ArrayField implements FieldInterface
{
    public function getName()
    {
        return 'array';
    }

    public function getTemplate()
    {
        return '_array.twig';
    }

    public function getStorageType()
    {
        return 'array';
    }

    public function getStorageOptions()
    {
        return array(
            'children' => array(),
            'nullable' => true,
        );
    }
}

Make field nullable instead of set default value


<?php

/**
 * Used to convert a data object to a json object
 *
 * @author marcus@silverstripe.com.au
 * @license BSD License http://silverstripe.org/bsd-license/
 */
class DataObjectSetJsonConverter {

	public function convert(DataObjectSet $set) {
		$ret = new stdClass();
		$ret->items = array();
		foreach ($set as $item) {
			$ret->items[] = $item->toMap();
		}

		return Convert::raw2json($ret);
	}
}

<?php

/**
 * Used to convert a data object to a json object
 *
 * @author marcus@silverstripe.com.au
 * @license BSD License http://silverstripe.org/bsd-license/
 */
class DataObjectSetJsonConverter {

	public function convert(DataObjectSet $set) {
		$ret = new stdClass();
		$ret->items = array();
		foreach ($set as $item) {
			if (method_exists($item, 'toMap')) {
				$ret->items[] = $item->toMap();
			} else {
				$ret->items[] = $item;
			}
		}

		return Convert::raw2json($ret);
	}
}

Check for toMap before calling.

Check for toMap before calling.


<?php

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

class AddActiveFieldToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table("users", function(Blueprint $table) {
            $table->char("active", 1)->default("Y");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table("users", function($table) {
            $table->dropColumn('logged_in_at');
        });
    }
}

<?php

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

class AddActiveFieldToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table("users", function(Blueprint $table) {
            $table->char("active", 1)->default("Y");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table("users", function($table) {
            $table->dropColumn('active');
        });
    }
}

Fix latest migration's down() function

Fix latest migration's down() function


<?php

namespace FullyBaked\Pslackr\Messages;

class CustomMessage implements Message
{
    protected $text;

    protected $optionalFields = [];

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

    public function asJson()
    {
        $message = ['text' => 'This is a test message'];

        $message = array_merge($message, $this->optionalFields);

        return json_encode($message);
    }

    public function channel($channelName)
    {
        $this->optionalFields['channel'] = $channelName;
    }

    public function username($username)
    {
        $this->optionalFields['username'] = $username;
    }

    public function iconEmoji($token)
    {
        $this->optionalFields['icon_emoji'] = $token;
    }

    public function iconUrl($url)
    {
        $this->optionalFields['icon_url'] = $url;
    }
}

<?php

namespace FullyBaked\Pslackr\Messages;

class CustomMessage implements Message
{
    protected $text;

    protected $optionalFields = [];

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

    public function asJson()
    {
        $message = ['text' => $this->text];

        $message = array_merge($message, $this->optionalFields);

        return json_encode($message);
    }

    public function channel($channelName)
    {
        $this->optionalFields['channel'] = $channelName;
    }

    public function username($username)
    {
        $this->optionalFields['username'] = $username;
    }

    public function iconEmoji($token)
    {
        $this->optionalFields['icon_emoji'] = $token;
    }

    public function iconUrl($url)
    {
        $this->optionalFields['icon_url'] = $url;
    }
}

Change static placeholder text with instance var


<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

use App\Models\BeatmapDiscussion;

$factory->define(BeatmapDiscussion::class, function (Faker\Generator $faker) use ($factory) {
    $type = rand(0, 1) === 0 ? 'timeline' : 'general';

    return $factory->raw(BeatmapDiscussion::class, $type);
});

$factory->defineAs(BeatmapDiscussion::class, 'timeline', function () {
    return  [
        'timestamp' => 0,
        'message_type' => array_rand(BeatmapDiscussion::MESSAGE_TYPES),
    ];
});

$factory->defineAs(BeatmapDiscussion::class, 'general', function () {
    return  [
        'timestamp' => null,
        'message_type' => null,
    ];
});

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

use App\Models\BeatmapDiscussion;

$factory->define(BeatmapDiscussion::class, function (Faker\Generator $faker) use ($factory) {
    $type = rand(0, 1) === 0 ? 'timeline' : 'general';

    return $factory->raw(BeatmapDiscussion::class, $type);
});

$factory->defineAs(BeatmapDiscussion::class, 'timeline', function () {
    return  [
        'timestamp' => 0,
        'message_type' => array_rand(BeatmapDiscussion::RESOLVABLE_TYPES),
    ];
});

$factory->defineAs(BeatmapDiscussion::class, 'general', function () {
    return  [
        'timestamp' => null,
        'message_type' => array_rand(BeatmapDiscussion::RESOLVABLE_TYPES),
    ];
});

Fix message type in factory

Fix message type in factory


<?php

namespace Kunstmaan\SeoBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * SeoType
 */
class SeoType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', 'hidden')
                ->add('metaTitle', null, array('label' => 'Title', 'attr' => array('info_text' => 'Use %websitetitle% to dynamic fill in the main website title.')))
                ->add('metaAuthor', null, array('label' => 'Meta author'))
                ->add('metaDescription', null, array('label' => 'Meta description'))
                ->add('metaKeywords', null, array('label' => 'Meta keywords'))
                ->add('metaRobots', null, array('label' => 'Meta robots'))
                ->add('metaRevised', null, array('label' => 'Meta revised'))
                ->add('extraMetadata', 'textarea', array('label' => 'Extra metadata', 'required' => false));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'data_class' => 'Kunstmaan\SeoBundle\Entity\Seo',
        ));
    }
}

<?php

namespace Kunstmaan\SeoBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * SeoType
 */
class SeoType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', 'hidden')
		->add('metaTitle', null, array(
		    'label' => 'Meta title',
		    'attr' => array(
			'info_text' => 'Sets the title in the head of your document. It should be short and descriptive. The content of the "Navigation title" field will be used if this field is left blank.'
		    )
		))
                ->add('metaAuthor', null, array('label' => 'Meta author'))
                ->add('metaDescription', null, array('label' => 'Meta description'))
                ->add('metaKeywords', null, array('label' => 'Meta keywords'))
                ->add('metaRobots', null, array('label' => 'Meta robots'))
                ->add('metaRevised', null, array('label' => 'Meta revised'))
                ->add('extraMetadata', 'textarea', array('label' => 'Extra metadata', 'required' => false));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'data_class' => 'Kunstmaan\SeoBundle\Entity\Seo',
        ));
    }
}

Update the admin interface and demo site generator

Update the admin interface to feature a fully responsive, fully retina, cleaned up look and feel based on Bootstrap 3. Simultaniously updated the generated demo site to be more in line with what we use as a starting point for our websites.

While this commit is squashed under my name, this is the result of the hard work by too many people to mention by name.


<?php
namespace Stirling\Core;

use InvalidArgumentException;

class Config
{

    protected static $instance;

    private $properties;

    /**
     * Config constructor.
     * @param string $configPath
     */
    private function __construct($configPath)
    {
        $this->properties = Array("git" => null, "name" => null, "version" => null);
        if (file_exists($configPath)) {
            $json = json_decode(file_get_contents($configPath), true);
            if ($json != null) {
                $this->properties = array_merge($this->properties, $json);
            }
        }
    }

    public static function instance($configPath = "./default.json")
    {
        if (self::$instance == null) {
            self::$instance = new Config($configPath);
        }
        return self::$instance;
    }

    public function __get($name)
    {
        if (key_exists($name, $this->properties)) {
            return $this->properties[$name];
        } else {
            throw new InvalidArgumentException("Property '" . $name . "' does not exist");
        }
    }

    public function getConfigMap()
    {
        $temp = $this->properties;
        unset($temp["version"]);
        unset($temp["name"]);
        unset($temp["git"]);
        return $temp;
    }
}

<?php
namespace Stirling\Core;

use InvalidArgumentException;

class Config
{

    protected static $instance;

    private $properties;

    /**
     * Config constructor.
     * @param string $configPath
     */
    private function __construct($configPath)
    {
        $this->properties = Array("git" => null, "name" => null, "version" => null);
        if (file_exists($configPath)) {
            $json = json_decode(file_get_contents($configPath), true);
            if ($json != null) {
                $this->properties = array_merge($this->properties, $json);
            }
        }
    }

    public static function instance($configPath = "./resources/default.json")
    {
        if (self::$instance == null) {
            self::$instance = new Config($configPath);
        }
        return self::$instance;
    }

    public function __get($name)
    {
        if (key_exists($name, $this->properties)) {
            return $this->properties[$name];
        } else {
            throw new InvalidArgumentException("Property '" . $name . "' does not exist");
        }
    }

    public function getConfigMap()
    {
        $temp = $this->properties;
        unset($temp["version"]);
        unset($temp["name"]);
        unset($temp["git"]);
        return $temp;
    }
}

Change default path for the config json

Change default path for the config json


<?php

namespace Aerys;

use Amp\Struct;

class InternalRequest {
    use Struct;
    public $isEncrypted;
    public $cryptoInfo;
    public $clientPort;
    public $clientAddr;
    public $serverPort;
    public $serverAddr;
    public $trace;
    public $protocol;
    public $method;
    public $headers;
    public $body;
    public $uri;
    public $uriRaw;
    public $uriHost;
    public $uriPort;
    public $uriPath;
    public $uriQuery;
    public $cookies;
    public $remaining;
    public $time;
    public $locals;
    public $debug;

    public function generateCookies() {
        $cookies = $this->headers["COOKIE"] ?? [""];
        $this->cookies = array_merge(...array_map('\Aerys\parseCookie', $cookies));
    }
}

<?php

namespace Aerys;

use Amp\Struct;

class InternalRequest {
    use Struct;
    public $isEncrypted;
    public $cryptoInfo;
    public $clientPort;
    public $clientAddr;
    public $serverPort;
    public $serverAddr;
    public $trace;
    public $protocol;
    public $method;
    public $headers;
    public $body;
    public $uri;
    public $uriRaw;
    public $uriHost;
    public $uriPort;
    public $uriPath;
    public $uriQuery;
    public $cookies;
    public $remaining;
    public $time;
    public $locals;

    public function generateCookies() {
        $cookies = $this->headers["COOKIE"] ?? [""];
        $this->cookies = array_merge(...array_map('\Aerys\parseCookie', $cookies));
    }
}

Remove superfluous debug property from internal request struct


<?php

namespace allejo\DaPulse;

use allejo\DaPulse\Objects\ApiObject;

class PulseColumn extends ApiObject
{
    const Date   = "date";
    const Person = "person";
    const Status = "status";
    const Text   = "text";

    protected $id;
    protected $title;
    protected $type;
    protected $empty_text;
    protected $labels;

    public function getId ()
    {
        return $this->id;
    }

    public function getTitle ()
    {
        return $this->title;
    }

    public function getType ()
    {
        return $this->type;
    }

    public function getEmptyText ()
    {
        return $this->empty_text;
    }

    public function getLabels ()
    {
        return $this->labels;
    }
}

<?php

namespace allejo\DaPulse;

use allejo\DaPulse\Objects\ApiObject;

class PulseColumn extends ApiObject
{
    const API_PREFIX = "boards";

    const Date   = "date";
    const Person = "person";
    const Status = "status";
    const Text   = "text";

    protected $id;
    protected $title;
    protected $type;
    protected $empty_text;
    protected $labels;
    protected $board_id;

    public function getId ()
    {
        return $this->id;
    }

    public function getTitle ()
    {
        return $this->title;
    }

    public function getType ()
    {
        return $this->type;
    }

    public function getEmptyText ()
    {
        return $this->empty_text;
    }

    public function getLabels ()
    {
        return $this->labels;
    }

    public function getBoardId ()
    {
        return $this->board_id;
    }

    public function editTitle ($title)
    {
        $this->editField("title", $title);
    }

    public function editLabels ($labels)
    {
        $this->editField("labels", $labels);
    }

    public function deleteColumn ()
    {
        $this->checkInvalid();

        self::sendDelete($this->getColumnsUrl());

        $this->deletedObject = true;
    }

    private function editField ($field, $value)
    {
        $this->checkInvalid();

        $postParams = array(
            $field => $value
        );

        self::sendPut($this->getColumnsUrl(), $postParams);

        $this->$field = $value;
    }

    private function getColumnsUrl ()
    {
        return sprintf("%s/%d/columns/%s.json", parent::apiEndpoint(), $this->getBoardId(), $this->getId());
    }
}

Support editing and deleting columns

Support editing and deleting columns


<?php

namespace Infrastructure\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Infrastructure\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [

    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

<?php

namespace Infrastructure\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Infrastructure\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [

    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        /** include laravel csrf-token on jwt token **/
        'web' => \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
    ];
}

Include csrf-token into JWT on every web request


<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;

class App
{
    public function run(): void
    {
        $client = new Client([
            "http_errors"   =>  false,
        ]);

        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

        $response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class App
{
    public function run(): void
    {
        $client = new Client([
            "http_errors"   =>  false,
        ]);

        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

        $response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        $this->respond($response);
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

Move the response handling to a separate method


<?php

class ExPage_Index extends ExPage_Abstract
{
    public function isLastPage()
    {
        return (count($this->find('td.ptds + td.ptdd')) > 0);
    }

    public function getGalleries()
    {
        $ret = array();

        $links = $this->find('.itg.gld .gl1t .glname a');
        foreach ($links as $linkElem) {
            $gallery = new stdClass();

            $link = pq($linkElem);
            $gallery->name = $link->text();

            preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);

            if (isset($matches[1]) && isset($matches[2])) {
                $gallery->exhenid = $matches[1];
                $gallery->hash = $matches[2];

                $ret[] = $gallery;
            }
        }

        return $ret;
    }
}

<?php

class ExPage_Index extends ExPage_Abstract
{
    public function isLastPage()
    {
        return (count($this->find('td.ptds + td.ptdd')) > 0);
    }

    public function getGalleries()
    {
        $ret = array();

        $links = $this->find('.itg.gld .gl1t a');
        foreach ($links as $linkElem) {
            $gallery = new stdClass();

            $link = pq($linkElem);
            $gallery->name = $link->text();

            preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);

            if (isset($matches[1]) && isset($matches[2])) {
                $gallery->exhenid = $matches[1];
                $gallery->hash = $matches[2];

                $ret[] = $gallery;
            }
        }

        return $ret;
    }
}

Fix gallery URL detection for feeds... again

They changed the HTML structure again it seems


<?php

namespace PhpXmlRpc;

/**
 * In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
 * For usage, see any file in the demo/client directory
 */
class Autoloader
{
    /**
     * Registers PhpXmlRpc\Autoloader as an SPL autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader or not.
     */
    public static function register($prepend = false)
    {
        spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
    }

    /**
     * Handles autoloading of classes.
     *
     * @param string $class A class name.
     */
    public static function autoload($class)
    {
        if (0 !== strpos($class, 'PhpXmlRpc\\')) {
            return;
        }

        if (is_file($file = __DIR__ . str_replace('PhpXmlRpc\\', '/', $class).'.php')) {
            require $file;
        }
    }
}

<?php

namespace PhpXmlRpc;

/**
 * In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
 * For usage, see any file in the demo/client directory
 */
class Autoloader
{
    /**
     * Registers PhpXmlRpc\Autoloader as an SPL autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader or not.
     */
    public static function register($prepend = false)
    {
        spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
    }

    /**
     * Handles autoloading of classes.
     *
     * @param string $class A class name.
     */
    public static function autoload($class)
    {
        if (0 !== strpos($class, 'PhpXmlRpc\\')) {
            return;
        }

        if (is_file($file = __DIR__ . str_replace(array('PhpXmlRpc\\', '\\'), '/', $class).'.php')) {
            require $file;
        }
    }
}

Fix autoloader to work with helper classes on linux


<?php

namespace SlimJson;

use Slim\Slim;

class View extends \Slim\View {

  /**
   * @param int|string $status
   * @param array|null $data
   * @return void
   */
  public function render($status, $data = null)
  {
    $app = Slim::getInstance();
    $response = $this->all();

    $status = \intval($status);
    $app->response()->status($status);
    if ($app->config(Config::Status)) {
      $response['_status'] = $status;
    }

    if (isset($response['flash']) && \is_object($response['flash'])) {
      $flash = $this->data->flash->getMessages();
      if (count($flash)) {
        $response['flash'] = $flash;
      } else {
        unset($response['flash']);
      }
    }

    $app->response()->header('Content-Type', 'application/json');
    $app->response()->body(json_encode($response, $app->config(Config::JsonEncodeOptions)));
  }

}

<?php

namespace SlimJson;

use Slim\Slim;

class View extends \Slim\View {

  /**
   * @param int|string $status
   * @param array|null $data
   * @return void
   */
  public function render($status, $data = null)
  {
    $app = Slim::getInstance();
    $response = $this->all();

    $status = \intval($status);
    $app->response()->status($status);
    if ($app->config(Config::Status)) {
      $response['_status'] = $status;
    }

    if (isset($response['flash']) && \is_object($response['flash'])) {
      $flash = $this->data->flash->getMessages();
      if (count($flash)) {
        $response['flash'] = $flash;
      } else {
        unset($response['flash']);
      }
    }

    $app->response()->header('Content-Type', 'application/json');
    $body = json_encode($response, $app->config(Config::JsonEncodeOptions)));
    if($status == 404){
        return $body;
    }else{
        $app->response()->body($body);
    }

}

Fix render function so 404 body is not ignored by slim


<?php

namespace Checkdomain\TeleCash\IPG\API\Response\Action;

use Checkdomain\TeleCash\IPG\API\Response\Action;
use Checkdomain\TeleCash\IPG\API\Service\OrderService;

/**
 * Class Validation
 */
class Validation extends Action
{

    /**
     * @param \DOMDocument $responseDoc
     *
     * @throws \Exception
     */
    public function __construct(\DOMDocument $responseDoc)
    {
        $actionResponse = $responseDoc->getElementsByTagNameNS(OrderService::NAMESPACE_N3, 'IPGApiActionResponse');
        $success        = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N3, 'successfully');

        if ($actionResponse->length > 0) {
            $this->wasSuccessful = ($success === 'true');
        } else {
            throw new \Exception("Validate Call failed " . $responseDoc->saveXML());
        }
    }

}

<?php

namespace Checkdomain\TeleCash\IPG\API\Response\Action;

use Checkdomain\TeleCash\IPG\API\Response\Action;
use Checkdomain\TeleCash\IPG\API\Service\OrderService;

/**
 * Class Validation
 */
class Validation extends Action
{

    /**
     * @param \DOMDocument $responseDoc
     *
     * @throws \Exception
     */
    public function __construct(\DOMDocument $responseDoc)
    {
        $actionResponse = $responseDoc->getElementsByTagNameNS(OrderService::NAMESPACE_N3, 'IPGApiActionResponse');
        $success        = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N3, 'successfully');

        if ($actionResponse->length > 0) {
            $this->wasSuccessful = ($success === 'true');
            if (false === $this->wasSuccessful) {
                $this->errorMessage = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N2, 'ErrorMessage');
            }
        } else {
            throw new \Exception("Validate Call failed " . $responseDoc->saveXML());
        }
    }

}

Set error message if validation fails

Change: Set error message if validation fails


<?php

namespace atk4\ui\tests;

class TemplateTest extends \atk4\core\PHPUnit_AgileTestCase
{
    /**
     * Test constructor.
     */
    public function testTesting()
    {
        $this->assertEquals('foo', 'foo');

        throw new \atk4\core\Exception(["testing", 'foo'=>'bar']);
    }

}

<?php

namespace atk4\ui\tests;

class TemplateTest extends \atk4\core\PHPUnit_AgileTestCase
{
    /**
     * Test constructor.
     */
    public function testTesting()
    {
        $this->assertEquals('foo', 'foo');
    }

}

Fix test case testing test

Fix test case testing test


<?php
App::uses('CroogoTestCase', 'TestSuite');

/**
 *  AllCorePluginsTest
 *
 */
class AllCorePluginsTest extends PHPUnit_Framework_TestSuite {

	public static function suite() {
		$suite = new CakeTestSuite('All core plugins tests');
		$path = CakePlugin::path('Acl') . 'Test' . DS . 'Case' . DS;
		$suite->addTestFile($path . 'AllAclTestsTest.php');
		$path = CakePlugin::path('Extensions') . DS . 'Test' . DS . 'Case' . DS;
		$suite->addTestFile($path . 'AllExtensionsTestsTest.php');
		return $suite;
	}

}

<?php
App::uses('CroogoTestCase', 'TestSuite');

/**
 *  AllCorePluginsTest
 *
 */
class AllCorePluginsTest extends PHPUnit_Framework_TestSuite {

	public static function suite() {
		$suite = new CakeTestSuite('All core plugins tests');
		$plugins = array(
			'Acl', 'Extensions', 'FileManager', 'Tinymce',
		);
		foreach ($plugins as $plugin) {
			CakePlugin::load($plugin);
			$suite->addTestDirectoryRecursive(CakePlugin::path($plugin) . 'Test' . DS);
		}
		return $suite;
	}

}

Include Extensions, FileManager and Tinymce in AllCoreTests


<?php

namespace Bolt\Provider;

use Bolt\Routing\Canonical;
use Silex\Application;
use Silex\ServiceProviderInterface;

/**
 * Canonical service provider.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class CanonicalServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['canonical'] = $app->share(
            function ($app) {
                return new Canonical(
                    $app['url_generator'],
                    $app['config']->get('general/force_ssl'),
                    $app['config']->get('general/canonical')
                );
            }
        );
    }

    public function boot(Application $app)
    {
        if (isset($app['canonical'])) {
            $app['dispatcher']->addSubscriber($app['canonical']);
        }
    }
}

<?php

namespace Bolt\Provider;

use Bolt\Routing\Canonical;
use Silex\Application;
use Silex\ServiceProviderInterface;

/**
 * Canonical service provider.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class CanonicalServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['canonical'] = $app->share(
            function ($app) {
                return new Canonical(
                    $app['url_generator.lazy'],
                    $app['config']->get('general/force_ssl'),
                    $app['config']->get('general/canonical')
                );
            }
        );
    }

    public function boot(Application $app)
    {
        if (isset($app['canonical'])) {
            $app['dispatcher']->addSubscriber($app['canonical']);
        }
    }
}

Use lazy URL generator as to prevent construction race


<?php
use Garden\Cli\Cli;
use Garden\Cli\Schema;

error_reporting(E_ALL); //E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR);
ini_set('display_errors', 'on');
ini_set('track_errors', 1);

date_default_timezone_set('America/Montreal');

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

$cli = new Cli();

$cli->description('Copy the labels from one github repo to another.')
    ->opt('from:f', 'The github repo to copy the labels from.', true)
    ->opt('to:t', 'The github repo to copy the labels to.', true)
    ->opt('token', 'The github access token. Uses the GITHUB_API_TOKEN if not specified.')
    ->opt('delete:d', 'Whether or not to delete extra labels.', false, 'boolean')
    ;

$args = $cli->parse($argv);

try {
    $sync = new \Vanilla\Github\GithubSync($args->getOpt('token', getenv('GITHUB_API_TOKEN')));
    $sync
        ->setFromRepo($args->getOpt('from'))
        ->setToRepo($args->getOpt('to'));

    $sync->syncLabels($args->getOpt('delete'));
} catch (Exception $ex) {
    echo $cli->red($ex->getMessage());
    return $ex->getCode();
}

<?php
use Garden\Cli\Cli;

error_reporting(E_ALL); //E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR);
ini_set('display_errors', 'on');
ini_set('track_errors', 1);

date_default_timezone_set('America/Montreal');

$paths = [
    __DIR__.'/../vendor/autoload.php', // locally
    __DIR__.'/../../../autoload.php' // dependency
];
foreach ($paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

$cli = new Cli();

$cli->opt('from:f', 'The github repo to copy the labels from.', true)
    ->opt('to:t', 'The github repo to copy the labels to.', true)
    ->opt('token', 'The github access token. Uses the GITHUB_API_TOKEN if not specified.')

    ->command('labels')
    ->description('Copy the labels from one github repo to another.')
    ->opt('delete:d', 'Whether or not to delete extra labels.', false, 'boolean')
    ;

$args = $cli->parse($argv);

try {
    $sync = new \Vanilla\Github\GithubSync($args->getOpt('token', getenv('GITHUB_API_TOKEN')));
    $sync
        ->setFromRepo($args->getOpt('from'))
        ->setToRepo($args->getOpt('to'));

    switch ($args->getCommand()) {
        case 'labels':
            $sync->syncLabels($args->getOpt('delete'));
            break;
    }
} catch (Exception $ex) {
    echo $cli->red($ex->getMessage());
    return $ex->getCode();
}

Change the label sync to use a command. Make the autoloader work with a global require.


<?php
declare(strict_types=1);

namespace Tests\Strategy;

use Moka\Strategy\ProphecyMockingStrategy;
use Prophecy\Prophecy\ObjectProphecy;

class ProphecyMockingStrategyTest extends MockingStrategyTestCase
{
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->setStrategy(new ProphecyMockingStrategy());
        $this->setMockType(ObjectProphecy::class);
    }
}

<?php
declare(strict_types=1);

namespace Tests\Strategy;

use Moka\Exception\MockNotCreatedException;
use Moka\Strategy\ProphecyMockingStrategy;
use Prophecy\Doubler\Doubler;
use Prophecy\Doubler\LazyDouble;
use Prophecy\Prophecy\ObjectProphecy;

class ProphecyMockingStrategyTest extends MockingStrategyTestCase
{
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->setStrategy(new ProphecyMockingStrategy());
        $this->setMockType(ObjectProphecy::class);
    }

    public function testGetWithCustomMockFailure()
    {
        $this->expectException(MockNotCreatedException::class);

        $this->strategy->get(new ObjectProphecy(new LazyDouble(new Doubler())));
    }
}

Test edge case in Prophecy strategy

Test edge case in Prophecy strategy


<?php

/*
 * This file is a part of the Validator library.
 *
 * (c) 2013 Ebidtech
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace EBT\Validator\Tests;

use EBT\Validator\ValidatorNumber;

/**
 * ValidatorNumberTest
 */
class ValidatorNumberTest extends TestCase
{
    /**
     * @param mixed     $value
     * @param int|float $min
     * @param int|float $max
     * @param bool      $expected
     *
     * @dataProvider providerRanges
     */
    public function testInRange($value, $min, $max, $expected)
    {
        $this->assertEquals($expected, ValidatorNumber::inRange($value, $min, $max));
    }

    /**
     * @return array
     */
    public function providerRanges()
    {
        return array(
            // value, min, max, expected,
            array(10, 5, 30, true)
        );
    }
}

<?php

/*
 * This file is a part of the Validator library.
 *
 * (c) 2013 Ebidtech
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace EBT\Validator\Tests;

use EBT\Validator\ValidatorNumber;

/**
 * ValidatorNumberTest
 */
class ValidatorNumberTest extends TestCase
{
    /**
     * @param mixed     $value
     * @param int|float $min
     * @param int|float $max
     * @param bool      $expected
     *
     * @dataProvider providerRanges
     */
    public function testInRange($value, $min, $max, $expected)
    {
        $this->assertEquals($expected, ValidatorNumber::inRange($value, $min, $max));
    }

    /**
     * @return array
     */
    public function providerRanges()
    {
        return array(
            // value, min, max, expected,
            array(10, 5, 30, true),
            array(10, 20, 30, false),
            array(40, 20, 30, false),
            array(7.5, 2.5, 8, true)
        );
    }
}

Add more tests to validator number

Add more tests to validator number


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

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generate hastag from a webpage</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Generate hastag from a webpage

      <?php
        $this->load->helper('form');
        echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        echo form_open("/Hashtags/generate_tags",array('class'=>'form-inline'));
      ?>

           <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required>

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

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

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generate hastag from a webpage</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Generate hastag from a webpage

      <?php
        $this->load->helper('form');
        echo form_open("/Hashtags/generate_tags",array)
      ?>
      <form class="form-inline" action="<?php echo "http://$_SERVER[HTTP_HOST]/index.php/Hashtags/generate_tags"?> method="POST">

           <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required>

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

Use normal without extra libs

Use normal without extra libs


<?php

namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;

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

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

        $rootNode->children()
            ->arrayNode('fabpot')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('i18n')->defaultFalse()->end()
                    ->booleanNode('debug')->defaultFalse()->end()
                    ->booleanNode('text')->defaultTrue()->end()
                    ->booleanNode('intl')->defaultTrue()->end()
                ->end()
            ->end();

        $rootNode->children()
            ->arrayNode('dms')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('textual_date')->defaultTrue()->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;

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

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

        $rootNode->children()
            ->arrayNode('fabpot')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('i18n')->defaultFalse()->end()
                    ->booleanNode('debug')->defaultFalse()->end()
                    ->booleanNode('text')->defaultTrue()->end()
                    ->booleanNode('intl')->defaultTrue()->end()
                ->end()
            ->end();

        $rootNode->children()
            ->arrayNode('dms')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('textual_date')->defaultTrue()->end()
                    ->booleanNode('pad_string')->defaultTrue()->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Add extension to DI configuration

Add extension to DI configuration


<?php

add_action( 'wp_ajax_pet-search', 'pet_search' );

function pet_search() {
	global $post;

	$meta_query = array(
		'relation' => 'AND'
	);

	foreach( ['sex', 'size', 'breed'] as $criterion ) {
		if ( isset( $_REQUEST[$criterion] ) && $_REQUEST[$criterion] != '' ) {
			$meta_query[] = array(
				'key' => $criterion,
				'value' => $_REQUEST[$criterion],
				'comapre' => '='
			);
		}
	}

	$posts = get_posts(array(
		'posts_per_page'  => 50,
		'post_type' => 'pet',
		'orderby' => 'ID',
		'order' => 'DESC',
		'meta_query' => $meta_query
	));

	// TODO: deal with zero results?

	foreach( $posts as $post ) {
		setup_postdata( $post );
?>
<li <?php post_class( 'small-1 large-4 columns' ) ?> id="post-<?php the_ID(); ?>">
	<div class="homepage-box">
		<?php get_template_part( 'parts/box', 'pet' ); ?>
	</div>
</li>
<?php
	}

	exit;
}

?>

<?php

add_action( 'wp_ajax_pet-search', 'pet_search' );
add_action( 'wp_ajax_nopriv_pet-search', 'pet_search' );

function pet_search() {
	global $post;

	$meta_query = array(
		'relation' => 'AND'
	);

	foreach( ['sex', 'size', 'breed'] as $criterion ) {
		if ( isset( $_REQUEST[$criterion] ) && $_REQUEST[$criterion] != '' ) {
			$meta_query[] = array(
				'key' => $criterion,
				'value' => $_REQUEST[$criterion],
				'comapre' => '='
			);
		}
	}

	$posts = get_posts(array(
		'posts_per_page'  => 50,
		'post_type' => 'pet',
		'orderby' => 'ID',
		'order' => 'DESC',
		'meta_query' => $meta_query
	));

	// TODO: deal with zero results?

	foreach( $posts as $post ) {
		setup_postdata( $post );
?>
<li <?php post_class( 'small-1 large-4 columns' ) ?> id="post-<?php the_ID(); ?>">
	<div class="homepage-box">
		<?php get_template_part( 'parts/box', 'pet' ); ?>
	</div>
</li>
<?php
	}

	exit;
}

?>

Allow pet search to non-admins as well

Allow pet search to non-admins as well


<?php

namespace RuiGomes\RssFeedFinder;

use Illuminate\Support\Collection;
use PHPHtmlParser\Dom;

class FeedFinder
{
    /**
     * @var \PHPHtmlParser\Dom
     */
    protected $dom;

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

    protected $feedTypes = [
        'application/rss+xml',
        'application/atom+xml',
    ];

    public function __construct($url)
    {
        $this->dom = new Dom();
        $this->url = $url;
    }

    public function find()
    {
        $this->dom->loadFromUrl($this->url);

        $feeds = new Collection($this->dom->find('link[rel=alternate]'));

        $feedUrls = $feeds->filter(function ($feed) {
            return in_array($feed->getAttribute('type'), $this->feedTypes);
        })->map(function ($feed) {
            return $feed->getAttribute('href');
        })->toArray();

        return $feedUrls;
    }

    public function setUrl($url)
    {
        $this->url = $url;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function setDom($dom)
    {
        $this->dom = $dom;
    }

    public function getDom()
    {
        return $this->dom;
    }
}

<?php

namespace RuiGomes\RssFeedFinder;

use Illuminate\Support\Collection;
use PHPHtmlParser\Dom;

class FeedFinder
{
    /**
     * @var \PHPHtmlParser\Dom
     */
    protected $dom;

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

    protected $feedTypes = [
        'application/rss+xml',
        'application/atom+xml',
    ];

    public function __construct($url)
    {
        $this->dom = new Dom();
        $this->url = $url;
    }

    public function find()
    {
        $this->dom->loadFromUrl($this->url);

        $feeds = new Collection($this->dom->find('link[rel=alternate]'));

        $feedUrls = $feeds->filter(function ($feed) {
            return in_array($feed->getAttribute('type'), $this->feedTypes);
        })->map(function ($feed) {
            return $feed->getAttribute('href');
        })->toArray();

        return $feedUrls;
    }

    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function setDom($dom)
    {
        $this->dom = $dom;
    }

    public function getDom()
    {
        return $this->dom;
    }
}

Allow method chaining after setUrl()

Allow method chaining after setUrl()


<?php

namespace BoomCMS\Installer;

use BoomCMS\Core\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Request $request, Auth\Auth $auth)
    {
        $installer = new Installer();

        if ( ! $installer->isInstalled()) {
            $this->dispatch('Illuminate\Database\Console\Migrations\InstallCommand');
            $this->dispatch('Illuminate\Database\Console\Migrations\MigrateCommand');

            $person = $this->dispatch('BoomCMS\Core\Commands\CreatePerson', [$request->input('user_name'), $request->input('user_email'), []]);
            $auth->login($person);

            $page = $this->dispatch('BoomCMS\Core\Commands\CreatePage', $this->app['boomcms.page.provider'], $auth);
            $this->dispatch('BoomCMS\Core\Commands\CreatePagePrimaryUri', $this->app['boomcms.page.provider'], $page, '', '');
            $installer->markInstalled();
        }
    }

    /**
     *
     * @return void
     */
    public function register()
    {
        $installer = new Installer();

        if (php_sapi_name() !== 'cli' && ! $installer->isInstalled()) {
            require __DIR__ . '/../../install.php';
        }

        $this->publishes([__DIR__.'/../../../public' => public_path('vendor/boomcms/boom-installer')], 'boomcms');
    }
}

<?php

namespace BoomCMS\Installer;

use BoomCMS\Core\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Request $request, Auth\Auth $auth)
    {
        $installer = new Installer();

        if ( ! $installer->isInstalled()) {
            $this->dispatch('Illuminate\Database\Console\Migrations\InstallCommand');
            $this->dispatch('Illuminate\Database\Console\Migrations\MigrateCommand');

            $installer->saveSiteDetails($request->input('site_name'), $request->input('site_email'));

            $person = $this->dispatch('BoomCMS\Core\Commands\CreatePerson', [$request->input('user_name'), $request->input('user_email'), []]);
            $auth->login($person);

            $page = $this->dispatch('BoomCMS\Core\Commands\CreatePage', $this->app['boomcms.page.provider'], $auth);
            $this->dispatch('BoomCMS\Core\Commands\CreatePagePrimaryUri', $this->app['boomcms.page.provider'], $page, '', '');
            $installer->markInstalled();
        }
    }

    /**
     *
     * @return void
     */
    public function register()
    {
        $installer = new Installer();

        if (php_sapi_name() !== 'cli' && ! $installer->isInstalled()) {
            require __DIR__ . '/../../install.php';
        }

        $this->publishes([__DIR__.'/../../../public' => public_path('vendor/boomcms/boom-installer')], 'boomcms');
    }
}

Save site details during install

Save site details during install


<?php

namespace CultuurNet\UDB3\Event\Events;

interface EventCdbXMLInterface
{
    /**
     * @return int
     */
    public function getEventId();

    /**
     * @return string
     */
    public function getCdbXml();

    /**
     * @return string
     */
    public function getCdbXmlNamespaceUri();
}

<?php

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Cdb\CdbXmlContainerInterface;

interface EventCdbXMLInterface extends CdbXmlContainerInterface
{
    /**
     * @return int
     */
    public function getEventId();

    /**
     * @return string
     */
    public function getCdbXml();

    /**
     * @return string
     */
    public function getCdbXmlNamespaceUri();
}

Extend cdb xml container interface

III-179: Extend cdb xml container interface


<?php

namespace Keyteq\Keymedia\API;

use Keyteq\Keymedia\API\Configuration;
use Keyteq\Keymedia\Util\RequestBuilder;

class RestConnector
{
    protected $config;
    protected $requestBuilder;

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

    public function getResource($resourceName, $resourceId, array $parameters = array())
    {
        $path = "{$resourceName}/{$resourceId}.json";
        $url = $this->buildUrl($path, $parameters);
        $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters);

        return $request->perform();
    }

    public function getCollection($resourceName, array $parameters = array())
    {
        $path = "{$resourceName}.json";
        $url = $this->buildUrl($path, $parameters);
        $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters);

        return $request->perform();
    }

    protected function buildUrl($path = '')
    {
        $rootUrl = $this->config->getApiUrl();
        $url = "{$rootUrl}/{$path}";

        return $url;
    }
}

<?php

namespace Keyteq\Keymedia\API;

use Keyteq\Keymedia\API\Configuration;
use Keyteq\Keymedia\Util\RequestBuilder;

class RestConnector
{
    protected $config;
    protected $requestBuilder;

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

    public function getResource($resourceName, $resourceId, array $parameters = array())
    {
        $path = "{$resourceName}/{$resourceId}.json";
        $url = $this->buildUrl($path, $parameters);
        $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters);

        return $request->perform();
    }

    public function getCollection($resourceName, array $parameters = array())
    {
        $path = "{$resourceName}.json";
        $url = $this->buildUrl($path);
        $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters);

        return $request->perform();
    }

    protected function buildUrl($path = '')
    {
        $rootUrl = $this->config->getApiUrl();
        $url = "{$rootUrl}/{$path}";

        return $url;
    }
}

Remove no longer used argument from buildUrl() call


<?php

namespace Canvas\Http\Controllers;

use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store()
    {
        $payload = request()->file();

        // We only expect single file uploads at this time
        $file = reset($payload);

        if ($file instanceof UploadedFile) {
            $path = $file->storePublicly($this->getBaseStoragePath(), [
                'disk' => config('canvas.storage_disk'),
            ]);

            return Storage::disk(config('canvas.storage_disk'))->url($path);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy()
    {
        $file = pathinfo(request()->getContent());
        $storagePath = $this->getBaseStoragePath();
        $path = "{$storagePath}/{$file['basename']}";

        $fileDeleted = Storage::disk(config('canvas.storage_disk'))->delete($path);

        if ($fileDeleted) {
            return response()->json([], 204);
        }
    }

    /**
     * Return the storage path url.
     *
     * @return string
     */
    private function getBaseStoragePath(): string
    {
        return sprintf('%s/%s', config('canvas.storage_path'), 'images');
    }
}

<?php

namespace Canvas\Http\Controllers;

use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store()
    {
        $payload = request()->file();

        // We only expect single file uploads at this time
        $file = reset($payload);

        if ($file instanceof UploadedFile) {
            $path = $file->store($this->getBaseStoragePath(), [
                'disk' => config('canvas.storage_disk'),
            ]);

            return Storage::disk(config('canvas.storage_disk'))->url($path);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy()
    {
        $file = pathinfo(request()->getContent());
        $storagePath = $this->getBaseStoragePath();
        $path = "{$storagePath}/{$file['basename']}";

        $fileDeleted = Storage::disk(config('canvas.storage_disk'))->delete($path);

        if ($fileDeleted) {
            return response()->json([], 204);
        }
    }

    /**
     * Return the storage path url.
     *
     * @return string
     */
    private function getBaseStoragePath(): string
    {
        return sprintf('%s/%s', config('canvas.storage_path'), 'images');
    }
}

Use method store instead of storePublicly


<?php

namespace Torann\Moderate;

trait HasModerateTrait
{
    /**
     * Register eloquent event handlers.
     *
     * @return void
     */
    public static function bootHasModerateTrait()
    {
        static::creating(function ($model) {
            $moderate = false;

            foreach ($model->moderate as $id => $moderation) {
                $rules = explode('|', $moderation);

                foreach ($rules as $rule) {
                    $action = explode(':', $rule);
                    $options = isset($action[1]) ? $action[1] : null;

                    if (app(Moderator::class)->$action[0]($model->$id, $options)) {
                        $moderate = true;
                        continue;
                    }
                }

                // No reason to keep going
                if ($moderate === true) {
                    continue;
                }
            }

            $model->moderated = $moderate;
        });

        static::created(function ($model) {
            if ($model->isModerated()) {
                event(new Events\Moderated($model));
            }
        });
    }

    /**
     * Check if the resource is moderated.
     *
     * @return bool
     */
    public function isModerated()
    {
        return $this->moderated == 1;
    }
}

<?php

namespace Torann\Moderate;

trait HasModerateTrait
{
    /**
     * Register eloquent event handlers.
     *
     * @return void
     */
    public static function bootHasModerateTrait()
    {
        static::creating(function ($model) {
            $moderate = false;

            foreach ($model->moderate as $id => $moderation) {
                $rules = explode('|', $moderation);

                foreach ($rules as $rule) {
                    $action = explode(':', $rule);
                    $options = isset($action[1]) ? $action[1] : null;

                    if (app(Moderator::class)->$action[0]($model->$id, $options)) {
                        $moderate = true;
                        continue;
                    }
                }

                // No reason to keep going
                if ($moderate === true) {
                    continue;
                }
            }

            $model->moderated = $moderate;
        });

        static::created(function ($model) {
            if ($model->isModerated()) {
                event(new Events\Moderated($model));
            }
        });
    }

    /**
     * Get moderated attribute as a proper boolean.
     *
     * @return bool
     */
    public function getModeratedAttribute()
    {
        return (bool) $this->moderated;
    }

    /**
     * Check if the resource is moderated.
     *
     * @return bool
     */
    public function isModerated()
    {
        return $this->moderated == true;
    }
}

Add mutator for the moderated attribute

Add mutator for the moderated attribute


<?php

namespace Del\Common\ZF1\Controller;

use Del\Common\ContainerService;
use Exception;
use Zend_Auth;
use Zend_Controller_Action;
use Zend_Layout;

class AbstractController extends Zend_Controller_Action
{
    protected $container;

    public function init()
    {
        $this->container = ContainerService::getInstance()->getContainer();
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getContainerObject($key)
    {
        return $this->container[$key];
    }

    /**
     *
     */
    public function sendJSONResponse(array $array)
    {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->getResponse()->setHeader('Content-Type', 'application/json');
        $this->_helper->json($array);
    }

    public function getIdentity()
    {
        if(Zend_Auth::getInstance()->hasIdentity()) {
            return Zend_Auth::getInstance()->getIdentity();
        }
        throw new Exception('No Identity.');
    }
}

<?php

namespace Del\Common\ZF1\Controller;

use Del\Common\ContainerService;
use Exception;
use Zend_Auth;
use Zend_Controller_Action;
use Zend_Layout;

class AbstractController extends Zend_Controller_Action
{
    protected $container;

    public function init()
    {
        $this->container = ContainerService::getInstance()->getContainer();
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getContainerObject($key)
    {
        return $this->container[$key];
    }

    /**
     *
     */
    public function sendJSONResponse(array $array)
    {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->getResponse()->setHeader('Content-Type', 'application/json');
        $this->_helper->json($array);
    }

    public function getIdentity()
    {
        if(Zend_Auth::getInstance()->hasIdentity()) {
            return Zend_Auth::getInstance()->getIdentity();
        }
        throw new Exception('No Identity.');
    }

    /**
     * @return Zend_Controller_Request_Http
     */
    public function getRequest()
    {
        return parent::getRequest();
    }
}

Add getRequest that PHPStorm will complete (ZF1 bad design)


<?php

class DownloadableOrderItemExtension extends DataExtension
{

    public function getDownloadLink()
    {
        $order = Order::get()->byID($this->owner->ParentID);

        if ($match = $this->owner->match()) {
            return $match->getDownloadLink().
                '?o='.$order->ID.
                '&k='.$order->AccessKey;
        }

        return false;
    }
}

<?php

class DownloadableOrderItemExtension extends DataExtension
{

    public function getDownloadLink()
    {
        $order = Order::get()->byID($this->owner->ParentID);
        $match = $this->owner->match();

        if ($match && method_exists($match, "getDownloadLink")) {
            return $match->getDownloadLink().
                '?o='.$order->ID.
                '&k='.$order->AccessKey;
        }

        return false;
    }
}

Add check to ensure item has a download link


<?php

use Scholarship\Forms\NominationForm;

class NominationController extends \BaseController {

  /**
  * @var nominationForm
  */
  protected $nominationForm;

  function __construct(NominationForm $nominationForm)
  {
    $this->nominationForm = $nominationForm;
  }

  public function store()
  {
    $input = Input::all();
    $this->nominationForm->validate($input);

    $nom = new Nomination;
    $nom->fill($input)->save();

    $this->sendNomEmail($nom);

    return Redirect::route('home')->with('flash_message', ['text' => 'Thanks for taking the time to nominate someone for the Foot Locker Scholar Athletes program! If you know other outstanding individuals for the program, we’d love to hear about them.', 'class' => '-info']);
  }

  public function sendNomEmail($nom)
  {
    $email = new Email;
    $data = array(
      'nom_name' => $nom->nom_name,
      'rec_name' => $nom->rec_name,
      'application' => link_to_route('home', 'Application'),
    );
    $email->sendEmail('nomination', 'applicant', $nom->nom_email, $data);

  }
}

<?php

use Scholarship\Forms\NominationForm;

class NominationController extends \BaseController {

  /**
  * @var nominationForm
  */
  protected $nominationForm;

  function __construct(NominationForm $nominationForm)
  {
    $this->nominationForm = $nominationForm;
  }

  public function store()
  {
    $input = Input::all();
    $this->nominationForm->validate($input);

    $nom = new Nomination;
    $nom->fill($input)->save();

    $this->sendNomEmail($nom);

    return Redirect::route('home')->with('flash_message', ['text' => 'Thanks for taking the time to nominate someone! If you know other outstanding individuals for the program, we’d love to hear about them.', 'class' => '-info']);
  }

  public function sendNomEmail($nom)
  {
    $email = new Email;
    $data = array(
      'nom_name' => $nom->nom_name,
      'rec_name' => $nom->rec_name,
      'application' => link_to_route('home', 'Application'),
    );
    $email->sendEmail('nomination', 'applicant', $nom->nom_email, $data);

  }
}

Update to generalize the flash message text.


<?php

namespace Interop\Http\Factory;

use Psr\Http\Message\StreamInterface;

interface StreamFactoryInterface
{
    /**
     * Create a new stream from a resource or a string.
     *
     * If the argument is a resource, it MUST be readable and SHOULD be seekable. It MAY be writable.
     * If the argument is a string, a temporary resource will be created that is writable and seekable.
     *
     * If the arugment is a string it will be interpided as the content of the stream. File names or
     * file paths are not supported.
     *
     * @param string|resource $resource
     *
     * @return StreamInterface
     */
    public function createStream($resource);
}

<?php

namespace Interop\Http\Factory;

use Psr\Http\Message\StreamInterface;

interface StreamFactoryInterface
{
    /**
     * Create a new stream from a string.
     *
     * The stream SHOULD be created with a temporary resource.
     *
     * @param string $content
     *
     * @return StreamInterface
     */
    public function createStream($content = '');

    /**
     * Create a stream from an existing file.
     *
     * The file MUST be opened using the given mode, which may be any mode
     * supported by the `fopen` function.
     *
     * @param string $file
     * @param string $mode
     *
     * @return StreamInterface
     */
    public function createStreamFromFile($file, $mode = 'r');

    /**
     * Create a new stream from an existing resource.
     *
     * The stream MUST be readable and may be writable.
     *
     * @param resource $resource
     *
     * @return StreamInterface
     */
    public function createStreamFromResource($resource);
}

Add separate methods for creating streams

Being able to create streams from 3 distinct sources aligns with
existing middleware that may need to:

- Create streams from strings
- Create streams from files
- Create streams from resources

In the case of strings and files, the final result will be a resource
that will be attached to the stream.

Refs #2
Refs #4
Refs #14
Refs #16


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         CakePHP(tm) v 3.0.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
namespace Cake\Network\Http\Adapter;

/**
 * Implements sending Cake\Network\Http\Request
 * via php's stream API.
 *
 */
class Stream {
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         CakePHP(tm) v 3.0.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
namespace Cake\Network\Http\Adapter;

/**
 * Implements sending Cake\Network\Http\Request
 * via php's stream API.
 *
 */
class Stream {

	public function __construct() {
	}

	public function send($request, $options) {
	}

}

Add incomplete send() method to Adapter.


<?php

if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
    print "This script must be run from the command line\n";
    exit();
}

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
define('STATUSNET', true);

require_once INSTALLDIR . '/lib/common.php';

class UUIDTest extends PHPUnit_Framework_TestCase
{
    public function testGenerate()
    {
        $result = UUID::gen();
        $this->assertRegExp('/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/',
                            $result);
        // Check version number
        $this->assertEquals(0x4000, hexdec(substr($result, 14, 4)) & 0xF000);
        $this->assertEquals(0x8000, hexdec(substr($result, 19, 4)) & 0xC000);
    }
}

<?php

if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
    print "This script must be run from the command line\n";
    exit();
}

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
define('STATUSNET', true);

require_once INSTALLDIR . '/lib/common.php';

class UUIDTest extends PHPUnit_Framework_TestCase
{
    public function testGenerate()
    {
        $result = UUID::gen();
        $this->assertRegExp('/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/',
                            $result);
        // Check version number
        $this->assertEquals(0x4000, hexdec(substr($result, 14, 4)) & 0xF000);
        $this->assertEquals(0x8000, hexdec(substr($result, 19, 4)) & 0xC000);
    }

    public function testUnique()
    {
        $reps = 100;
        $ids = array();

        for ($i = 0; $i < $reps; $i++) {
            $ids[] = UUID::gen();
        }

        $this->assertEquals(count($ids), count(array_unique($ids)), "UUIDs must be unique");
    }
}

Make sure the UUIDs are unique too :)

Make sure the UUIDs are unique too :)


<?php
    global $post;
    $items = get_field('index', $module->ID);
?>

    <?php foreach ($items as $item) : $post = $item['page']; setup_postdata($post); ?>

        <a href="<?php the_permalink(); ?>" class="box box-index" data-equal-item>
            <?php if ($item['image_display'] == 'featured' && $thumbnail = get_thumbnail_source()) : ?>
                <img class="box-image" src="<?php echo $thumbnail; ?>">
            <?php elseif ($item['image_display'] == 'custom' && !empty($item['custom_image'])) : ?>
                <img class="box-image" src="<?php echo $item['custom_image']['url']; ?>" alt="<?php echo (!empty($item['custom_image']['alt'])) ? $item['custom_image']['alt'] : $item['custom_image']['description']; ?>">
            <?php endif; ?>

<?php the_title(); ?>

                <?php the_excerpt(); ?>

    <?php endforeach; ?>

<?php wp_reset_postdata(); ?>

Reset postdata in index module

Reset postdata in index module