<?php
/**
 * FrontMatterParser.php
 *
 * Created By: jonathan
 * Date: 23/09/2017
 * Time: 00:34
 */

namespace Stati\Parser;

use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Yaml\Yaml;

class FrontMatterParser
{
    public static function parse($text)
    {
        $split = preg_split("/[\n]*[-]{3}/", $text, 2, PREG_SPLIT_NO_EMPTY);

        if (count($split) > 1) {
            try {
                // Using symfony's YAML parser
                // we can use trim here because we only remove white space
                // at the beginning (first should not have any) and at the end (insignificant)
                return Yaml::parse(trim($split[0]));
            } catch (InvalidArgumentException $e) {
                // This is not YAML
                return [];
            }
        }
        return [];
    }
}

<?php
/**
 * FrontMatterParser.php
 *
 * Created By: jonathan
 * Date: 23/09/2017
 * Time: 00:34
 */

namespace Stati\Parser;

use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;

class FrontMatterParser
{
    public static function parse($text)
    {
        $split = preg_split("/[\n]*[-]{3}/", $text, 2, PREG_SPLIT_NO_EMPTY);

        if (count($split) > 1) {
            try {
                // Using symfony's YAML parser
                // we can use trim here because we only remove white space
                // at the beginning (first should not have any) and at the end (insignificant)
                $val = trim($split[0]);
                if (strlen($val) === 0) {
                    return [];
                }
                return Yaml::parse($val);
            } catch (InvalidArgumentException $e) {
                // This is not YAML
                return [];
            } catch (ParseException $err) {
                return [];
            }
        }
        return [];
    }
}

Return empty array on ParseException

Return empty array on ParseException


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

class UninstallSearch extends Command
{

    protected $signature = 'search:uninstall {index? : The name of the index to delete}';

    protected $description = 'Tear down the Search Service index';

    /**
     * The name of the index to delete.
     *
     * @var string
     */
    protected $index;

    public function __construct()
    {

        parent::__construct();
        $this->index = env('ELASTICSEARCH_INDEX', 'data_aggregator_test');

    }

    public function handle()
    {

        if ($this->argument('index'))
        {

            $this->index = $this->argument('index');

        }

        $params = [
            'index' => $this->index,
        ];

        if (Elasticsearch::indices()->exists($params))
        {

            $return = Elasticsearch::indices()->delete($params);

        }

    }

}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

use App\Console\Helpers\Indexer;

class UninstallSearch extends Command
{

    use Indexer;

    protected $signature = 'search:uninstall {prefix? : The prefixes of the indexes to delete} {--y|yes : Answer "yes" to all prompts confirming to delete index}';

    protected $description = 'Tear down the Search Service indexes';

    /**
     * The prefix of the indexes to delete.
     *
     * @var string
     */
    protected $prefix;

    public function __construct()
    {

        parent::__construct();
        $this->prefix = env('ELASTICSEARCH_INDEX_PREFIX', 'test_');

    }

    public function handle()
    {

        if ($this->argument('prefix'))
        {

            $this->prefix = $this->argument('prefix');

        }

        if (!$this->option('yes') && !$this->confirm("This will delete all indexes that begin with the prefix " .$this->prefix .". Do you wish to continue?"))
        {

            return false;

        }

        foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model)
        {

            $endpoint = endpointFor($model);
            $index = $this->prefix .$endpoint;

            $params = [
                'index' => $index,
            ];

            if (Elasticsearch::indices()->exists($params))
            {

                $return = Elasticsearch::indices()->delete($params);

                $this->info($this->done($return));

            }
            else
            {

                $this->info("Index " .$index . " does not exist.");

            }

        }

    }

}

Update search:uninstall to work with multiple indexes


<% _.each(data, function(row) { %>
	<%= _.escape(row.metadata.title) %>
	<%= row.comments %>
<% }); %>
<% if (_.isEmpty(data)) { %>
	Es entsprechen leider keine Daten der Suchanfrage.
<% } %>

<% _.each(data, function(row) { %>
	<a class="list-group-item" onclick="commentsToGeodataController(<%= row.id %>)"><%= _.escape(row.metadata.title) %>
	<%= row.comments %>
<% }); %>
<% if (_.isEmpty(data)) { %>
	Es entsprechen leider keine Daten der Suchanfrage.
<% } %>

Work template for showing geodata over

Work template for showing geodata over


<?php

namespace ALttP\World;

class Retro extends Open
{
    /**
     * Create a new world and initialize all of the Regions within it.
     * In Retro we force certain config values that cannot be overriden.
     *
     * @param int    $id      Id of this world
     * @param array  $config  config for this world
     *
     * @return void
     */
    public function __construct(int $id = 0, array $config = [])
    {
        parent::__construct($id, array_merge($config, [
            'rom.rupeeBow' => true,
            'rom.genericKeys' => true,
            'region.takeAnys' => true,
            'region.wildKeys' => true,
        ]));
    }
}

<?php

namespace ALttP\World;

class Retro extends Open
{
    /**
     * Create a new world and initialize all of the Regions within it.
     * In Retro we force certain config values that cannot be overriden.
     *
     * @param int    $id      Id of this world
     * @param array  $config  config for this world
     *
     * @return void
     */
    public function __construct(int $id = 0, array $config = [])
    {
        parent::__construct($id, array_merge($config, [
            'rom.rupeeBow' => true,
            'rom.genericKeys' => true,
            'region.takeAnys' => true,
            'region.wildKeys' => true,
        ]));

        if ($this->config('difficulty') !== 'custom') {
            switch ($this->config('item.pool')) {
            case 'hard':
            case 'expert':
            case 'crowd_control':
                $this->config['item.count.KeyD1'] = 0;
                $this->config['item.count.KeyA2'] = 0;
                $this->config['item.count.KeyD7'] = 0;
                $this->config['item.count.KeyD2'] = 0;

                $this->config['item.count.TwentyRupees2'] = 15 + $this->config('item.count.TwentyRupees2', 0);
                break;
            case 'normal':
                $this->config['item.count.KeyD1'] = 0;
                $this->config['item.count.KeyA2'] = 0;
                $this->config['item.count.TwentyRupees2'] = 10 + $this->config('item.count.TwentyRupees2', 0);
            }
        }
    }
}

Remove 10-15 keys from retro (replace with green 20 rupees).


<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'full_name', 'provider', 'provider_id',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'full_name', 'email', 'provider', 'provider_id',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Allow user email address to be mass assigned


<?php

namespace Despark\Cms\Admin\Observers;

use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;

/**
 * Class ImageObserver.
 */
class ImageObserver
{
    /**
     * @param Model $model
     */
    public function saved(Model $model)
    {
        $model->saveImages();
    }

    /**
     * @param Model $model
     */
    public function deleted(Model $model)
    {
        $imageInstance = app(ImageContract::class);
        \DB::table($imageInstance->getTable())->where('resource_id', '=', $model->getKey())
           ->delete();

        \File::deleteDirectory($model->getCurrentUploadDir());
    }
}

<?php

namespace Despark\Cms\Admin\Observers;

use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;

/**
 * Class ImageObserver.
 */
class ImageObserver
{
    /**
     * @param Model $model
     */
    public function saved(Model $model)
    {
        $model->saveImages();
    }

    /**
     * @param Model $model
     */
    public function deleted(Model $model)
    {
        $imageInstance = app(ImageContract::class);

        \DB::table($imageInstance->getTable())
            ->where('resource_id', '=', $model->getKey())
            ->where('resource_model', '=', $model->getMorphClass())
            ->delete();

        \File::deleteDirectory($model->getCurrentUploadDir());
    }
}

Fix critical Image delete observer!!!

Fix critical Image delete observer!!!

Update ImageObserver.php


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Command;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class AboutCommand extends BaseCommand
{
    protected function configure()
    {
        $this
            ->setName('about')
            ->setDescription('Shows the short information about Composer.')
            ->setHelp(
                <<<EOT
<info>php composer.phar about</info>
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->getIO()->write(
            <<<EOT
<info>Composer - Dependency Manager for PHP</info>
<comment>Composer is a dependency manager tracking local dependencies of your projects and libraries.
See https://getcomposer.org/ for more information.</comment>
EOT
        );

        return 0;
    }
}

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Command;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class AboutCommand extends BaseCommand
{
    protected function configure()
    {
        $this
            ->setName('about')
            ->setDescription('Shows a short information about Composer.')
            ->setHelp(
                <<<EOT
<info>php composer.phar about</info>
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $composerVersion = Composer::getVersion();

        $this->getIO()->write(
            <<<EOT
<info>Composer - Dependency Manager for PHP - version $composerVersion</info>
<comment>Composer is a dependency manager tracking local dependencies of your projects and libraries.
See https://getcomposer.org/ for more information.</comment>
EOT
        );

        return 0;
    }
}

Add Composer version in about command

Add Composer version in about command


<?php

function redirect($url = '/') {
    header('HTTP/1.1 302 Found');
    header("Location: $url");
}
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect();
    exit;
}

$quizJson = json_decode(file_get_contents('php://input'), true);
$grade = $quizJson['grade'];
$subject = $quizJson['subject'];
$chapter = $quizJson['chapter'];
$fileName = "json/$grade/$subject/$chapter.json";

if(file_exists($fileName)) {
    $existingJson = json_decode(file_get_contents($fileName));
} else {
    $existingJson = [];
}
$quizJson['quiz']['type'] = 'quiz';
array_push($existingJson, $quizJson['quiz']);
file_put_contents($fileName, json_encode($existingJson));
header('HTTP/1.1 201 Created');
header('Content-Type: application/json');
echo json_encode($quizJson);
/*
 * {grade:, subject: chapter: quiz: {}}
 */
?>

<?php

function redirect($url = '/') {
    header('HTTP/1.1 302 Found');
    header("Location: $url");
}
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect();
    exit;
}

$quizJson = json_decode(file_get_contents('php://input'), true);
$grade = $quizJson['grade'];
$subject = $quizJson['subject'];
$chapter = $quizJson['chapter'];
$fileName = "json/$grade/$subject/$chapter.json";

if(file_exists($fileName)) {
    $existingJson = json_decode(file_get_contents($fileName));
} else {
    $existingJson = array();
}
$quizJson['quiz']['type'] = 'quiz';
array_push($existingJson, $quizJson['quiz']);
file_put_contents($fileName, json_encode($existingJson));
header('HTTP/1.1 201 Created');
header('Content-Type: application/json');
echo json_encode($quizJson);
/*
 * {grade:, subject: chapter: quiz: {}}
 */
?>

Use php5.3 syntax for array

Use php5.3 syntax for array


<?php

namespace PHPSpec2\Matcher;

abstract class BasicMatcher implements MatcherInterface
{
    final public function positiveMatch($name, $subject, array $arguments)
    {
        if (!$this->matches($subject, $arguments)) {
            throw $this->getFailureException($name, $subject, $arguments);
        }

        return $subject;
    }

    final public function negativeMatch($name, $subject, array $arguments)
    {
        if ($this->matches($subject, $arguments)) {
            throw $this->getNegativeFailureException($name, $subject, $arguments);
        }

        return $subject;
    }

    abstract protected function matches($subject, array $arguments);
    abstract protected function getFailureException($name, $subject, array $arguments);
    abstract protected function getNegativeFailureException($name, $subject, array $arguments);
}

<?php

namespace PHPSpec2\Matcher;

abstract class BasicMatcher implements MatcherInterface
{
    final public function positiveMatch($name, $subject, array $arguments)
    {
        if (false === $this->matches($subject, $arguments)) {
            throw $this->getFailureException($name, $subject, $arguments);
        }

        return $subject;
    }

    final public function negativeMatch($name, $subject, array $arguments)
    {
        if (true === $this->matches($subject, $arguments)) {
            throw $this->getNegativeFailureException($name, $subject, $arguments);
        }

        return $subject;
    }

    abstract protected function matches($subject, array $arguments);
    abstract protected function getFailureException($name, $subject, array $arguments);
    abstract protected function getNegativeFailureException($name, $subject, array $arguments);
}

Check match with identity operator against a boolean


<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\ClientSide;

abstract class Manifest {

abstract public function calculateFingerprint($details);

abstract public function checkValid();

abstract public function expand();

}#

<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\ClientSide;

abstract class Manifest {

/**
 * @return string MD5 hash representation
 */
abstract public function calculateFingerprint($details);

/**
 * @return bool True if valid, false if invalid
 */
abstract public function checkValid();

/**
 * @return void
 */
abstract public function expand();

}#

Add annotations to abstract methods

Add annotations to abstract methods


<?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.
|
*/

Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);

Route::resource('projects', 'ProjectsController');
Route::resource('tickets', 'TicketsController');
Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
Route::resource('statuses', 'StatusesController');

<?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.
|
*/

Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);

Route::group(['before' => 'auth'], function()
{
	Route::resource('projects', 'ProjectsController');
	Route::resource('tickets', 'TicketsController');
	Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
	Route::resource('statuses', 'StatusesController');
});

Add route group that requires auth

Add route group that requires auth


<?php

namespace Eole\Sandstone\Tests\Unit\Websocket;

use Eole\Sandstone\Serializer\ServiceProvider as SerializerServiceProvider;
use Eole\Sandstone\Websocket\Routing\TopicRouter;
use Eole\Sandstone\Websocket\Application as WebsocketApplication;
use Eole\Sandstone\Application;

class ApplicationTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadTopicThrowExceptionWhenImplementingTheWrongEventDispatcherInterface()
    {
        $app = new Application();
        $websocketAppClass = new \ReflectionClass(WebsocketApplication::class);
        $method = $websocketAppClass->getMethod('loadTopic');
        $method->setAccessible(true);
        $websocketApp = $websocketAppClass->newInstance($app);

        $app->register(new SerializerServiceProvider());

        $app['sandstone.websocket.router'] = function () {
            $wrongTopic = new WrongTopic('my-topic');
            $topicRouterMock = $this->createMock(TopicRouter::class);

            $topicRouterMock
                ->method('loadTopic')
                ->willReturn($wrongTopic)
            ;

            return $topicRouterMock;
        };

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('WrongTopic seems to implements the wrong EventSubscriberInterface');

        $method->invokeArgs($websocketApp, ['my-topic']);
    }
}

<?php

namespace Eole\Sandstone\Tests\Unit\Websocket;

use Eole\Sandstone\Serializer\ServiceProvider as SerializerServiceProvider;
use Eole\Sandstone\Websocket\Routing\TopicRouter;
use Eole\Sandstone\Websocket\Application as WebsocketApplication;
use Eole\Sandstone\Application;

class ApplicationTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadTopicThrowExceptionWhenImplementingTheWrongEventDispatcherInterface()
    {
        $app = new Application();
        $websocketAppClass = new \ReflectionClass(WebsocketApplication::class);
        $method = $websocketAppClass->getMethod('loadTopic');
        $method->setAccessible(true);
        $websocketApp = $websocketAppClass->newInstance($app);

        $app->register(new SerializerServiceProvider());

        $app['sandstone.websocket.router'] = function () {
            $wrongTopic = new WrongTopic('my-topic');
            $topicRouterMock = $this->getMockBuilder(TopicRouter::class)->disableOriginalConstructor()->getMock();

            $topicRouterMock
                ->method('loadTopic')
                ->willReturn($wrongTopic)
            ;

            return $topicRouterMock;
        };

        $this->setExpectedExceptionRegExp(
            \LogicException::class,
            '/WrongTopic seems to implements the wrong EventSubscriberInterface/'
        );

        $method->invokeArgs($websocketApp, ['my-topic']);
    }
}

Fix incompatibility with php 5.5 in tests


<?php

/**
 * Base Integration Test
 *
 * The core test-class for all integration tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class BaseIntegrationTest extends BaseUnitTest
{
    protected function _before()
    {
        parent::_before();
    }

    protected function _after()
    {
        parent::_after();
    }

    /********************************************************
     * Helpers
     *******************************************************/
}

<?php

/**
 * Base Integration Test
 *
 * The core test-class for all integration tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class BaseIntegrationTest extends BaseUnitTest
{
    protected function _before()
    {
        parent::_before();
    }

    protected function _after()
    {
        parent::_after();
    }

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

    public function outputPath()
    {
        return parent::outputPath() . 'commands/';
    }
}

Add output path to base integration test

Ensuring that all output goes into a commands directory, because we
are mainly only going to test the application's commands


<?php

namespace SimpleSAML\Test\Auth;

use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;

/**
 * Tests for SimpleSAML_Auth_Source
 */
class SourceTest extends ClearStateTestCase
{
    public function testParseAuthSource()
    {
        $class = new \ReflectionClass('SimpleSAML_Auth_Source');
        $method = $class->getMethod('parseAuthSource');
        $method->setAccessible(true);

        // test direct instantiation of the auth source object
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);

        // test instantiation via an auth source factory
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
    }
}

class TestAuthSource extends \SimpleSAML_Auth_Source
{
    public function authenticate(&$state)
    {
    }
}

class TestAuthSourceFactory implements SourceFactory
{
    public function create(array $info, array $config)
    {
        return new TestAuthSource($info, $config);
    }
}

<?php

namespace SimpleSAML\Test\Auth;

use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;

/**
 * Tests for SimpleSAML_Auth_Source
 */
class SourceTest extends ClearStateTestCase
{
    public function testParseAuthSource()
    {
        $class = new \ReflectionClass('SimpleSAML_Auth_Source');
        $method = $class->getMethod('parseAuthSource');
        $method->setAccessible(true);

        // test direct instantiation of the auth source object
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);

        // test instantiation via an auth source factory
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
    }
}

class TestAuthSource extends \SimpleSAML_Auth_Source
{
    public function authenticate(array &$state)
    {
    }
}

class TestAuthSourceFactory implements SourceFactory
{
    public function create(array $info, array $config)
    {
        return new TestAuthSource($info, $config);
    }
}

Make signature of test auth source match that of class it extends


<?php

namespace fennecweb\ajax\details;

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

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('details/Project');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
                      'table_1'
        );
        $this->assertArraySubset($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\details;

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

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('details/Project');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
                      'table_1'
        );
        $this->assertArraySubset($expected, $results);
    }
}

Add correct name of constant variables

Add correct name of constant variables


<?php
/**
 * Bareos Reporter
 * Application for managing Bareos Backup Email Reports
 *
 * Dashboard Controller
 *
 * @license The MIT License (MIT) See: LICENSE file
 * @copyright Copyright (c) 2016 Matt Clinton
 * @author Matt Clinton <matt@laralabs.uk>
 * @website http://www.magelabs.uk/
 */

namespace App\Http\Controllers;

use App\Catalogs;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class DashboardController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('dashboard.index');
    }

    /**
     * Change the active director, set active_director
     * session variable if input value not empty.
     *
     * @return \Illuminate\Http\Response
     */
    public function changeDirector()
    {
        $director_id = Input::get('director-select');

        if(!empty($director_id))
        {
            Session::set('active_director', $director_id);

            return redirect('directors')->with('success', 'Director changed successfully');
        }
        else
        {
            return redirect('directors')->with('failed', 'Unable to change director');
        }
    }
}

<?php
/**
 * Bareos Reporter
 * Application for managing Bareos Backup Email Reports
 *
 * Dashboard Controller
 *
 * @license The MIT License (MIT) See: LICENSE file
 * @copyright Copyright (c) 2016 Matt Clinton
 * @author Matt Clinton <matt@laralabs.uk>
 * @website http://www.magelabs.uk/
 */

namespace App\Http\Controllers;

use App\Catalogs;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class DashboardController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('dashboard.index');
    }

    /**
     * Change the active director, set active_director
     * session variable if input value not empty.
     *
     * @return \Illuminate\Http\Response
     */
    public function changeDirector()
    {
        $director_id = Input::get('director-select');

        if(!empty($director_id))
        {
            $connectionName = Catalogs::getCatalogName($director_id);

            Session::set('active_connection', $connectionName);
            Session::set('active_director', $director_id);

            return redirect('directors')->with('success', 'Director changed successfully');
        }
        else
        {
            return redirect('directors')->with('failed', 'Unable to change director');
        }
    }
}

Save connection name in session too

Save connection name in session too


<?php

namespace Howtomakeaturn\Db2d;

use Ifsnop\Mysqldump\Mysqldump;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxFile;

class Db2d
{
    private $dumper;

    private $uploader;

    public function configureDatabase($db, $username, $password)
    {
        $this->dumper = new Mysqldump("mysql:host=localhost;dbname=$db", $username, $password);
    }

    public function configureDropbox($key, $secret, $token)
    {
        $app = new DropboxApp($key, $secret, $token);

        $this->uploader = new Dropbox($app);
    }

    public function backup()
    {
        $name = 'backup-' . date('Ymd-H-i-s') . '.sql';

        $this->dumper->start($name);

        $dropboxFile = new DropboxFile($name);

        $file = $this->uploader->upload($dropboxFile, "/$name", ['autorename' => true]);

        unlink($name);
    }
}

<?php

namespace Howtomakeaturn\Db2d;

use Ifsnop\Mysqldump\Mysqldump;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxFile;

class Db2d
{
    private $dumper;

    private $uploader;

    public function configureDatabase($db, $username, $password)
    {
        $this->dumper = new Mysqldump("mysql:host=localhost;dbname=$db", $username, $password);

        return $this;
    }

    public function configureDropbox($key, $secret, $token)
    {
        $app = new DropboxApp($key, $secret, $token);

        $this->uploader = new Dropbox($app);

        return $this;
    }

    public function backup()
    {
        $name = 'backup-' . date('Ymd-H-i-s') . '.sql';

        $this->dumper->start($name);

        $dropboxFile = new DropboxFile($name);

        $file = $this->uploader->upload($dropboxFile, "/$name", ['autorename' => true]);

        unlink($name);
    }
}

Allow configuration methods to be chained.


Update the stored hash in the database if it is too old


<?php
/*
 * Plugin Name: LuckyGrids
 * Version: 0.1.0
 * Plugin URI: http://luckygrids.io/wordpress
 * Description: Embed LuckyGrids using a shortcode.
 * Author: Ryan Burnette
 * Author URI: http://ryanburnette.com
 * Requires at least: 2.5
 * Tested up to: 4.1
 */

function luckygrids_embed_code($id) {
  return '

';
}

function luckygrids_shortcode($atts) {
  $defaults = array();
  $a = shortcode_atts($defaults, $atts);
  $id = $a['id'];
  return luckygrids_embed_code($id);
}

add_shortcode('luckygrid', 'luckygrids_shortcode');
add_shortcode('luckygrids', 'luckygrids_shortcode');

<?php
/*
 * Plugin Name: LuckyGrids
 * Version: 0.1.0
 * Plugin URI: http://luckygrids.io/wordpress
 * Description: Embed LuckyGrids using a shortcode.
 * Author: Ryan Burnette
 * Author URI: http://ryanburnette.com
 * Requires at least: 2.5
 * Tested up to: 4.0.1
 */

function luckygrids_embed_code($id) {
  return '

';
}

function luckygrids_shortcode_atts($atts) {
  $supported = array(
    'id' => '0'
  );
  return shortcode_atts($supported, $atts);
}

function luckygrids_shortcode($atts) {
  $atts = luckygrids_shortcode_atts($atts);
  return luckygrids_embed_code($atts['id']);
}

add_shortcode('luckygrid', 'luckygrids_shortcode');
add_shortcode('luckygrids', 'luckygrids_shortcode');

Refactor and fix string concat typo

Refactor and fix string concat typo


<?php
/**
 * Frontend {{ moduleName }} {{ action }} action
 */
class Frontend{{ moduleName|capitalize }}{{ action|capitalize }} extends FrontendBaseBlock
{
    /**
     * Execute the extra
     *
     * @return void
     */
    public function execute()
    {
        parent::execute();
        $this->loadTemplate();
        $this->getData();
        $this->parse();
    }

    /**
     * Load the data, don't forget to validate the incoming data
     *
     * @return void
     */
    protected function getData()
    {

    }

    /**
     * Parse the data into the template
     *
     * @return void
     */
    protected function parse()
    {

    }
}

<?php
/**
 * Frontend {{ moduleName }} {{ action }} action
 */
class Frontend{{ moduleName|capitalize }}{{ action|capitalize }} extends FrontendBaseBlock
{
    /**
     * Execute the extra
     *
     * @return void
     */
    public function execute()
    {
        parent::execute();
        $this->loadTemplate();
        $this->getData();
        $this->parse();
    }

    /**
     * Load the data, don't forget to validate the incoming data
     *
     * @return void
     */
    protected function getData()
    {

    }

    /**
     * Parse the data into the template
     *
     * @return void
     */
    protected function parse()
    {
        // Breadcrumbs
        $this->breadcrumb->addElement(
            SpoonFilter::ucfirst(FL::lbl('{{ moduleName|capitalize }}')),
            FrontendNavigation::getBackendURLForBlock('index', '{{ moduleName }}')
        );
{% if action != 'index' %}
        $this->breadcrumb->addElement(
            SpoonFilter::ucfirst(FL::lbl('{{ action|capitalize }}')),
            FrontendNavigation::getBackendURLForBlock('{{ action }}', '{{ moduleName }}')
        );
{% endif %}
    }
}

Add breadcrumbs to the frontend actions

Add breadcrumbs to the frontend actions

Fixes #11


<?php

namespace DI\Test\IntegrationTest\Definitions;

use DI\Annotation\Inject;
use DI\ContainerBuilder;
use DI\Test\IntegrationTest\Fixtures\Implementation1;
use DI\Test\IntegrationTest\Fixtures\Interface1;

/**
 * Test definitions using wildcards.
 */
class WildcardDefinitionsTest extends \PHPUnit_Framework_TestCase
{
    public function test_wildcards()
    {
        $builder = new ContainerBuilder();
        $builder->addDefinitions([
            'foo*'                                 => 'bar',
            'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'),
        ]);
        $container = $builder->build();

        $this->assertEquals('bar', $container->get('foo1'));

        $object = $container->get(Interface1::class);
        $this->assertInstanceOf(Implementation1::class, $object);
    }

    public function test_wildcards_as_dependency()
    {
        $builder = new ContainerBuilder();
        $builder->useAnnotations(true);
        $builder->addDefinitions([
            'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'),
        ]);
        $container = $builder->build();

        /** @var WildcardDefinitionsTestFixture $object */
        $object = $container->get(WildcardDefinitionsTestFixture::class);
        $this->assertInstanceOf(Implementation1::class, $object->dependency);
    }
}

class WildcardDefinitionsTestFixture
{
    /**
     * @Inject
     * @var Interface1
     */
    public $dependency;
}

<?php

namespace DI\Test\IntegrationTest\Definitions;

use DI\Annotation\Inject;
use DI\ContainerBuilder;
use DI\Test\IntegrationTest\BaseContainerTest;
use DI\Test\IntegrationTest\Fixtures\Implementation1;
use DI\Test\IntegrationTest\Fixtures\Interface1;

/**
 * Test definitions using wildcards.
 */
class WildcardDefinitionsTest extends BaseContainerTest
{
    /**
     * @dataProvider provideContainer
     */
    public function test_wildcards(ContainerBuilder $builder)
    {
        $builder->addDefinitions([
            'foo*' => 'bar',
            'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'),
        ]);
        $container = $builder->build();

        $this->assertEquals('bar', $container->get('foo1'));

        $object = $container->get(Interface1::class);
        $this->assertInstanceOf(Implementation1::class, $object);
    }

    /**
     * @dataProvider provideContainer
     */
    public function test_wildcards_as_dependency(ContainerBuilder $builder)
    {
        $builder->useAnnotations(true);
        $builder->addDefinitions([
            'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'),
        ]);
        $container = $builder->build();

        /** @var WildcardDefinitionsTestFixture $object */
        $object = $container->get(WildcardDefinitionsTestFixture::class);
        $this->assertInstanceOf(Implementation1::class, $object->dependency);
    }
}

class WildcardDefinitionsTestFixture
{
    /**
     * @Inject
     * @var Interface1
     */
    public $dependency;
}

Cover wildcard definitions for the compiled container


<?php
namespace CrudJsonApi\Test\App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class CountriesTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Currencies');
        $this->belongsTo('NationalCapitals');

        $this->hasMany('Cultures');
        $this->hasMany('NationalCities');

        // e.g. Italy has Vatican
        $this->hasMany('SubCountries', [
            'className' => 'Countries',
            'propertyName' => 'subcountries' //not-default to mess a little
        ]);

        // e.g. Vatican has Italy
        $this->belongsTo('SuperCountries', [
            'className' => 'Countries',
            'propertyName' => 'supercountry'
        ]);
    }

    public function validationDefault(Validator $validator)
    {
        // used for testing built-in validation rules/messages
        $validator
            ->requirePresence('name')
            ->notEmpty('name');

        // used for testing user-defined rules/messages
        $validator
            ->notEmpty('code')
            ->add('code', [
                'UPPERCASE_ONLY' => [
                    'rule' => ['custom', '/^([A-Z]+)+$/'],
                    'message' => "Field must be uppercase only"
                ]
            ]);

        return $validator;
    }
}

<?php
namespace CrudJsonApi\Test\App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class CountriesTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Currencies');
        $this->belongsTo('NationalCapitals');

        $this->hasMany('Cultures');
        $this->hasMany('NationalCities');

        // e.g. Italy has Vatican
        $this->hasMany('SubCountries', [
            'className' => 'Countries',
            'foreignKey' => 'supercountry_id',
            'propertyName' => 'subcountries' //not-default to mess a little
        ]);

        // e.g. Vatican has Italy
        $this->belongsTo('SuperCountries', [
            'className' => 'Countries',
            'foreignKey' => 'supercountry_id',
            'propertyName' => 'supercountry'
        ]);
    }

    public function validationDefault(Validator $validator)
    {
        // used for testing built-in validation rules/messages
        $validator
            ->requirePresence('name')
            ->notEmpty('name');

        // used for testing user-defined rules/messages
        $validator
            ->notEmpty('code')
            ->add('code', [
                'UPPERCASE_ONLY' => [
                    'rule' => ['custom', '/^([A-Z]+)+$/'],
                    'message' => "Field must be uppercase only"
                ]
            ]);

        return $validator;
    }
}

Add explicit foreign keys in countries table.


<?php if(!is_front_page()): ?>

        <?php echo roots_title(); ?>

<?php endif; ?>

<?php $hide_title = get_field( "hide_page_header_title" ); ?>
<?php if(!is_front_page() && !is_array($hide_title)): ?>

        <?php echo roots_title(); ?>

<?php endif; ?>

Hide page header with custom field settings


<?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('LACONICA', true);

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

class HashTagDetectionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     *
     */
    public function testProduction($content, $expected)
    {
        $rendered = common_render_text($content);
        $this->assertEquals($expected, $rendered);
    }

    static public function provider()
    {
        return array(
                     array('hello',
                           'hello'),
                     array('#hello',
                           'hello'),
                     );
    }
}

<?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('LACONICA', true);

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

class HashTagDetectionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     *
     */
    public function testProduction($content, $expected)
    {
        $rendered = common_render_text($content);
        $this->assertEquals($expected, $rendered);
    }

    static public function provider()
    {
        return array(
                     array('hello',
                           'hello'),
                     array('#hello',
                           '# common_canonical_tag('hello'))) . '" rel="tag">hello'),
                     );
    }
}

Correct the hash tag test

Correct the hash tag test


<?php

use tests\_pages\LoginPage;

$I = new WebGuy($scenario);
$I->wantTo('ensure that login works');

$loginPage = LoginPage::openBy($I);

$I->see('Login', 'h1');

$I->amGoingTo('try to login with empty credentials');
$loginPage->login('', '');
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.');
$I->see('Password cannot be blank.');

$I->amGoingTo('try to login with wrong credentials');
$loginPage->login('admin', 'wrong');
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.');

$I->amGoingTo('try to login with correct credentials');
$loginPage->login('admin', 'admin');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see user info');
$I->see('Logout (admin)');

<?php

use tests\_pages\LoginPage;

$I = new WebGuy($scenario);
$I->wantTo('ensure that login works');

$loginPage = LoginPage::openBy($I);

$I->see('Login', 'h1');

$I->amGoingTo('try to login with empty credentials');
$loginPage->login('', '');
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.');
$I->see('Password cannot be blank.');

$I->amGoingTo('try to login with wrong credentials');
$loginPage->login('admin', 'wrong');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.');

$I->amGoingTo('try to login with correct credentials');
$loginPage->login('admin', 'admin');
if (method_exists($I, 'wait')) {
    $I->wait(3); // only for selenium
}
$I->expectTo('see user info');
$I->see('Logout (admin)');

Add wait() to login test with wrong credentials to fix WebDriver test


<?php
declare(strict_types=1);

namespace ApiClients\Tests\Foundation\Middleware;

use ApiClients\Foundation\Middleware\MiddlewareInterface;
use ApiClients\Foundation\Middleware\PostTrait;
use ApiClients\Foundation\Middleware\PreTrait;

class DummyMiddleware implements MiddlewareInterface
{
    use PreTrait;
    use PostTrait;
}

<?php
declare(strict_types=1);

namespace ApiClients\Tests\Foundation\Middleware;

use ApiClients\Foundation\Middleware\DefaultPriorityTrait;
use ApiClients\Foundation\Middleware\MiddlewareInterface;
use ApiClients\Foundation\Middleware\PostTrait;
use ApiClients\Foundation\Middleware\PreTrait;

class DummyMiddleware implements MiddlewareInterface
{
    use DefaultPriorityTrait;
    use PreTrait;
    use PostTrait;
}

Use the new priority trait in the dummy middle ware


@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}

    @if ($model->id)

            id) }}">
                @lang('menus::global.New menulink')

                @include('core::admin._lang-switcher-for-list')

    @endif

        {!! BootForm::text(__('Name'), 'name') !!}
        {!! BootForm::text(__('Class'), 'class') !!}
        {!! TranslatableBootForm::hidden('status')->value(0) !!}
        {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}

    @if ($model->id)

            id) }}">
                @lang('menus::global.New menulink')

                @include('core::admin._lang-switcher-for-list')

    @endif

        {!! BootForm::text(__('Name'), 'name') !!}
        {!! BootForm::text(__('Class'), 'class') !!}
        {!! TranslatableBootForm::hidden('status')->value(0) !!}
        {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}

Use of @component for buttons in form

Use of @component for buttons in form


<?php

namespace Adldap\Laravel\Traits;

use Adldap\Models\User;
use Adldap\Laravel\Events\AuthenticatedWithWindows;
use Adldap\Laravel\Events\DiscoveredWithCredentials;
use Adldap\Laravel\Events\AuthenticatedWithCredentials;
use Illuminate\Contracts\Auth\Authenticatable;

trait DispatchesAuthEvents
{
    /**
     * Dispatches an authentication event when users login by their credentials.
     *
     * @param User                 $user
     * @param Authenticatable|null $model
     *
     * @return void
     */
    public function handleAuthenticatedWithCredentials(User $user, Authenticatable $model = null)
    {
        event(new AuthenticatedWithCredentials($user, $model));
    }

    /**
     * Dispatches an event when a user has logged in via the WindowsAuthenticate middleware.
     *
     * @param User                 $user
     * @param Authenticatable|null $model
     *
     * @return void
     */
    protected function handleAuthenticatedWithWindows(User $user, Authenticatable $model = null)
    {
        event(new AuthenticatedWithWindows($user, $model));
    }

    /**
     * Dispatches an event when a user has been discovered by the their credentials.
     *
     * @param User $user
     */
    protected function handleDiscoveredWithCredentials(User $user)
    {
        event(new DiscoveredWithCredentials($user));
    }
}

<?php

namespace Adldap\Laravel\Traits;

use Adldap\Models\User;
use Adldap\Laravel\Events\AuthenticatedWithWindows;
use Adldap\Laravel\Events\DiscoveredWithCredentials;
use Adldap\Laravel\Events\AuthenticatedWithCredentials;
use Illuminate\Support\Facades\Event;
use Illuminate\Contracts\Auth\Authenticatable;

trait DispatchesAuthEvents
{
    /**
     * Dispatches an authentication event when users login by their credentials.
     *
     * @param User                 $user
     * @param Authenticatable|null $model
     *
     * @return void
     */
    public function handleAuthenticatedWithCredentials(User $user, Authenticatable $model = null)
    {
        Event::fire(new AuthenticatedWithCredentials($user, $model));
    }

    /**
     * Dispatches an event when a user has logged in via the WindowsAuthenticate middleware.
     *
     * @param User                 $user
     * @param Authenticatable|null $model
     *
     * @return void
     */
    protected function handleAuthenticatedWithWindows(User $user, Authenticatable $model = null)
    {
        Event::fire(new AuthenticatedWithWindows($user, $model));
    }

    /**
     * Dispatches an event when a user has been discovered by the their credentials.
     *
     * @param User $user
     */
    protected function handleDiscoveredWithCredentials(User $user)
    {
        Event::fire(new DiscoveredWithCredentials($user));
    }
}

Use facade for firing events

Use facade for firing events


<?php
/**
 * Raguvis CmsNavigation
 */

namespace Raguvis\CmsNavigation\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Add Include in navigation flag
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $setup->getConnection()->addColumn(
            $setup->getTable('cms_page'),
            'show_in_navigation',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
                'nullable' => false,
                'comment' => 'Flag whether or not CMS page should be included in top navigation'
            ]
        );
        $installer->endSetup();
    }
}

<?php
/**
 * Raguvis CmsNavigation
 */

namespace Raguvis\CmsNavigation\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Add Include in navigation flag
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $setup->getConnection()->addColumn(
            $setup->getTable('cms_page'),
            'show_in_navigation',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
                'nullable' => false,
                'comment' => 'Flag whether or not CMS page should be included in top navigation',
                'default' => 0
            ]
        );
        $installer->endSetup();
    }
}

Fix cms_page field to have default value

Otherwise when cms page is added via code it will fail with error 'Integrity constraint violation: 1048 Column 'show_in_navigation' cannot be null'


<?php

use Ockcyp\WpJsCli\Command\GotoCommand;

class GotoCommandTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->gotoCommand = new GotoCommand;
    }

    /**
     * @expectedException Ockcyp\WpJsCli\Exception\MissingCommandArgumentException
     */
    public function testGivesMissingCommandArgumentException()
    {
        $this->gotoCommand->execute();
    }
}

<?php

use Ockcyp\WpJsCli\Command\GotoCommand;

class GotoCommandTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->gotoCommand = new GotoCommand;
    }

    /**
     * @expectedException Ockcyp\WpJsCli\Exception\MissingCommandArgumentException
     */
    public function testGivesMissingCommandArgumentException()
    {
        $this->gotoCommand->execute();
    }

    public function testReturnsNullWhenPostNotFound()
    {
        $res = $this->gotoCommand->addArguments('about')
            ->execute();

        $this->assertNotEmpty($res);
        $this->assertEquals('http://www.ockwebs.com/about/', $res['url']);
    }

    public function testReturnsPostUrl()
    {
        $res = $this->gotoCommand->addArguments('not-a-post')
            ->execute();

        $this->assertNull($res);
    }
}

Add more tests for GotoCommand

Add more tests for GotoCommand


<?php setup_postdata($post); ?>

        <?php  if ( fik_product_stock_quantity() == 0) { ?>
            Out of stock
        <?php  } ?>
        <?php if ( get_fik_previous_price() ) { ?>
            Rebajado
        <?php } ?>
            <a href="<?php the_permalink(); ?>">
                <?php if ( has_post_thumbnail() ) { ?>
                    <?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
                <?php } ?>

                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                    <?php the_fik_previous_price(); ?><?php the_fik_price(); ?>

                <?php echo get_the_tag_list( '
', ', ', '
') ?>

<?php setup_postdata($post); ?>

        <?php  if ( fik_product_stock_quantity() == 0) { ?>
            Out of stock
        <?php  } ?>
        <?php if ( get_fik_previous_price() && fik_product_stock_quantity() != 0) { ?>
            Rebajado
        <?php } ?>
            <a href="<?php the_permalink(); ?>">
                <?php if ( has_post_thumbnail() ) { ?>
                    <?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
                <?php } ?>

                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                    <?php the_fik_previous_price(); ?><?php the_fik_price(); ?>

                <?php echo get_the_tag_list( '
', ', ', '
') ?>

Remove rebajado label if product is out of stock


<?php

use Litipk\BigNumbers\Decimal as Decimal;

/**
 * @group cos
 */
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
    public function cosProvider() {
        // Some values provided by Mathematica
        return array(
            array('1', '0.54030230586814', 14),
            array('123.123', '-0.82483472946164834', 17),
            array('15000000000', '-0.72218064388924347681', 20)
        );
    }

    /**
     * @dataProvider cosProvider
     */
    public function testSimple($nr, $answer, $digits)
    {
        $x = Decimal::fromString($nr);
        $cosX = $x->cos((int)$digits);

        $this->assertTrue(
            Decimal::fromString($answer)->equals($cosX),
            "The answer must be " . $answer . ", but was " . $cosX
        );
    }
}

<?php

use Litipk\BigNumbers\Decimal as Decimal;

/**
 * @group cos
 */
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
    public function cosProvider() {
        // Some values provided by Mathematica
        return array(
            array('1', '0.54030230586814', 14),
            array('123.123', '-0.82483472946164834', 17),
            array('15000000000', '-0.72218064388924347683', 20)
        );
    }

    /**
     * @dataProvider cosProvider
     */
    public function testSimple($nr, $answer, $digits)
    {
        $x = Decimal::fromString($nr);
        $cosX = $x->cos((int)$digits);

        $this->assertTrue(
            Decimal::fromString($answer)->equals($cosX),
            "The answer must be " . $answer . ", but was " . $cosX
        );
    }
}

Fix of the cosinue test for the negative rounding error.


<?php

namespace MageTitans\Workshop\Domain\Stock;

use PHPUnit\Framework\TestCase;

final class StockTest extends TestCase
{
    public function testGetInStock()
    {
        $stock = new Stock(
            false,
            0
        );
        $this->assertFalse($stock->getInStock());
    }
}

<?php

namespace MageTitans\Workshop\Domain\Stock;

use PHPUnit\Framework\TestCase;

final class StockTest extends TestCase
{
    /**
     * @dataProvider getInStockProvider
     */
    public function testGetInStock($inStock, $expectedInStock)
    {
        $stock = new Stock(
            $inStock,
            100
        );
        $this->assertEquals($expectedInStock, $stock->getInStock());
    }

    public function getInStockProvider()
    {
        return [
            [true, true],
            [false, false],
            [1, 1],
            [0, 0]
        ];
    }

    /**
     * @dataProvider getStockLevelProvider
     */
    public function testGetStockLevel($stockLevel, $expectedStockLevel)
    {
        $stock = new Stock(
            true,
            $stockLevel
        );
        $this->assertEquals($expectedStockLevel, $stock->getStockLevel());
    }

    public function getStockLevelProvider()
    {
        return [
            [300, 300],
            [20, 20],
            [0, 0],
            [5, 5]
        ];
    }
}

Test both functions in the stock object

Test both functions in the stock object


<?php

namespace Rezzza\RestApiBehatExtension;

abstract class ExpectationFailed extends \Exception
{
    abstract function getContextText();

    /**
     * Returns exception message with additional context info.
     *
     * @return string
     */
    public function __toString()
    {
        try {
            $contextText = $this->pipeString($this->trimString($this->getContextText())."\n");
            $string = sprintf("%s\n\n%s", $this->getMessage(), $contextText);
        } catch (\Exception $e) {
            return $this->getMessage();
        }

        return $string;
    }

    /**
     * Prepends every line in a string with pipe (|).
     *
     * @param string $string
     *
     * @return string
     */
    protected function pipeString($string)
    {
        return '|  '.strtr($string, array("\n" => "\n|  "));
    }

    /**
     * Trims string to specified number of chars.
     *
     * @param string $string response content
     * @param int    $count  trim count
     *
     * @return string
     */
    protected function trimString($string, $count = 1000)
    {
        $string = trim($string);
        if ($count < mb_strlen($string)) {
            return mb_substr($string, 0, $count - 3).'...';
        }

        return $string;
    }
}

<?php

namespace Rezzza\RestApiBehatExtension;

abstract class ExpectationFailed extends \Exception
{
    abstract public function getContextText();

    /**
     * Returns exception message with additional context info.
     *
     * @return string
     */
    public function __toString()
    {
        try {
            $contextText = $this->pipeString($this->trimString($this->getContextText())."\n");
            $string = sprintf("%s\n\n%s", $this->getMessage(), $contextText);
        } catch (\Exception $e) {
            return $this->getMessage();
        }

        return $string;
    }

    /**
     * Prepends every line in a string with pipe (|).
     *
     * @param string $string
     *
     * @return string
     */
    protected function pipeString($string)
    {
        return '|  '.strtr($string, ["\n" => "\n|  "]);
    }

    /**
     * Trims string to specified number of chars.
     *
     * @param string $string response content
     * @param int    $count  trim count
     *
     * @return string
     */
    protected function trimString($string, $count = 1000)
    {
        $string = trim($string);
        if ($count < mb_strlen($string)) {
            return mb_substr($string, 0, $count - 3).'...';
        }

        return $string;
    }
}

Use php array sugar syntax

Use php array sugar syntax


<?php

namespace Flint;

use Flint\Controller\ControllerResolver;

/**
 * @package Flint
 */
class Application extends \Silex\Application
{
    /**
     * Assigns rootDir and debug to the pimple container. Also replaces the
     * normal resolver with a ApplicationAware Resolver.
     *
     * @param string $rootDir
     * @param boolean $debug
     */
    public function __construct($rootDir, $debug = false)
    {
        parent::__construct();

        $this['root_dir'] = $rootDir;
        $this['debug'] = $debug;

        $this['resolver'] = $this->share($this->extend('resolver', function ($resolver, $app) {
            return new ControllerResolver($resolver, $app);
        }));
    }
}

<?php

namespace Flint;

use Flint\Provider\ControllerServiceProvider;
use Silex\Provider\TwigServiceProvider;

/**
 * @package Flint
 */
class Application extends \Silex\Application
{
    /**
     * Assigns rootDir and debug to the pimple container. Also replaces the
     * normal resolver with a ApplicationAware Resolver.
     *
     * @param string $rootDir
     * @param boolean $debug
     */
    public function __construct($rootDir, $debug = false)
    {
        parent::__construct();

        $this['root_dir'] = $rootDir;
        $this['debug']    = $debug;

        $this->register(new ControllerServiceProvider);
        $this->register(new TwigServiceProvider);
    }
}

Enable Twig and the ControllerServiceProvider


<?php

if (!function_exists('coalesce')) {

    /**
     * @return The first non null argument (or null)
     */
    function coalesce() {
        return array_shift(array_filter(func_get_args(), function ($value) {
            return !is_null($value);
        }));
    }
}

if (!function_exists('coalescy')) {

    /**
     * @return The first non "falsy" argument (or null)
     */
    function coalescy() {
        return array_shift(array_filter(func_get_args()));
    }
}

if (!function_exists('val')) {

    /**
     * @param array $arr
     * @param string|int $index
     * @return The array element or null if it's undefined
     */
    function val($arr, $index) {
        return isset($arr[$index]) ? $arr[$index] : null;
    }
}

?>

<?php

if (!function_exists('coalesce')) {

    /**
     * @return The first non null argument (or null)
     */
    function coalesce() {
        $notNullArgs = array_filter(func_get_args(), function ($value) {
            return !is_null($value);
        });
        return array_shift($notNullArgs);
    }
}

if (!function_exists('coalescy')) {

    /**
     * @return The first non "falsy" argument (or null)
     */
    function coalescy() {
        $notFalsyArgs = array_filter(func_get_args());
        return array_shift($notFalsyArgs);
    }
}

if (!function_exists('val')) {

    /**
     * @param array $arr
     * @param string|int $index
     * @return The array element or null if it's undefined
     */
    function val($arr, $index) {
        return isset($arr[$index]) ? $arr[$index] : null;
    }
}

?>

Fix a PHP strict error

Fix a PHP strict error


<?php
// this is the default file
// please copy to config.php and adjust carefully before executing tests
// make sure to never set the constants to your production database (otherwise it will be cleared)

//chado test database
define('DEFAULT_DBVERSION', 'test');
define('DATABASE', serialize(array('test' => array(
       'DB_ADAPTER' => 'pgsql',
       'DB_CONNSTR' => 'pgsql:host=localhost;dbname=testchado;port=5432',
       'DB_USERNAME' => 'postgres',
       'DB_PASSWORD' => '',
       'DB_HOST' => 'localhost',
       'DB_PORT' => 5432,
       'DB_DBNAME' => 'testchado'
))));

?>

<?php

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

// this is the default file
// please copy to config.php and adjust carefully before executing tests
// make sure to never set the constants to your production database (otherwise it will be cleared)

//chado test database
define('DEFAULT_DBVERSION', 'test');
define('DATABASE', serialize(array('test' => array(
       'DB_ADAPTER' => 'pgsql',
       'DB_CONNSTR' => 'pgsql:host=localhost;dbname=testchado;port=5432',
       'DB_USERNAME' => 'postgres',
       'DB_PASSWORD' => '',
       'DB_HOST' => 'localhost',
       'DB_PORT' => 5432,
       'DB_DBNAME' => 'testchado'
))));

?>

Add require statement to travis conf

Add require statement to travis conf


<?=$title?>

<?php foreach ($nav as $link=>&$info): ?>

            <a href="<?=$_base,'/',$module,$link?>" title="<?=$info['desc']?>">
<?php if (isset($info['icon'])) : ?>
            <span class="<?=$info['icon']?>" aria-hidden="true" style="font-size:48px;margin-top:10px">
<?php else : ?>
                <img src="<?=$_base,$info['imag']?>" alt="<?=$info['name']?>" align="middle" />
<?php endif; ?>
                <?=$info['name']?>

<?php endforeach; ?>

    ¿Cómo realizo el proceso de certificación utilizando LibreDTE?

Fix enlace a manual certificación

Fix enlace a manual certificación


<?php

namespace MongoDB\Tests\GridFS;

use MongoDB\Collection;
use MongoDB\GridFS\Bucket;
use MongoDB\Tests\FunctionalTestCase as BaseFunctionalTestCase;

/**
 * Base class for GridFS functional tests.
 */
abstract class FunctionalTestCase extends BaseFunctionalTestCase
{
    protected $bucket;
    protected $chunksCollection;
    protected $filesCollection;

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

        $this->bucket = new Bucket($this->manager, $this->getDatabaseName());
        $this->bucket->drop();

        $this->chunksCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.chunks');
        $this->filesCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.files');
    }

    /**
     * Asserts that a variable is a stream containing the expected data.
     *
     * Note: this will seek to the beginning of the stream before reading.
     *
     * @param string   $expectedContents
     * @param resource $stream
     */
    protected function assertStreamContents($expectedContents, $stream)
    {
        $this->assertInternalType('resource', $stream);
        $this->assertSame('stream', get_resource_type($stream));
        $this->assertEquals($expectedContents, stream_get_contents($stream, -1,.0));
    }

    /**
     * Creates an in-memory stream with the given data.
     *
     * @param string $data
     * @return resource
     */
    protected function createStream($data = '')
    {
        $stream = fopen('php://temp', 'w+b');
        fwrite($stream, $data);
        rewind($stream);

        return $stream;
    }
}

<?php

namespace MongoDB\Tests\GridFS;

use MongoDB\Collection;
use MongoDB\GridFS\Bucket;
use MongoDB\Tests\FunctionalTestCase as BaseFunctionalTestCase;

/**
 * Base class for GridFS functional tests.
 */
abstract class FunctionalTestCase extends BaseFunctionalTestCase
{
    protected $bucket;
    protected $chunksCollection;
    protected $filesCollection;

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

        $this->bucket = new Bucket($this->manager, $this->getDatabaseName());
        $this->bucket->drop();

        $this->chunksCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.chunks');
        $this->filesCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.files');
    }

    /**
     * Asserts that a variable is a stream containing the expected data.
     *
     * Note: this will seek to the beginning of the stream before reading.
     *
     * @param string   $expectedContents
     * @param resource $stream
     */
    protected function assertStreamContents($expectedContents, $stream)
    {
        $this->assertInternalType('resource', $stream);
        $this->assertSame('stream', get_resource_type($stream));
        $this->assertEquals($expectedContents, stream_get_contents($stream, -1, 0));
    }

    /**
     * Creates an in-memory stream with the given data.
     *
     * @param string $data
     * @return resource
     */
    protected function createStream($data = '')
    {
        $stream = fopen('php://temp', 'w+b');
        fwrite($stream, $data);
        rewind($stream);

        return $stream;
    }
}

Fix typo in stream_get_contents() call

Fix typo in stream_get_contents() call


<?php

/**
 * This file is part of the rybakit/msgpack.php package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace MessagePack\Tests\Perf;

class TestSkippedException extends \RuntimeException
{
    private $test;

    public function __construct(Test $test, int $code = null, \Exception $previous = null)
    {
        $message = sprintf('"%s" test is skipped', $test->getName());

        parent::__construct($message, $code, $previous);

        $this->test = $test;
    }

    public function getTest() : Test
    {
        return $this->test;
    }
}

<?php

/**
 * This file is part of the rybakit/msgpack.php package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace MessagePack\Tests\Perf;

class TestSkippedException extends \RuntimeException
{
    /** @var Test */
    private $test;

    public function __construct(Test $test, int $code = 0, \Throwable $previous = null)
    {
        $message = sprintf('"%s" test is skipped', $test->getName());

        parent::__construct($message, $code, $previous);

        $this->test = $test;
    }

    public function getTest() : Test
    {
        return $this->test;
    }
}

Fix deprecation warning regarding passing null to parameter of type int


<?php

use Benrowe\Laravel\Config\Config;

/**
 * Tests to ensure invalid data is not allowed into the config (data that can't be persisted)
 */
class InvalidConfigTest extends PHPUnit_Framework_TestCase
{
    public function testNullData()
    {
        // invalid data
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(null);

    }

    public function testObjData()
    {
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(new stdClass);
    }
}

<?php

use Benrowe\Laravel\Config\Config;

/**
 * Tests to ensure invalid data is not allowed into the config (data that can't be persisted)
 */
class InvalidConfigTest extends PHPUnit_Framework_TestCase
{
    public function testNullData()
    {
        // invalid data
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(null);

    }

    public function testObjData()
    {
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(new stdClass);
    }

    public function testNonStringForValue()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', new stdClass);
    }
}

Add new test case for adding object value


<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library')
)));

//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());

require_once 'CcMusicDirsQuery.php';
require_once 'BaseCcMusicDirsQuery.php';

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library')
)));

//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());

require_once 'CcMusicDirsQuery.php';
require_once 'BaseCcMusicDirsQuery.php';

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

CC-5781: Upgrade script for new storage quota implementation


<?php
namespace Webaholicson\Minimvc\Page\View;

/**
 * Main page controller. Default view for the entire system.
 *
 * @author Antonio Mendes <webaholicson@gmail.com>
 */
class Index extends \Webaholicson\Minimvc\Core\View\AbstractView
{
    protected $_view = 'layout';
}

<?php
namespace Webaholicson\Minimvc\Page\View;

/**
 * Main page controller. Default view for the entire system.
 *
 * @author Antonio Mendes <webaholicson@gmail.com>
 */
class Index extends \Webaholicson\Minimvc\Core\View\AbstractView
{
    protected $_template = 'layout';
}

Fix page module index view

Fix page module index view


<?php
/**
 * Project: notification-bundle
 * User: Leandro Luccerini <leandro.luccerini@gmail.com>
 * Date: 08/11/18
 * Time: 9.29
 */

namespace Mgilet\NotificationBundle\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Mgilet\NotificationBundle\Entity\NotificationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('mgilet_notification');

        $rootNode->children()
            ->scalarNode('notification_class')
                ->cannotBeEmpty()
                ->defaultValue(NotificationInterface::DEFAULT_NOTIFICATION_ENTITY_CLASS)
            ->end()
        ->end();

        return $treeBuilder;
    }
}

<?php
/**
 * Project: notification-bundle
 * User: Leandro Luccerini <leandro.luccerini@gmail.com>
 * Date: 08/11/18
 * Time: 9.29
 */

namespace Mgilet\NotificationBundle\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Mgilet\NotificationBundle\Entity\NotificationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('mgilet_notification');

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            $rootNode = $treeBuilder->root('mgilet_notification');
        }

        $rootNode->children()
            ->scalarNode('notification_class')
                ->cannotBeEmpty()
                ->defaultValue(NotificationInterface::DEFAULT_NOTIFICATION_ENTITY_CLASS)
            ->end()
        ->end();

        return $treeBuilder;
    }
}

Update TreeBuilder construction (Compatibility SF4.2+)


<?
//Get query string because $_GET does not work with mod rewrite
//This code should be rewritten at some point... It's ugly
//
//Multiple identical keys cannot be passed into pooch. This is a Limitation of this implimentation.
//Example: Give the query string "id=2&id=3" the value of $query_string['id'] would be 3.
function getQueryString(){
	global $query_string;
	$query_string = array();
	$new_query_string = array();
	if(strpos($_SERVER['REQUEST_URI'], '?')){
		$query_string = explode('?', $_SERVER['REQUEST_URI']);

		if(strpos($query_string[1], '&')){
			$query_string = explode('&', $query_string[1]);
			foreach ($query_string as $value) {
				$value_array = explode('=', $value);
				$new_query_string[$value_array[0]] = $value_array[1];
			}
			$query_string = $new_query_string;
		}else{
			$value_array = explode('=', $query_string[1]);
			$new_query_string[$value_array[0]] = $value_array[1];
		}
	}

	$query_string = $new_query_string;
}

getQueryString();
?>

<?
//Get query string because $_GET does not work with mod rewrite
//This code should be rewritten at some point... It's ugly
//
//Multiple identical keys cannot be passed into pooch. This is a Limitation of this implimentation.
//Example: Give the query string "id=2&id=3" the value of $query_string['id'] would be 3.
function getQueryString(){
	global $query_string;
	$query_string = array();
	$new_query_string = array();
	if(strpos($_SERVER['REQUEST_URI'], '?')){
		$query_string = explode('?', $_SERVER['REQUEST_URI']);

		if(strpos($query_string[1], '&')){
			$query_string = explode('&', $query_string[1]);
			foreach ($query_string as $value) {
				$value_array = explode('=', $value);
				$new_query_string[urldecode($value_array[0])] = urldecode($value_array[1]);
			}
			$query_string = $new_query_string;
		}else{
			$value_array = explode('=', $query_string[1]);
			$new_query_string[urldecode($value_array[0])] = urldecode($value_array[1]);
		}
	}

	$query_string = $new_query_string;
}

getQueryString();
?>

Add urldecode to query string class

Add urldecode to query string class


<?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.
 */

namespace Sylius\Component\Payment\Factory;

use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
final class PaymentFactory implements PaymentFactoryInterface
{
    /**
     * @var FactoryInterface
     */
    private $factory;

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

    /**
     * {@inheritDoc}
     */
    public function createNew()
    {
        return $this->factory->createNew();
    }

    /**
     * {@inheritdoc}
     */
    public function createWithAmountAndCurrencyCode($amount, $currencyCode)
    {
        /** @var PaymentInterface $payment */
        $payment = $this->factory->createNew();
        $payment->setAmount($amount);
        $payment->setCurrencyCode($currencyCode);

        return $payment;
    }
}

<?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.
 */

namespace Sylius\Component\Payment\Factory;

use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
final class PaymentFactory implements PaymentFactoryInterface
{
    /**
     * @var FactoryInterface
     */
    private $factory;

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

    /**
     * {@inheritdoc}
     */
    public function createNew()
    {
        return $this->factory->createNew();
    }

    /**
     * {@inheritdoc}
     */
    public function createWithAmountAndCurrencyCode($amount, $currencyCode)
    {
        /** @var PaymentInterface $payment */
        $payment = $this->factory->createNew();
        $payment->setAmount($amount);
        $payment->setCurrencyCode($currencyCode);

        return $payment;
    }
}

[CS] Fix invalid inheritdoc tags in many places


<?php

namespace App\Form\Type;

use App\Entity\Property;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Regex;

class UserPropertyListener implements EventSubscriberInterface
{
    private $forceEditable = false;

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

    public static function getSubscribedEvents() {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
        );
    }

    public function preSetData(FormEvent $ev) {
        $property = $ev->getData()->getProperty();
        /* @var $property Property */
        $options = array(
            'label' => $property->getDisplayName(),
            'required' => $property->isRequired(),
            'empty_data' => null,
        );
        if($property->isRequired()) {
            $options['constraints'][] = new NotNull;
        }
        $options['constraints'][] = new Regex($property->getValidationRegex());
        $ev->getForm()->add('data', $this->forceEditable||$property->isUserEditable()?'text':'bs_static', $options);
    }
}

<?php

namespace App\Form\Type;

use App\Entity\Property;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;

class UserPropertyListener implements EventSubscriberInterface
{
    private $forceEditable = false;

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

    public static function getSubscribedEvents() {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
        );
    }

    public function preSetData(FormEvent $ev) {
        $property = $ev->getData()->getProperty();
        /* @var $property Property */
        $options = array(
            'label' => $property->getDisplayName(),
            'required' => $property->isRequired()&&!$this->forceEditable,
            'empty_data' => null,
        );
        if($property->isRequired()&&!$this->forceEditable) {
            $options['constraints'][] = new NotBlank;
        }
        $options['constraints'][] = new Regex($property->getValidationRegex());
        $ev->getForm()->add('data', $this->forceEditable||$property->isUserEditable()?'text':'bs_static', $options);
    }
}

Use NotBlank validator for clearer error messages, allow admin to always submit blanks


<?php
namespace Api\V8\Param\Options;

use Api\V8\JsonApi\Repository\Filter as FilterRepository;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class Filter extends BaseOption
{
    /**
     * @inheritdoc
     */
    public function add(OptionsResolver $resolver)
    {
        $resolver
            ->setDefined('filter')
            ->setAllowedTypes('filter', 'array')
            ->setAllowedValues('filter', $this->validatorFactory->createClosure([
                new Assert\NotBlank(),
            ]))
            ->setNormalizer('filter', function (Options $options, $values) {
                // we don't support multiple level filtering. for now.
                $bean = $this->beanManager->newBeanSafe($options->offsetGet('moduleName'));
                $filter = new FilterRepository($bean->db);

                return $filter->parseWhere($bean, $values);
            });
    }
}

<?php
namespace Api\V8\Param\Options;

use Api\V8\JsonApi\Repository\Filter as FilterRepository;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class Filter extends BaseOption
{
    /**
     * @inheritdoc
     */
    public function add(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults(['filter' => [
                'deleted' => [
                    'eq' => 0
                ]]])
            ->setDefined('filter')
            ->setAllowedTypes('filter', 'array')
            ->setAllowedValues('filter', $this->validatorFactory->createClosure([
                new Assert\NotBlank(),
            ]))
            ->setNormalizer('filter', function (Options $options, $values) {
                // we don't support multiple level filtering. for now.
                $bean = $this->beanManager->newBeanSafe($options->offsetGet('moduleName'));
                $filter = new FilterRepository($bean->db);

                return $filter->parseWhere($bean, $values);
            });
    }
}

Add a default filter parameter to API requests to exclude deleted records


<?php

namespace Fuzz\ApiServer\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Fuzz\ApiServer\Response\ResponseFactory;
use Illuminate\Support\ServiceProvider;

class ApiServerServiceProvider extends ServiceProvider
{
	/**
	* Register any other events for your application.
	*
	* @param  \Illuminate\Contracts\Events\Dispatcher $events
	* @return void
	*/
	public function boot(DispatcherContract $events)
	{
		$config_file = realpath(__DIR__ . '/../config/api.php');
		$this->publishes(
			[
				$config_file => config_path('api.php'),
			]
		);
	}

	/**
	 * Register bindings in the container.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton(ResponseFactory::class, function ($app) {
			return new ResponseFactory(config('api.responders'));
		});
	}
}

<?php

namespace Fuzz\ApiServer\Providers;

use Fuzz\ApiServer\Response\CsvResponder;
use Fuzz\ApiServer\Response\JsonResponder;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Fuzz\ApiServer\Response\ResponseFactory;
use Illuminate\Support\ServiceProvider;

class ApiServerServiceProvider extends ServiceProvider
{
	/**
	* Register any other events for your application.
	*
	* @param  \Illuminate\Contracts\Events\Dispatcher $events
	* @return void
	*/
	public function boot(DispatcherContract $events)
	{
		$config_file = realpath(__DIR__ . '/../config/api.php');
		$this->publishes(
			[
				$config_file => config_path('api.php'),
			]
		);
	}

	/**
	 * Register bindings in the container.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton(ResponseFactory::class, function ($app) {
			return new ResponseFactory(config('api.responders', [
				'json' => JsonResponder::class,
				'csv'  => CsvResponder::class,
			]));
		});
	}
}

Add default config to service provider

Add default config to service provider


<?php
/**
 * @author Marc Pantel <pantel.m@gmail.com>
 */
namespace Payum\Core\Bridge\Symfony\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * CreditCardDateValidator
 *
 * Validate if the Credit Card is not expired
 */
class CreditCardDateValidator extends ConstraintValidator
{
    /**
     * {@inheritDoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value) {
            return;
        }

        if (!($value instanceof \DateTime)) {
            $this->context->buildViolation($constraint->invalidMessage, array(
                '{{ value }}' => $value,
            ))
            ->addViolation();

            return;
        }

        /**
         * The Credit Card is not expired until last day of the month
         */
        $value->modify('last day of this month');

        if (null !== $constraint->min && $value < $constraint->min) {
            $this->context->buildViolation($constraint->minMessage)
                ->atPath('expireAt')
                ->addViolation();
        }
    }
}

<?php
/**
 * @author Marc Pantel <pantel.m@gmail.com>
 */
namespace Payum\Core\Bridge\Symfony\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * CreditCardDateValidator
 *
 * Validate if the Credit Card is not expired
 */
class CreditCardDateValidator extends ConstraintValidator
{
    /**
     * {@inheritDoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value) {
            return;
        }

        if (!($value instanceof \DateTime)) {
            if (method_exists($this->context, 'buildViolation')) {
                $this->context->buildViolation($constraint->invalidMessage, array(
                             '{{ value }}' => $value,
                         ))
                     ->addViolation();

                return;
            }

            $this->context->addViolationAt('expireAt', $constraint->invalidMessage, array(
                '{{ value }}' => $value,
            ));
        }

        /**
         * The Credit Card is not expired until last day of the month
         */
        $value->modify('last day of this month');

        if (null !== $constraint->min && $value < $constraint->min) {
            if (method_exists($this->context, 'buildViolation')) {

                $this->context->buildViolation($constraint->minMessage)
                    ->atPath('expireAt')
                    ->addViolation();

                return;
            }

            $this->context->addViolationAt('expireAt', $constraint->minMessage);

        }
    }
}

Test if method buildViolation exist and fallback to addViolation for symfony < 2.5


<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }

}

<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }

}

Fix wrong table preferrence for role_user


<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Helper;

/**
 * Helps with class name transformations
 */
class ClassNameTransformer
{
    /**
     * Tries to map a model name to the associated entity class name.
     *
     * @param string $modelClassName
     *
     * @return string
     */
    public function transformModelToEntity (string $modelClassName) : string
    {
        $className = trim($modelClassName, "\\");
        $className = preg_replace("~\\\\Model\\\\(.+)Model$~", "\\\\Entity\\\\\\1", $className);
        return $className;
    }
}

<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Helper;

/**
 * Helps with class name transformations
 *
 * @internal
 */
class ClassNameTransformer
{
    /**
     * Tries to map a model name to the associated entity class name.
     *
     * @param string $modelClassName
     *
     * @return string
     */
    public function transformModelToEntity (string $modelClassName) : string
    {
        $className = trim($modelClassName, "\\");
        $className = preg_replace("~\\\\Model\\\\(.+)Model$~", "\\\\Entity\\\\\\1", $className);
        return $className;
    }
}

Make class name transformer internal

Make class name transformer internal


<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Utilities;

abstract class HtmlUtils
{
    public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery)
    {
        $html = self::normalizeHTML($html);

        libxml_use_internal_errors(true);

        $DOMDocument->loadHTML($html);

        $xmlErrors = libxml_get_errors();

        /** @var \LibXMLError $error */
        foreach ($xmlErrors as $error)
        {
            // http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors
            if ($error->code === 801)
            {
                continue;
            }

            @trigger_error($error->message, E_USER_WARNING);
        }

        libxml_clear_errors();

        $xpath = new \DOMXPath($DOMDocument);

        return $xpath->query($xpathQuery);
    }

    private static function normalizeHTML($html)
    {
        if (strpos($html, '' === false) || strpos($html, '') === false)
        {
            return sprintf('%s', $html);
        }

        return $html;
    }
}

<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Utilities;

abstract class HtmlUtils
{
    public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery)
    {
        $html = self::normalizeHTML($html);

        libxml_use_internal_errors(true);

        $DOMDocument->loadHTML($html);

        $xmlErrors = libxml_get_errors();

        /** @var \LibXMLError $error */
        foreach ($xmlErrors as $error)
        {
            // http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors
            if ($error->code === 801)
            {
                continue;
            }

            @trigger_error($error->message, E_USER_WARNING);
        }

        libxml_clear_errors();

        $xpath = new \DOMXPath($DOMDocument);

        return $xpath->query($xpathQuery);
    }

    private static function normalizeHTML($html)
    {
        if (strpos($html, '') === false || strpos($html, '') === false)
        {
            return sprintf('%s', $html);
        }

        return $html;
    }
}

Fix typo in HTML normalization

Fix typo in HTML normalization


<?php

namespace Kunstmaan\UtilitiesBundle\Twig;

use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class UtilitiesTwigExtension extends AbstractExtension
{
    /**
     * @var SlugifierInterface
     */
    private $slugifier;

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

    /**
     * Returns a list of filters.
     *
     * @return array An array of filters
     */
    public function getFilters()
    {
        return [
            new TwigFilter('slugify', [$this, 'slugify']),
        ];
    }

    /**
     * @param string $text
     *
     * @return string
     */
    public function slugify($text)
    {
        return $this->slugifier->slugify($text);
    }
}

<?php

namespace Kunstmaan\UtilitiesBundle\Twig;

use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

/**
 * @final since 5.4
 */
class UtilitiesTwigExtension extends AbstractExtension
{
    /**
     * @var SlugifierInterface
     */
    private $slugifier;

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

    /**
     * Returns a list of filters.
     *
     * @return array An array of filters
     */
    public function getFilters()
    {
        return [
            new TwigFilter('slugify', [$this, 'slugify']),
        ];
    }

    /**
     * @param string $text
     *
     * @return string
     */
    public function slugify($text)
    {
        return $this->slugifier->slugify($text);
    }
}

Mark classes extending twig final

[AllBundles] Mark classes extending twig final