<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use Ds\Set;
use InvalidArgumentException;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;

class Renderer implements BlockRendererInterface, ConfigurationAwareInterface
{
    /**
     * @var Set
     */
    private $allowedClasses;

    public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
    {
        if (!$block instanceof Element) {
            throw new InvalidArgumentException('Incompatible block type: '.get_class($block));
        }

        $renderedChildren = $htmlRenderer->renderBlocks($block->children());

        if (!$this->allowedClasses->contains($block->getClass())) {
            return $renderedChildren;
        }

        $separator = $htmlRenderer->getOption('inner_separator', "\n");

        return new HtmlElement(
            'div',
            $block->getData('attributes', []),
            $separator.$renderedChildren.$separator,
        );
    }

    public function setConfiguration(ConfigurationInterface $configuration): void
    {
        $this->allowedClasses = new Set($configuration->get('style_block_allowed_classes'));
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use Ds\Set;
use InvalidArgumentException;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;

class Renderer implements BlockRendererInterface, ConfigurationAwareInterface
{
    /**
     * @var Set
     */
    private $allowedClasses;

    public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
    {
        if (!$block instanceof Element) {
            throw new InvalidArgumentException('Incompatible block type: '.get_class($block));
        }

        $renderedChildren = $htmlRenderer->renderBlocks($block->children());

        if (!$this->allowedClasses->contains($block->getClass())) {
            return $renderedChildren;
        }

        $separator = $htmlRenderer->getOption('inner_separator', "\n");

        return new HtmlElement(
            'div',
            $block->getData('attributes', []),
            $separator.$renderedChildren.$separator,
        );
    }

    public function setConfiguration(ConfigurationInterface $configuration): void
    {
        $this->allowedClasses = new Set($configuration->get('style_block_allowed_classes') ?? []);
    }
}

Fix fail when no StyleBlock classes are allowed


<?php

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

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

return [
    'up' => function (Builder $schema) {
        // Delete rows with non-existent entities so that we will be able to create
        // foreign keys without any issues.
        $schema->getConnection()
            ->table('post_likes')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id');
            })
            ->orWhereNotExists(function ($query) {
                $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id');
            })
            ->delete();

        $schema->table('post_likes', function (Blueprint $table) {
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('post_likes', function (Blueprint $table) {
            $table->dropForeign(['post_id', 'user_id']);
        });
    }
];

<?php

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

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

return [
    'up' => function (Builder $schema) {
        // Delete rows with non-existent entities so that we will be able to create
        // foreign keys without any issues.
        $schema->getConnection()
            ->table('post_likes')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id');
            })
            ->orWhereNotExists(function ($query) {
                $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id');
            })
            ->delete();

        $schema->table('post_likes', function (Blueprint $table) use ($schema) {
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('post_likes', function (Blueprint $table) use ($schema) {
            $table->dropForeign(['post_id', 'user_id']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


<?php
/*
 * This file is part of Handlebars.php Helpers Set
 *
 * (c) Dmitriy Simushev <simushevds@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JustBlackBird\HandlebarsHelpers\Comparison;

use Handlebars\Helper as HelperInterface;

/**
 * Conditional helper that checks if one value is between two another values.
 *
 * Borders of the interval are excluded from comparison. That's why in cases
 * where the value under comparision is equal to one of the borders the result of
 * "between" operator is false.
 *
 * Example of usage:
 * ```handlebars
 *   {{#ifBetween value leftBorder rightBorder}
 *     The first argument is between borders.
 *   {{else}}
 *     The first argument is not between the borders.
 *   {{/ifBetween}}
 * ```
 *
 * @author Dmitriy Simushev <simushevds@gmail.com>
 */
class IfBetweenHelper extends AbstractComparisonHelper implements HelperInterface
{
    /**
     * {@inheritdoc}
     */
    protected function evaluateCondition($args)
    {
        if (count($args) != 3) {
            throw new \InvalidArgumentException(
                '"ifBetween" helper expects exactly three arguments.'
            );
        }

        return ($args[0] > $args[1]) && ($args[0] < $args[2]);
    }
}

<?php
/*
 * This file is part of Handlebars.php Helpers Set
 *
 * (c) Dmitriy Simushev <simushevds@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JustBlackBird\HandlebarsHelpers\Comparison;

use Handlebars\Helper as HelperInterface;

/**
 * Conditional helper that checks if one value is between two another values.
 *
 * Borders of the interval are excluded from comparison. That's why in cases
 * where the value under comparision is equal to one of the borders the result
 * of "between" operator is false.
 *
 * Example of usage:
 * ```handlebars
 *   {{#ifBetween value leftBorder rightBorder}}
 *     The first argument is between borders.
 *   {{else}}
 *     The first argument is not between the borders.
 *   {{/ifBetween}}
 * ```
 *
 * @author Dmitriy Simushev <simushevds@gmail.com>
 */
class IfBetweenHelper extends AbstractComparisonHelper implements HelperInterface
{
    /**
     * {@inheritdoc}
     */
    protected function evaluateCondition($args)
    {
        if (count($args) != 3) {
            throw new \InvalidArgumentException(
                '"ifBetween" helper expects exactly three arguments.'
            );
        }

        return ($args[0] > $args[1]) && ($args[0] < $args[2]);
    }
}

Fix typo in ifBetween helper's docs

Fix typo in ifBetween helper's docs


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace Database\Factories\Forum;

use App\Models\Forum\PollOption;
use App\Models\Forum\Topic;
use Database\Factories\Factory;

class PollOptionFactory extends Factory
{
    protected $model = PollOption::class;

    public function definition(): array
    {
        return [
            'poll_option_text' => fn () => $this->faker->sentence(),
            'topic_id' => Topic::factory()->poll(0),
        ];
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace Database\Factories\Forum;

use App\Models\Forum\PollOption;
use Database\Factories\Factory;

class PollOptionFactory extends Factory
{
    protected $model = PollOption::class;

    public function definition(): array
    {
        return [
            'poll_option_text' => fn () => $this->faker->sentence(),
            'topic_id' => null,
        ];
    }
}

Use invalid PollOption topic_id in factory by default

Not useful to use this factory by itself


<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(function ($router) {
                 require base_path('routes/web.php');
             });
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(function ($router) {
                 require base_path('routes/api.php');
             });
    }
}

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

Use path for group directly

Use path for group directly


<?php

require dirname(__DIR__) . '/vendor/autoload.php';

// Create eventloop
$loop = \React\EventLoop\Factory::create();

// Create a socket
$socket = new \React\Socket\Server($loop);
$socket->listen(12345, '0.0.0.0');

// Bind to IP and port
$node = new \WyriHaximus\PhuninNode\Node($loop, $socket);

// Add plugins
$node->addPlugin(new \WyriHaximus\PhuninNode\Plugins\Plugins());
$node->addPlugin(new \WyriHaximus\PhuninNode\Plugins\PluginsCategories());
$node->addPlugin(new \WyriHaximus\PhuninNode\Plugins\MemoryUsage());
$node->addPlugin(new \WyriHaximus\PhuninNode\Plugins\Uptime());

// Get rolling
$loop->run();

<?php

use React\EventLoop\Factory;
use React\Socket\Server;
use WyriHaximus\PhuninNode\Node;
use WyriHaximus\PhuninNode\Plugins\MemoryUsage;
use WyriHaximus\PhuninNode\Plugins\Plugins;
use WyriHaximus\PhuninNode\Plugins\PluginsCategories;
use WyriHaximus\PhuninNode\Plugins\Uptime;

require dirname(__DIR__) . '/vendor/autoload.php';

// Create eventloop
$loop = Factory::create();

// Create a socket
$socket = new Server($loop);
$socket->listen(12345, '0.0.0.0');

// Bind to IP and port
$node = new Node($loop, $socket);

// Add plugins
$node->addPlugin(new Plugins());
$node->addPlugin(new PluginsCategories());
$node->addPlugin(new MemoryUsage());
$node->addPlugin(new Uptime());

// Get rolling
$loop->run();

Use use import so the code is easier on the eyes


<?php
/**
 * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\BackgroundJob;

class Job extends \Test\TestCase {
	private $run = false;

	protected function setUp() {
		parent::setUp();
		$this->run = false;
	}

	public function testRemoveAfterException() {
		$jobList = new DummyJobList();
		$job = new TestJob($this, function () {
			throw new \Exception();
		});
		$jobList->add($job);

		$this->assertCount(1, $jobList->getAll());
		$job->execute($jobList);
		$this->assertTrue($this->run);
		$this->assertCount(0, $jobList->getAll());
	}

	public function markRun() {
		$this->run = true;
	}
}

<?php
/**
 * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\BackgroundJob;

class Job extends \Test\TestCase {
	private $run = false;

	protected function setUp() {
		parent::setUp();
		$this->run = false;
	}

	public function testRemoveAfterException() {
		$jobList = new DummyJobList();
		$job = new TestJob($this, function () {
			throw new \Exception();
		});
		$jobList->add($job);

		$logger = $this->getMockBuilder('OCP\ILogger')
			->disableOriginalConstructor()
			->getMock();
		$logger->expects($this->once())
			->method('error')
			->with('Error while running background job: ');

		$this->assertCount(1, $jobList->getAll());
		$job->execute($jobList, $logger);
		$this->assertTrue($this->run);
		$this->assertCount(1, $jobList->getAll());
	}

	public function markRun() {
		$this->run = true;
	}
}

Fix the test to expect the new behaviour


Stocks Game

Home

Stocks

Portfolio

        <form method="POST" action="">
            <select>
              {playerList}
              <option value="{Player}">{Player}</option>
              {/playerList}
            </select>
            <input type="submit">
        </form>

Add header login drop down and button

Add header login drop down and button


<?php

/*
 * This file is part of the VinceCmsSonataAdmin bundle.
 *
 * (c) Vincent Chalamon <vincentchalamon@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Vince\Bundle\CmsSonataAdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Vince\Bundle\CmsBundle\Entity\Area;

/**
 * AreaType manage areas list for a specific template
 *
 * @author Vincent Chalamon <vincentchalamon@gmail.com>
 */
class AreaType extends AbstractType
{

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        foreach ($options['areas'] as $area) {
            /** @var Area $area */
            $builder->add($area->getName(), $area->getType(), array(
                    'label'    => $area->getTitle(),
                    'required' => $area->isRequired()
                )
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(array('areas'));
    }

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

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'form';
    }
}

<?php

/*
 * This file is part of the VinceCmsSonataAdmin bundle.
 *
 * (c) Vincent Chalamon <vincentchalamon@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Vince\Bundle\CmsSonataAdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Vince\Bundle\CmsBundle\Entity\Area;

/**
 * AreaType manage areas list for a specific template
 *
 * @author Vincent Chalamon <vincentchalamon@gmail.com>
 */
class AreaType extends AbstractType
{

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        foreach ($options['areas'] as $area) {
            /** @var Area $area */
            $fieldOptions = array(
                'label'    => $area->getTitle(),
                'required' => $area->isRequired()
            );
            if ($area->getType() == 'document') {
                $fieldOptions['string'] = true;
            }
            $builder->add($area->getName(), $area->getType(), $fieldOptions);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(array('areas'));
    }

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

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'form';
    }
}

Update for document form type

Update for document form type


<?php
namespace tests\SlackApi;

use SlackApi\Client;
use \tests\Fixtures\TestModule;

/**
 * Class AbstractModuleTest
 */
class ModuleTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @return string
     */
    protected function getRealToken()
    {
        return getenv('SLACK_TEST_TOKEN');
    }

    /**
     * @return string
     */
    protected function getFakeToken()
    {
        return 'fake-token';
    }

    /**
     * @return Client
     */
    protected function getClient()
    {
        return new Client($this->getRealToken());
    }

    /**
     *
     */
    public function testRequest()
    {
        $module = new TestModule('api', $this->getClient());

        $response = $module->request('test', ['argument' => 'value']);
        $this->assertInstanceOf('\SlackApi\Response', $response);
        $this->assertTrue($response->isSuccess());
    }

    /**
     *
     */
    public function testPredefinedRequest()
    {
        $module = new TestModule('api', $this->getClient());

        $response = $module->test();
        $this->assertInstanceOf('\SlackApi\Response', $response);
        $this->assertTrue($response->isSuccess());
    }
}

<?php
namespace tests\SlackApi;

use SlackApi\Client;
use SlackApi\Response;
use \tests\Fixtures\TestModule;

/**
 * Class AbstractModuleTest
 */
class ModuleTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @return string
     */
    protected function getRealToken()
    {
        return getenv('SLACK_TEST_TOKEN');
    }

    /**
     * @return string
     */
    protected function getFakeToken()
    {
        return 'fake-token';
    }

    /**
     * @return Client
     */
    protected function getClient()
    {
        return new Client($this->getRealToken());
    }

    /**
     *
     */
    public function testRequest()
    {
        $mock = $this->getMockBuilder(TestModule::class)
            ->setMethods(['request'])
            ->disableOriginalConstructor()
            ->getMock();
        $mock->expects($this->once())
            ->method('request')
            ->will($this->returnValue(new Response(['ok' => true])));
        /** @var TestModule $mock */
        $response = $mock->request('test');
        $this->assertInstanceOf('\SlackApi\Response', $response);
        $this->assertTrue($response->isSuccess());
    }
}

Update test: mock module request

Update test: mock module request


<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
        	'showScriptName' => false,
    	],
		'survey' => [
    		'class' => 'common\components\LimeSurvey',
    		'username' => 'admin',
    		'password' => 'Samsung_1',
    		'url' => 'http://elearning.usarb.md/dmc/limesurvey',
			'surveyId' => '429785',
		]
    ],
];

<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
        	'showScriptName' => false,
    	],
		'survey' => [
    		'class' => 'common\components\LimeSurvey',
    		'username' => 'admin',
    		'password' => 'Samsung_1',
    		'url' => 'http://elearning.usarb.md/dmc/limesurvey',
			'surveyId' => '429785',
		],
    	'settings' => [
    		'class' => 'pheme\settings\components\Settings',
    	],
    ],
	'modules' => [
		'settings' => [
			'class' => 'pheme\settings\Module',
		],
	],
];

Add config for phemellc/yii2-settings extension


<?php namespace Aedart\Scaffold\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Base Command
 *
 * The base command for all scaffold console commands
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
abstract class BaseCommand extends Command
{

    /**
     * The input
     *
     * @var InputInterface
     */
    protected $input;

    /**
     * The output
     *
     * @var OutputInterface
     */
    protected $output;

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = new SymfonyStyle($input, $output);

        return $this->runCommand();
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    abstract public function runCommand();
}

<?php namespace Aedart\Scaffold\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Base Command
 *
 * The base command for all scaffold console commands
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
abstract class BaseCommand extends Command
{

    /**
     * The input
     *
     * @var InputInterface
     */
    protected $input;

    /**
     * The output
     *
     * @var OutputInterface|SymfonyStyle
     */
    protected $output;

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = new SymfonyStyle($input, $output);

        return $this->runCommand();
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    abstract public function runCommand();
}

Change type to improve type hint

Change type to improve type hint


<?php

return [

    /*
     * This is your authorization key which you get from your profile.
     * @ http://www.larabug.com
     */
    'login_key' => env('LB_KEY', 'LB_KEY'),

    /*
     * This is your project key which you receive when creating a project
     * @ http://www.larabug.com/projects
     */
    'project_key' => env('LB_PROJECT_KEY', 'LB_PROJECT_KEY'),

    /*
     * Environments where LaraBug should report
     */
    'environments' => [
        'production'
    ],

    /*
     * How many lines to show near exception line.
     */
    'lines_count' => 12,

    /*
     * Set the sleep time between duplicate exceptions.
     */
    'sleep' => 5,

    /*
     * Define your path for your 500 errors.
     */
    'errorView' => 'errors.500', // Refers to views/errors/500.blade.php

    /*
     * List of exceptions to skip sending.
     */
    'except' => [
        'Symfony\Component\HttpKernel\Exception\NotFoundHttpException',
    ],

    /*
     * Filter out these variables before sending them to larabug
     */
    'blacklist' => [
        'password',
        'authorization'
    ],

    /**
     * Release git hash
     */
    'release' => trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
];

<?php

return [

    /*
     * This is your authorization key which you get from your profile.
     * @ http://www.larabug.com
     */
    'login_key' => env('LB_KEY', 'LB_KEY'),

    /*
     * This is your project key which you receive when creating a project
     * @ http://www.larabug.com/projects
     */
    'project_key' => env('LB_PROJECT_KEY', 'LB_PROJECT_KEY'),

    /*
     * Environments where LaraBug should report
     */
    'environments' => [
        'production'
    ],

    /*
     * How many lines to show near exception line.
     */
    'lines_count' => 12,

    /*
     * Set the sleep time between duplicate exceptions.
     */
    'sleep' => 5,

    /*
     * Define your path for your 500 errors.
     */
    'errorView' => 'errors.500', // Refers to views/errors/500.blade.php

    /*
     * List of exceptions to skip sending.
     */
    'except' => [
        'Symfony\Component\HttpKernel\Exception\NotFoundHttpException',
    ],

    /*
     * Filter out these variables before sending them to larabug
     */
    'blacklist' => [
        'password',
        'authorization'
    ],

    /**
     * Release git hash
     */
    // 'release' => trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
];

Comment release by default to fix fatal

Comment release by default to fix fatal


<?php
/**
 * Demo app with SAML auth
 */

if (isset($_GET['signin'])) {
	require("/vagrant/SP/lib/_autoload.php");
	$as = new SimpleSAML_Auth_Simple('default-sp');
	$as->requireAuth();
	if ($as->isAuthenticated()) {
		$saml_attributes = $as->getAttributes();
	}
}

?>

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="">
		<meta name="author" content="">

		<title>Signin Template for Bootstrap</title>

		<link href="styles/css/bootstrap.css" rel="stylesheet">
		<link href="styles/css/signin.css" rel="stylesheet">
	</head>

	<body>
		<div class="container">
			<form class="form-signin" method="GET" action="?">
				<input type="hidden" name="signin" value="" />
				<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
			</form>
		</div>
	</body>
</html>

<?php
/**
 * Demo app with SAML auth
 */

if (isset($_GET['signin'])) {
	require("/vagrant/SP/lib/_autoload.php");
	$as = new SimpleSAML_Auth_Simple('default-sp');
	$as->requireAuth();
	if ($as->isAuthenticated()) {
		$saml_attributes = $as->getAttributes();
	}
}

?>

<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="">
		<meta name="author" content="">

		<title>SSO Sign In Demo</title>

		<link href="styles/css/bootstrap.css" rel="stylesheet">
		<link href="styles/css/signin.css" rel="stylesheet">

			<?php if (!isset($saml_attributes)) { ?>
			<form class="form-signin" method="GET" action="?">
				<input type="hidden" name="signin" value="" />
				<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
			</form>
			<?php } else {
				$name = $saml_attributes['name'][0];
				print "
Welcome {$name}!
";
			} ?>

Add login support to demo app

Add login support to demo app


<?php
namespace Haystack\Tests\Functional;

use Haystack\HArray;

class HArrayMapTest extends \PHPUnit_Framework_TestCase
{
    /** @var HArray */
    private $arrList;
    /** @var HArray */
    private $arrDict;

    protected function setUp()
    {
        $this->arrList = new HArray(["apple", "bobble", "cobble", "dobble"]);
        $this->arrDict = new HArray(["a" => "apple", "b" => "bobble", "c" => "cobble", "d" => "dobble"]);
    }

    public function testArrayMap()
    {
        $capitalizeList = function ($word) {
            return strtoupper($word);
        };

        $newArrList = $this->arrList->map($capitalizeList);
        $this->assertEquals("APPLE", $newArrList[0]);
    }

}

<?php
namespace Haystack\Tests\Functional;

use Haystack\HArray;

class HArrayMapTest extends \PHPUnit_Framework_TestCase
{
    /** @var HArray */
    private $arrList;
    /** @var HArray */
    private $arrDict;

    protected function setUp()
    {
        $this->arrList = new HArray(["apple", "bobble", "cobble", "dobble"]);
        $this->arrDict = new HArray(["a" => "apple", "b" => "bobble", "c" => "cobble", "d" => "dobble"]);
    }

    public function testArrayMap()
    {
        $capitalizeList = function ($word) {
            return strtoupper($word);
        };

        $newArrList = $this->arrList->map($capitalizeList);
        $this->assertEquals("APPLE", $newArrList[0]);

        $newArrDict = $this->arrDict->map($capitalizeList);
        $this->assertEquals("APPLE", $newArrDict["a"]);
    }

}

Add test for mapping over a dict array

Add test for mapping over a dict array


<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap any application services.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register any application services.
	 *
	 * This service provider is a great spot to register your various container
	 * bindings with the application. As you can see, we are registering our
	 * "Registrar" implementation here. You can add your own bindings too!
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->bind(
			'Illuminate\Contracts\Auth\Registrar',
			'App\Services\Registrar'
		);
	}

}

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Handler\ErrorLogHandler;

class AppServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap any application services.
	 *
	 * @return void
	 */
	public function boot()
	{
		\Log::getMonoLog()->pushHandler(new ErrorLogHandler());
	}

	/**
	 * Register any application services.
	 *
	 * This service provider is a great spot to register your various container
	 * bindings with the application. As you can see, we are registering our
	 * "Registrar" implementation here. You can add your own bindings too!
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->bind(
			'Illuminate\Contracts\Auth\Registrar',
			'App\Services\Registrar'
		);
	}

}

Change default logging to STDOUT.

Change default logging to STDOUT.


<?php
use Cake\Core\Configure;

// CsvMigrations plugin configuration
return [
    'CsvMigrations' => [
        'api' => [
            'auth' => Configure::read('API.auth')
        ]
    ]
];

<?php
use Cake\Core\Configure;

// CsvMigrations plugin configuration
return [
    'CsvMigrations' => [
        'tableValidation' => false,
        'api' => [
            'auth' => Configure::read('API.auth')
        ]
    ]
];

Set table validation to false by default


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

passthru(
    './vendor/bin/phpcs --standard=PSR2 -n src tests *.php',
    $returnStatus
);
if ($returnStatus !== 0) {
    exit(1);
}

passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
    if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
        fputs(STDERR, "Code coverage was NOT 100%\n");
        exit(1);
    }
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

passthru(
    './vendor/bin/phpcs --standard=PSR2 -n src tests *.php',
    $returnStatus
);
if ($returnStatus !== 0) {
    exit(1);
}

passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
    if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
        fputs(STDERR, "Code coverage was NOT 100%\n");
        exit(1);
    }
}

echo "Code coverage was 100%\n";

Remove deprecated --dev flag for composer


<?php
declare(strict_types = 1);

namespace Apha\Saga;

use Apha\Domain\Identity;
use Apha\EventHandling\EventHandler;
use Apha\Message\Event;
use Apha\Message\Events;
use JMS\Serializer\Annotation as Serializer;

abstract class Saga implements EventHandler
{
    /**
     * @Serializer\Type("Apha\Domain\Identity")
     * @var Identity
     */
    private $identity;

    /**
     * @Serializer\Type("Apha\Saga\AssociationValues")
     * @var AssociationValues
     */
    protected $associationValues;

    /**
     * @param Identity $identity
     * @param AssociationValues $associationValues
     */
    public function __construct(Identity $identity, AssociationValues $associationValues)
    {
        $this->identity = $identity;
        $this->associationValues = $associationValues;
        $this->changes = new Events();
    }

    /**
     * @return Identity
     */
    final public function getId(): Identity
    {
        return $this->identity;
    }

    /**
     * @return AssociationValues
     */
    final public function getAssociationValues(): AssociationValues
    {
        return $this->associationValues;
    }

    /**
     * @param Event $event
     * @return void
     */
    abstract public function on(Event $event);

    /**
     * @return bool
     */
    abstract public function isActive(): bool;
}

<?php
declare(strict_types = 1);

namespace Apha\Saga;

use Apha\Domain\Identity;
use Apha\EventHandling\EventHandler;
use Apha\Message\Event;
use Apha\Message\Events;
use JMS\Serializer\Annotation as Serializer;

abstract class Saga implements EventHandler
{
    /**
     * @Serializer\Type("Apha\Domain\Identity")
     * @var Identity
     */
    private $identity;

    /**
     * @Serializer\Type("Apha\Saga\AssociationValues")
     * @var AssociationValues
     */
    protected $associationValues;

    /**
     * @param Identity $identity
     * @param AssociationValues $associationValues
     */
    public function __construct(Identity $identity, AssociationValues $associationValues)
    {
        $this->identity = $identity;
        $this->associationValues = $associationValues;
    }

    /**
     * @return Identity
     */
    final public function getId(): Identity
    {
        return $this->identity;
    }

    /**
     * @return AssociationValues
     */
    final public function getAssociationValues(): AssociationValues
    {
        return $this->associationValues;
    }

    /**
     * @param Event $event
     * @return void
     */
    abstract public function on(Event $event);

    /**
     * @return bool
     */
    abstract public function isActive(): bool;
}

Remove assignment of non-existing member.


<?php

namespace Hmaus\Reynaldo\Elements;

class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse
{
    public function getStatusCode()
    {
        return (int)$this->attributes['statusCode'];
    }

    public function getHeaders()
    {
        $headersFromAttributes = $this->getAttribute('headers');

        if (!$headersFromAttributes) {
            return [];
        }

        $headers = [];

        foreach ($headersFromAttributes['content'] as $header) {
            $headers[$header['content']['key']['content']] = $header['content']['value']['content'];
        }

        return $headers;
    }

    public function hasMessageBody()
    {
        return $this->getMessageBodyAsset() !== null;
    }

    public function getMessageBodyAsset()
    {
        return $this->getFirstAssetByClass('messageBody');
    }

    /**
     * @param $className
     * @return AssetElement|null
     */
    private function getFirstAssetByClass($className)
    {
        $assets = $this->getElementsByType(AssetElement::class);

        /** @var AssetElement $asset */
        foreach ($assets as $asset) {
            if ($asset->hasClass($className)) {
                return $asset;
            }
        }

        return null;
    }

    public function hasMessageBodySchema()
    {
        return $this->getMessageBodySchemaAsset() !== null;
    }

    public function getMessageBodySchemaAsset()
    {
        return $this->getFirstAssetByClass('messageBodySchema');
    }

    public function getDataStructure()
    {
        return $this->getFirstElementByType(DataStructureElement::class);
    }
}

<?php

namespace Hmaus\Reynaldo\Elements;

class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse
{
    public function getStatusCode()
    {
        return isset($this->attributes['statusCode']) ? (int)$this->attributes['statusCode'] : 0;
    }

    public function getHeaders()
    {
        $headersFromAttributes = $this->getAttribute('headers');

        if (!$headersFromAttributes) {
            return [];
        }

        $headers = [];

        foreach ($headersFromAttributes['content'] as $header) {
            $headers[$header['content']['key']['content']] = $header['content']['value']['content'];
        }

        return $headers;
    }

    public function hasMessageBody()
    {
        return $this->getMessageBodyAsset() !== null;
    }

    public function getMessageBodyAsset()
    {
        return $this->getFirstAssetByClass('messageBody');
    }

    /**
     * @param $className
     * @return AssetElement|null
     */
    private function getFirstAssetByClass($className)
    {
        $assets = $this->getElementsByType(AssetElement::class);

        /** @var AssetElement $asset */
        foreach ($assets as $asset) {
            if ($asset->hasClass($className)) {
                return $asset;
            }
        }

        return null;
    }

    public function hasMessageBodySchema()
    {
        return $this->getMessageBodySchemaAsset() !== null;
    }

    public function getMessageBodySchemaAsset()
    {
        return $this->getFirstAssetByClass('messageBodySchema');
    }

    public function getDataStructure()
    {
        return $this->getFirstElementByType(DataStructureElement::class);
    }
}

Fix NOTICE error on PHP 7.4: Trying to access array offset on value of type null


<?php

namespace Interop\Async\Loop;

/**
 * MUST be thrown if any operation (except cancel()) is attempted with an invalid watcher identifier. [Invalid watcher identifier: any identifier not yet emitted by the driver or cancelled by the user]
 */
class InvalidWatcherException extends \LogicException
{

}

<?php

namespace Interop\Async\Loop;

/**
 * MUST be thrown if any operation (except cancel()) is attempted with an invalid watcher identifier.
 * [Invalid watcher identifier: any identifier not yet emitted by the driver or cancelled by the user]
 */
class InvalidWatcherException extends \LogicException
{

}

Add line break to prevent overlong line

Add line break to prevent overlong line


<?php declare(strict_types=1);

namespace Psalm\Visitor;

use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;

/**
 * Visitor cloning all nodes and linking to the original nodes using an attribute.
 *
 * This visitor is required to perform format-preserving pretty prints.
 */
class CloningVisitor extends NodeVisitorAbstract
{
    public function enterNode(Node $origNode)
    {
        $node = clone $origNode;
        if ($c = $node->getDocComment()) {
            $node->setDocComment(clone $c);
        }
        return $node;
    }
}

<?php declare(strict_types=1);

namespace Psalm\Visitor;

use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;

/**
 * Visitor cloning all nodes and linking to the original nodes using an attribute.
 *
 * This visitor is required to perform format-preserving pretty prints.
 */
class CloningVisitor extends NodeVisitorAbstract
{
    public function enterNode(Node $origNode)
    {
        $node = clone $origNode;
        if ($cs = $node->getComments()) {
            $node->setAttribute(
                'comments',
                array_map(
                    /**
                     * @return \PhpParser\Comment
                     */
                    function (\PhpParser\Comment $c) {
                        return clone $c;
                    },
                    $cs
                )
            );
        }
        return $node;
    }
}

Clone all comments, not just docs

Clone all comments, not just docs


<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;

class ProjectName
{
    public const RC_FILE = '.laravelstatsrc';

    public function get(): ?string
    {
        if ($this->hasStoredProjectName()) {
            return File::get($this->pathToRcFile());
        }

        return null;
    }

    public function determineProjectNameFromGit(): ?string
    {
        $process = Process::fromShellCommandline('/usr/local/bin/git config --get remote.origin.url');
        $process->run();

        if ($process->isSuccessful() === false) {
            return null;
        }

        $remoteUrl = parse_url(trim($process->getOutput()));

        return Str::replaceFirst('/', '', $remoteUrl['path']);
    }

    protected function pathToRcFile(): string
    {
        return base_path(self::RC_FILE);
    }

    public function hasStoredProjectName(): bool
    {
        return File::exists($this->pathToRcFile());
    }

    public function storeNameInRcFile(string $projectName): void
    {
        File::put($this->pathToRcFile(), $projectName);
    }
}

<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;

class ProjectName
{
    public const RC_FILE = '.laravelstatsrc';

    public function get(): ?string
    {
        if ($this->hasStoredProjectName()) {
            return File::get($this->pathToRcFile());
        }

        return null;
    }

    public function determineProjectNameFromGit(): ?string
    {
        $process = Process::fromShellCommandline('/usr/local/bin/git config --get remote.origin.url');
        $process->run();

        if ($process->isSuccessful() === false) {
            return null;
        }

        $remoteUrl = parse_url(trim($process->getOutput()));

        $remoteUrl = Str::replaceLast('.git', '', $remoteUrl['path']);

        return Str::replaceFirst('/', '', $remoteUrl);
    }

    protected function pathToRcFile(): string
    {
        return base_path(self::RC_FILE);
    }

    public function hasStoredProjectName(): bool
    {
        return File::exists($this->pathToRcFile());
    }

    public function storeNameInRcFile(string $projectName): void
    {
        File::put($this->pathToRcFile(), $projectName);
    }
}

Remove ".git" from project names

Remove ".git" from project names


<?php

namespace Routelandia\Entities;

use Respect\Relational\Mapper;
use Routelandia\DB;

/**
 * Represents a single highway.
 *
 */
class Highway {
  public $highwayid;
  public $direction;
  public $highwayname;
  public $bound;

  // Hide some of the params that the client won't need.
  protected $highwaylength;
  protected $startmp;
  protected $endmp;

  /******************************************************************************
   * STATIC CLASS METHODS
   ******************************************************************************/

  /**
   * Returns all highways
   */
  public static function fetchAll() {
    return DB::instance()->highways->fetchAll();
  }

  /**
   * Returns the single requested highway
   */
  public static function fetch($id) {
    return DB::instance()->highways[$id]->fetch();
  }
}

<?php

namespace Routelandia\Entities;

use Respect\Relational\Mapper;
use Routelandia\DB;

/**
 * Represents a single highway.
 *
 */
class Highway {
  public $highwayid;
  public $direction;
  public $highwayname;
  public $bound;
  public $fullGeoJson;

  // Hide some of the params that the client won't need.
  protected $highwaylength;
  protected $startmp;
  protected $endmp;

  /**
   * Gets all the stations for this highway, and concatenates their JSON segments together
   * into a single giant JSON polyline, saving that into the $fullGeoJson field.
   */
  function buildBigLine() {
    $output = new \stdClass();
    $output->type = "Linestring";
    $output->coordinates = array();

    $ss = OrderedStation::fetchForHighway($this->highwayid);
    foreach($ss as $ts) {
      foreach($ts->geojson_raw->coordinates as $tc) {
        $output->coordinates[] = $tc;
      }
    }

    $this->fullGeoJson = $output;
  }

  /******************************************************************************
   * STATIC CLASS METHODS
   ******************************************************************************/

  /**
   * Returns all highways
   */
  public static function fetchAll() {
    return DB::instance()->highways->fetchAll();
  }

  /**
   * Returns the single requested highway
   */
  public static function fetch($id) {
    return DB::instance()->highways[$id]->fetch();
  }
}

Add buildBigLine() to create the whole highway JSON


<?php

/*
 * Plugin Name: Admin Color Schema
 * Plugin URI: https://github.com/hyyan/admin-color-schema/
 * Description: A wordpress plugin to enable wordpress themes to add its own admin color schema directly from theme
 * Author: Hyyan Abo Fakher
 * Version: 0.1
 * Author URI: https://github.com/hyyan
 * GitHub Plugin URI: hyyan/admin-color-schema
 * License: MIT License
 */

require_once __DIR__ . '/src/HyyanAdminColorSchema.php';

/**
 * Bootstrap the plugin
 */
new HyyanAdminColorSchema();

<?php

/*
 * Plugin Name: Admin Color Schema
 * Plugin URI: https://github.com/hyyan/admin-color-schema/
 * Description: A wordpress plugin to enable wordpress themes to add its own admin color schema directly from theme
 * Author: Hyyan Abo Fakher
 * Version: 0.1.1
 * Author URI: https://github.com/hyyan
 * GitHub Plugin URI: hyyan/admin-color-schema
 * License: MIT License
 */

require_once __DIR__ . '/src/HyyanAdminColorSchema.php';

/**
 * Bootstrap the plugin
 */
new HyyanAdminColorSchema();

Update the version number to 0.1.1

Update the version number to 0.1.1


<?php
/**
 * WP-CLI commands for Revision Strike.
 *
 * @package Revision Strike
 * @author Steve Grunwell
 */

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
	return;
}

/**
 * Remove revisions on old posts to clean up the database.
 */
class RevisionStrikeCLI extends WP_CLI {

	/**
	 * Remove old post revisions.
	 *
	 * ## EXAMPLES
	 *
	 *   wp revisionstrike clean
	 */
	public function clean( $args, $assoc_args ) {
		do_action( RevisionStrike::STRIKE_ACTION );
	}

}

WP_CLI::add_command( 'revisionstrike', 'RevisionStrikeCLI' );

<?php
/**
 * WP-CLI commands for Revision Strike.
 *
 * @package Revision Strike
 * @author Steve Grunwell
 */

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
	return;
}

/**
 * Remove revisions on old posts to clean up the database.
 */
class RevisionStrikeCLI extends WP_CLI {

	/**
	 * Remove old post revisions.
	 *
	 * ## EXAMPLES
	 *
	 *   wp revisionstrike clean
	 */
	public function clean( $args, $assoc_args ) {
		do_action( RevisionStrike::STRIKE_ACTION );
	}

}

WP_CLI::add_command( 'revision-strike', 'RevisionStrikeCLI' );

Use 'revision-strike', not 'revisionstrike' for the WP-CLI command


<?php

/*

Plugin Name: Castlegate IT WP Breadcrumb
Plugin URI: http://github.com/castlegateit/cgit-wp-breadcrumb
Description: Simple breadcrumb navigation for WordPress.
Version: 3.0
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: MIT

*/

add_action('plugins_loaded', function () {
    require_once __DIR__ . '/classes/autoload.php';
    require_once __DIR__ . '/functions.php';
});

<?php

/*

Plugin Name: Castlegate IT WP Breadcrumb
Plugin URI: http://github.com/castlegateit/cgit-wp-breadcrumb
Description: Simple breadcrumb navigation for WordPress.
Version: 3.1
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: MIT

*/

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

require_once __DIR__ . '/classes/autoload.php';
require_once __DIR__ . '/functions.php';

do_action('cgit_breadcrumb_loaded');

Switch to WP action for dependent plugins


<?php

require_once('../../../config.gen.inc.php');
require_once "MDB2.php";
require_once $install_path."lib/db.php";

$db = new db;

$stmtd =& $db->connection->prepare("DELETE FROM Buildings");
$stmtd->execute();

$filename = "buildings.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd);

$lines = explode("\r", $contents);
echo("Starting import of ".count($lines)." building records...");
foreach ($lines as $line) {
	$fields = explode("\t", $line);
	echo("\nImporting '".$fields[0]."'...");
	$types = array('text','text','text','text','text','text','text','integer','text','text','text','text','text');
	$stmt =& $db->connection->prepare("INSERT INTO Buildings (name,latitude,longitude,physical_address,type,subtype,code,parent,wifi,phone,website,hours,campus,uid) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",$types);
	$stmt->execute(array($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6], $fields[7], $fields[8], $fields[9], $fields[10],$fields[11],$fields[12],$fields[13]));
}
echo("\nCompleted importing building data...\n");

?>

<?php

require_once('../../../config.gen.inc.php');
require_once "MDB2.php";
require_once $install_path."lib/db.php";

$db = new db;

$stmtd =& $db->connection->prepare("DELETE FROM Buildings");
$stmtd->execute();

$filename = "buildings.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd);

$lines = explode("\n", $contents);
echo("Starting import of ".count($lines)." building records...");
foreach ($lines as $line) {
	$fields = explode("\t", $line);
	echo("\nImporting '".$fields[0]."'...");
	$types = array('text','text','text','text','text','text','text','integer','text','text','text','text','text');
	$stmt =& $db->connection->prepare("INSERT INTO Buildings (name,latitude,longitude,physical_address,type,subtype,code,parent,wifi,phone,website,hours,campus,uid) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",$types);
	$stmt->execute(array($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6], $fields[7], $fields[8], $fields[9], $fields[10],$fields[11],$fields[12],$fields[13]));
}
echo("\nCompleted importing building data...\n");

?>

Use newline instead of carriage return for import of buildings from XLS


<?php

use Maghead\Testing\CommandWorkFlowTestCase;

/**
 * @group command
 */
class SchemaCommandsTest extends CommandWorkFlowTestCase
{
    public function testSchemaBuildCommand()
    {
        $ret = $this->app->run(array('maghead','schema','build','-f'));
        $this->assertTrue($ret);
    }

    /**
     * @depends testSchemaBuildCommand
     */
    public function testSchemaListCommand()
    {
        $this->expectOutputRegex('/AuthorBooks\\\\Model\\\\AuthorSchema/');
        $this->app->run(array('maghead','schema','list'));
    }

    /**
     * @depends testSchemaListCommand
     */
    public function testSchemaStatusCommand()
    {
        // $this->expectOutputRegex('/up-to-date/');
        $ret = $this->app->run(array('maghead','schema','status'));
        $this->assertTrue($ret);
    }

    /**
     * @depends testSchemaListCommand
     */
    public function testSchemaCleanCommand()
    {
        $this->expectOutputRegex('/Cleaning schema/');
        $ret = $this->app->run(array('maghead','schema','clean'));
        $this->assertTrue($ret);
    }
}

<?php

use Maghead\Testing\CommandWorkFlowTestCase;

/**
 * @group command
 */
class SchemaCommandsTest extends CommandWorkFlowTestCase
{
    public function schemaBuildParameterDataProvider()
    {
        return [
            [['-f']],
            [['-f', 'src']],
            [['-f', 'tests/apps/AuthorBooks/Model/AddressSchema.php', 'tests/apps/AuthorBooks/Model/AuthorSchema.php']],
        ];
    }

    /**
     * @dataProvider schemaBuildParameterDataProvider
     */
    public function testSchemaBuildCommand($args)
    {
        $ret = $this->app->run(array_merge(['maghead','schema','build'], $args));
        $this->assertTrue($ret);
    }

    /**
     * @depends testSchemaBuildCommand
     */
    public function testSchemaListCommand()
    {
        $this->expectOutputRegex('/AuthorBooks\\\\Model\\\\AuthorSchema/');
        $this->app->run(array('maghead','schema','list'));
    }

    /**
     * @depends testSchemaListCommand
     */
    public function testSchemaStatusCommand()
    {
        $ret = $this->app->run(array('maghead','schema','status'));
        $this->assertTrue($ret);
    }

    /**
     * @depends testSchemaListCommand
     */
    public function testSchemaCleanCommand()
    {
        $this->expectOutputRegex('/Cleaning schema/');
        $ret = $this->app->run(array('maghead','schema','clean'));
        $this->assertTrue($ret);
    }
}

Add more test case for schema build commands


<?php
/**
 * Created by PhpStorm.
 * User: isselguberna
 * Date: 29/9/15
 * Time: 23:48
 */

namespace Nats\tests\Unit;

use Nats\ConnectionOptions;

/**
 * Class ConnectionOptionsTest
 */
class ConnectionOptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests Connection Options getters and setters. Only necessary for code coverage.
     *
     * @return void
     */
    public function testSettersAndGetters()
    {
        $options = new ConnectionOptions();
        $options
            ->setHost('host')
            ->setPort(4222)
            ->setUser('user')
            ->setPass('password')
            ->setLang('lang')
            ->setVersion('version')
            ->setVerbose(true)
            ->setPedantic(true)
            ->setReconnect(true);

        $this->assertEquals('host', $options->getHost());
        $this->assertEquals(4222, $options->getPort());
        $this->assertEquals('user', $options->getUser());
        $this->assertEquals('password', $options->getPass());
        $this->assertEquals('lang', $options->getLang());
        $this->assertEquals('version', $options->getVersion());
        $this->assertTrue($options->isVerbose());
        $this->assertTrue($options->isPedantic());
        $this->assertTrue($options->isReconnect());
    }
}

<?php
namespace Nats\tests\Unit;

use Nats\ConnectionOptions;

/**
 * Class ConnectionOptionsTest
 */
class ConnectionOptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests Connection Options getters and setters. Only necessary for code coverage.
     *
     * @return void
     */
    public function testSettersAndGetters()
    {
        $options = new ConnectionOptions();
        $options
            ->setHost('host')
            ->setPort(4222)
            ->setUser('user')
            ->setPass('password')
            ->setLang('lang')
            ->setVersion('version')
            ->setVerbose(true)
            ->setPedantic(true)
            ->setReconnect(true);

        $this->assertEquals('host', $options->getHost());
        $this->assertEquals(4222, $options->getPort());
        $this->assertEquals('user', $options->getUser());
        $this->assertEquals('password', $options->getPass());
        $this->assertEquals('lang', $options->getLang());
        $this->assertEquals('version', $options->getVersion());
        $this->assertTrue($options->isVerbose());
        $this->assertTrue($options->isPedantic());
        $this->assertTrue($options->isReconnect());
    }
}

Clean shitty phpstorm comment :(

Clean shitty phpstorm comment :(


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

class CreatePublicDashboardTestCase extends KWWebTestCase
{
  var $url = null;
  var $db  = null;

  function __construct()
   {
   parent::__construct();
   require('config.test.php');
   $this->url = $configure['urlwebsite'];
   $this->db  =& new database($db['type']);
   $this->db->setDb($db['name']);
   $this->db->setHost($db['host']);
   $this->db->setUser($db['login']);
   $this->db->setPassword($db['pwd']);
   }

  function testCreatePublicDashboard()
    {
    $content = $this->connect($this->url);
    if(!$content)
      {
      return;
      }

    $this->login();
    if(!$this->analyse($this->clickLink('[Create new project]')))
      {
      return;
      }

    $this->setField('name', 'PublicDashboard');
    $this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
    $this->setField('public', '1');
    $this->clickSubmitByName('Submit');

    $this->checkErrors();
    $this->assertText('The project PublicDashboard has been created successfully.');
    }
}

?>

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

class CreatePublicDashboardTestCase extends KWWebTestCase
{
  var $url = null;
  var $db  = null;

  function __construct()
   {
   parent::__construct();
   require('config.test.php');
   $this->url = $configure['urlwebsite'];
   $this->db  =& new database($db['type']);
   $this->db->setDb($db['name']);
   $this->db->setHost($db['host']);
   $this->db->setUser($db['login']);
   $this->db->setPassword($db['pwd']);
   }

  function testCreatePublicDashboard()
    {
    $content = $this->connect($this->url);
    if(!$content)
      {
      return;
      }

    $this->login();
    if(!$this->analyse($this->clickLink('[Create new project]')))
      {
      return;
      }

    $this->setField('name', 'PublicDashboard');
    $this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
    $this->setField('public', '1');
    $this->setField('emailAdministrator','1');
    $this->clickSubmitByName('Submit');

    $this->checkErrors();
    $this->assertText('The project PublicDashboard has been created successfully.');
    }
}

?>

ENH: Use emailadministrator in createpublicdashboard test


<?php

declare(strict_types=1);

namespace Ray\Di\Di;

/**
 * Annotates your class methods into which the Injector should inject values
 *
 * @Annotation
 * @Target("METHOD")
 */
final class Inject implements InjectInterface
{
    /**
     * If true, and the appropriate binding is not found, the Injector will skip injection of this method or field rather than produce an error.
     *
     * @var bool
     */
    public $optional = false;

    /**
     * {@inheritdoc}
     */
    public function isOptional(): bool
    {
        return $this->optional;
    }
}

<?php

declare(strict_types=1);

namespace Ray\Di\Di;

use Attribute;

/**
 * Annotates your class methods into which the Injector should inject values
 *
 * @Annotation
 * @Target("METHOD")
 */
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PARAMETER)]
final class Inject implements InjectInterface
{
    /**
     * If true, and the appropriate binding is not found, the Injector will skip injection of this method or field rather than produce an error.
     *
     * @var bool
     */
    public $optional = false;

    /**
     * {@inheritdoc}
     */
    public function isOptional(): bool
    {
        return $this->optional;
    }

    public function __construct(array $value = [], bool $optional = false)
    {
        $this->optional = $value['optional'] ?? $optional;
    }
}

Enable to annote to parameter

Enable to annote to parameter


<?php

namespace Craft;

class IncrementPlugin extends BasePlugin
{
    public function getName()
    {
        return Craft::t('Increment');
    }

    public function getVersion()
    {
        return '0.2';
    }

    public function getDeveloper()
    {
        return 'Bob Olde Hampsink';
    }

    public function getDeveloperUrl()
    {
        return 'http://www.itmundi.nl';
    }

    public function init()
    {
        // check increment fields to make sure no duplicate values are inserted
        craft()->on('entries.beforeSaveEntry', function (Event $event) {
            $isNewEntry = $event->params['isNewEntry'];
            $entry = $event->params['entry'];

            // exisiting entries don't change, so no need to check
            if ($isNewEntry) {
                $fields = $entry->getFieldLayout()->getFields();
                foreach ($fields as $field) {
                    if ($field->getField()->type == 'Increment') {
                        $handle = $field->getField()->handle;
                        $max = craft()->db->createCommand()->select('MAX(`field_'.$handle.'`)')->from('content')->queryScalar();
                        $currentValue = $entry[$handle];

                        // current value should by higher than max, otherwise a duplicate entry could be created
                        if ($currentValue <= $max) {
                            $entry->setContentFromPost(array($handle => $max + 1));
                        }
                    }
                }
            }
        });
    }
}

<?php

namespace Craft;

class IncrementPlugin extends BasePlugin
{
    public function getName()
    {
        return Craft::t('Increment');
    }

    public function getVersion()
    {
        return '0.2';
    }

    public function getDeveloper()
    {
        return 'Bob Olde Hampsink';
    }

    public function getDeveloperUrl()
    {
        return 'http://www.itmundi.nl';
    }

    public function init()
    {
        // Check increment fields to make sure no duplicate values are inserted
        craft()->on('elements.beforeSaveElement', function (Event $event) {

            // Check if this is a new element
            $isNewElement = $event->params['isNewElement'];

            // Get element
            $element = $event->params['element'];

            // Exisiting elements don't change, so no need to check
            if ($isNewElement) {

                // Get element fields
                $fields = $element->getFieldLayout()->getFields();

                // Loop through element fields
                foreach ($fields as $field) {

                    // Get field model
                    $field = $field->getField();

                    // Check if this field is an Increment field
                    if ($field->type == $this->getClassHandle()) {

                        // Re-calculate max value
                        $max = craft()->db->createCommand()->select('MAX(`field_'.$field->handle.'`)')->from('content')->queryScalar();

                        // Get current value
                        $currentValue = $element->{$field->handle};

                        // Current value should by higher than max, otherwise a duplicate element could be created
                        if ($currentValue <= $max) {
                            $element->setContentFromPost(array($field->handle => ($max + 1)));
                        }
                    }
                }
            }
        });
    }
}

Check for duplicates on saving of each element, instead of entry only


<?php
/* ====================
[BEGIN_COT_EXT]
Hooks=news.loop
Tags=news.tpl:{PAGE_ROW_COMMENTS}
[END_COT_EXT]
==================== */

/**
 * Comments system for Cotonti
 *
 * @package comments
 * @version 0.7.0
 * @author Cotonti Team
 * @copyright Copyright (c) Cotonti Team 2008-2011
 * @license BSD
 */

defined('COT_CODE') or die('Wrong URL');

require_once cot_incfile('comments', 'plug');

$page_urlp = empty($pag['page_alias']) ? 'id='.$pag['page_id'] : 'al='.$pag['page_alias'];
$news->assign(array(
	'PAGE_ROW_COMMENTS' => cot_comments_link('page', $page_urlp, 'page', $pag['page_id'], $pag['page_cat']),
	'PAGE_ROW_COMMENTS_COUNT' => cot_comments_count('page', $pag['page_id'])
));

?>

<?php
/* ====================
[BEGIN_COT_EXT]
Hooks=news.loop
Tags=news.tpl:{PAGE_ROW_COMMENTS}
[END_COT_EXT]
==================== */

/**
 * Comments system for Cotonti
 *
 * @package comments
 * @version 0.7.0
 * @author Cotonti Team
 * @copyright Copyright (c) Cotonti Team 2008-2011
 * @license BSD
 */

defined('COT_CODE') or die('Wrong URL');

require_once cot_incfile('comments', 'plug');

$page_urlp = empty($pag['page_alias']) ? 'c='.$pag['page_cat'].'&id='.$pag['page_id'] : 'c='.$pag['page_cat'].'&al='.$pag['page_alias'];
$news->assign(array(
	'PAGE_ROW_COMMENTS' => cot_comments_link('page', $page_urlp, 'page', $pag['page_id'], $pag['page_cat']),
	'PAGE_ROW_COMMENTS_COUNT' => cot_comments_count('page', $pag['page_id'])
));

?>

Fix for page links in comments

Fix for page links in comments


<?php
namespace Uphp\web;

use \UPhp\ActionDispach\Routes as Route;
use \UPhp\ActionController\ActionController;

class Application
{
    public function __construct()
    {
        set_exception_handler("src\uphpExceptionHandler");
        set_error_handler("src\uphpErrorHandler");
    }

    public function start($config)
    {
       //carregando os initializers
        $this->getInitializersFiles();
        $this->getRoutes();
        ActionController::callController($config);
    }

    private function getInitializersFiles()
    {
        $path = "config/initializers/";
        $directory = dir($path);
        while ($file = $directory -> read()) {
            if ($file != "." && $file != "..") {
                require($path . $file);
            }
        }
        $directory->close();
    }

    private function getRoutes()
    {
        return require("config/routes.php");
    }
}

Add call controller in method start app

Add call controller in method start app


<?php

namespace Symfony\Upgrade\Fixer;

use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

class FormGetnameToGetblockprefixFixer extends FormTypeFixer
{
    /**
     * @inheritdoc
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        if ($this->isFormType($tokens) && null !== $this->matchGetNameMethod($tokens)) {
            $this->fixGetNameMethod($tokens);
        }

        return $tokens->generateCode();
    }

    private function matchGetNameMethod(Tokens $tokens)
    {
        return $tokens->findSequence([
            [T_PUBLIC, 'public'],
            [T_FUNCTION],
            [T_STRING, 'getName'],
            '(',
            ')'
        ]);
    }

    private function fixGetNameMethod(Tokens $tokens)
    {
        $matchedTokens = $this->matchGetNameMethod($tokens);
        $matchedIndexes = array_keys($matchedTokens);
        $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3];
        $matchedTokens[$matchedIndex]->setContent('getBlockPrefix');
    }

    /**
     * @inheritdoc
     */
    public function getDescription()
    {
        return 'The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.';
    }
}

<?php

namespace Symfony\Upgrade\Fixer;

use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

class FormGetnameToGetblockprefixFixer extends FormTypeFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        if ($this->isFormType($tokens)) {
            $this->fixGetNameMethod($tokens);
        }

        return $tokens->generateCode();
    }

    private function matchGetNameMethod(Tokens $tokens)
    {
        return $tokens->findSequence([
            [T_PUBLIC, 'public'],
            [T_FUNCTION],
            [T_STRING, 'getName'],
            '(',
            ')'
        ]);
    }

    private function fixGetNameMethod(Tokens $tokens)
    {
        $matchedTokens = $this->matchGetNameMethod($tokens);
        if (null === $matchedTokens) {
            return;
        }

        $matchedIndexes = array_keys($matchedTokens);
        $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3];
        $matchedTokens[$matchedIndex]->setContent('getBlockPrefix');
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.';
    }
}

Move tokens null check to method.

Move tokens null check to method.


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Use phpcs as a library.

Use phpcs as a library.


<div role="filemanager-modal" class="modal" tabindex="-1"
     data-frame-id="<?= $frameId ?>"
     data-frame-src="<?= $frameSrc ?>"
     data-btn-id="<?= $btnId ?>"
     data-input-id="<?= $inputId ?>"
     data-image-container="<?= is_set($imageContainer) ? $imageContainer : '' ?>"
     data-paste-data="<?= is_set($pasteData) ? $pasteData : '' ?>"
     data-thumb="<?= $thumb ?>">

<div role="filemanager-modal" class="modal" tabindex="-1"
     data-frame-id="<?= $frameId ?>"
     data-frame-src="<?= $frameSrc ?>"
     data-btn-id="<?= $btnId ?>"
     data-input-id="<?= $inputId ?>"
     data-image-container="<?= $imageContainer ?>"
     data-paste-data="<?= $pasteData ?>"
     data-thumb="<?= $thumb ?>">

Revert "Fixed Modal view bug"

Revert "Fixed Modal view bug"

This reverts commit ce3917c8b04123e60eba2e02528cf1f8c4a8e0df.


<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * A factory for Travel.
 *
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Travel>
 */
class TravelFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string,string|int|\DateTime>
     */
    public function definition()
    {
        return [
            'name' => $this->faker->word(),
            'primary_contact_user_id' => User::all()->random()->id,
            'destination' => $this->faker->word(),
            'departure_date' => $this->faker->dateTimeBetween('now', '1 year'),
            'return_date' => $this->faker->dateTimeBetween('now', '1 year'),
            'fee_amount' => (string) $this->faker->randomFloat(2, 0, 1000),
            'included_with_fee' => $this->faker->paragraph(),
        ];
    }
}

<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * A factory for Travel.
 *
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Travel>
 */
class TravelFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string,string|int|\DateTime>
     */
    public function definition()
    {
        return [
            'name' => $this->faker->word(),
            'primary_contact_user_id' => User::all()->random()->id,
            'destination' => $this->faker->word(),
            'departure_date' => $this->faker->dateTimeBetween('now', '1 week'),
            'return_date' => $this->faker->dateTimeBetween('1 week', '2 weeks'),
            'fee_amount' => (string) $this->faker->randomFloat(2, 0, 1000),
            'included_with_fee' => $this->faker->paragraph(),
        ];
    }
}

Update travel factory to ensure return date is after departure date


<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
	$path = $configuration->getRootPath();
	$relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path)?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath)?>

<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
    $path = $configuration->getRootPath();
    $relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path, array('placeholder' => t('Example: %s', $_SERVER['DOCUMENT_ROOT'])))?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath, array('placeholder' => t('Example: %s', '/some/path')))?>

Add examples for file storage location

Add examples for file storage location


<?php

/**
 * This file is part of the Tarantool Client 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.
 */

declare(strict_types=1);

namespace Tarantool\Client\Tests\Unit;

use PHPUnit\Framework\TestCase;
use Tarantool\Client\Response;

final class ResponseTest extends TestCase
{
    public function testHasBodyKeyReturnsTrue() : void
    {
        $response = new Response([], [42 => null]);

        self::assertTrue($response->hasBodyField(42));
    }

    public function testHasBodyKeyReturnsFalse() : void
    {
        $response = new Response([], [24 => null]);

        self::assertFalse($response->hasBodyField(42));
    }
}

<?php

/**
 * This file is part of the Tarantool Client 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.
 */

declare(strict_types=1);

namespace Tarantool\Client\Tests\Unit;

use PHPUnit\Framework\TestCase;
use Tarantool\Client\Keys;
use Tarantool\Client\Response;

final class ResponseTest extends TestCase
{
    public function testGetSchemaIdReturnsCorrectId() : void
    {
        $schemaId = 42;
        $response = new Response([Keys::SCHEMA_ID => $schemaId], []);

        self::assertSame($schemaId, $response->getSchemaId());
    }

    public function testHasBodyKeyReturnsTrue() : void
    {
        $response = new Response([], [42 => null]);

        self::assertTrue($response->hasBodyField(42));
    }

    public function testHasBodyKeyReturnsFalse() : void
    {
        $response = new Response([], [24 => null]);

        self::assertFalse($response->hasBodyField(42));
    }
}

Add a unit test for Respose::getSchemaId()


<?php

namespace Bauhaus\Http;

class ResponseTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function createReponseWithStatusCode200IfItWasNotInformed()
    {
        $response = new Response();

        $this->assertEquals(200, $response->getStatusCode());
    }

    /**
     * @test
     */
    public function createNewResponseWithTheDesiredStatusCode()
    {
        $response = new Response();

        $newResponse = $response->withStatus(202);

        $this->assertNotSame($response, $newResponse);
        $this->assertEquals(202, $newResponse->getStatusCode());
    }
}

<?php

namespace Bauhaus\Http;

class ResponseTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function responseIsCreatedWithTheStatusCode200ByDefault()
    {
        $response = new Response();

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('OK', $response->getReasonPhrase());
    }

    /**
     * @test
     */
    public function createNewResponseGivenAStatusCodeAndExpectingTheRecommendedReasonPhrase()
    {
        $response = new Response();

        $newResponse = $response->withStatus(202);

        $this->assertNotSame($response, $newResponse);
        $this->assertEquals(202, $newResponse->getStatusCode());
        $this->assertEquals('Accepted', $newResponse->getReasonPhrase());
    }

    /**
     * @test
     */
    public function createNewResponseGivenAStatusCodeAndAReasonPhrase()
    {
        $response = new Response();

        $newResponse = $response->withStatus(202, 'Processing request');

        $this->assertNotSame($response, $newResponse);
        $this->assertEquals(202, $newResponse->getStatusCode());
        $this->assertEquals('Processing request', $newResponse->getReasonPhrase());
    }
}

Cover with tests all behaviors of Response


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / Include / Class
 */

namespace PH7;

class DbTableName
{
    const ADMIN = 'admins';
    const MEMBER = 'members';
    const MEMBERSHIP = 'memberships';
    const AFFILIATE = 'affiliates';
    const SUBSCRIBER = 'subscribers';
    const MEMBER_INFO = 'members_info';
    const AFFILIATE_INFO = 'affiliates_info';
    const MEMBER_PRIVACY = 'members_privacy';
    const MEMBER_NOTIFICATION = 'members_notifications';
    const BLOCK_IP = 'block_ip';
    const AD = 'ads';
    const AD_AFFILIATE = 'ads_affiliates';
    const ALBUM_PICTURE = 'albums_pictures';
    const ALBUM_VIDEO = 'albums_videos';

    const USER_TABLES = [
        self::ADMIN,
        self::MEMBER,
        self::AFFILIATE
    ];
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / Include / Class
 */

namespace PH7;

class DbTableName
{
    const ADMIN = 'admins';
    const MEMBER = 'members';
    const MEMBERSHIP = 'memberships';
    const AFFILIATE = 'affiliates';
    const SUBSCRIBER = 'subscribers';
    const MEMBER_INFO = 'members_info';
    const AFFILIATE_INFO = 'affiliates_info';
    const MEMBER_PRIVACY = 'members_privacy';
    const MEMBER_NOTIFICATION = 'members_notifications';
    const BLOCK_IP = 'block_ip';
    const AD = 'ads';
    const AD_AFFILIATE = 'ads_affiliates';
    const PICTURE = 'pictures';
    const VIDEO = 'videos';
    const ALBUM_PICTURE = 'albums_pictures';
    const ALBUM_VIDEO = 'albums_videos';

    const USER_TABLES = [
        self::ADMIN,
        self::MEMBER,
        self::AFFILIATE
    ];
}

Add "pictures" and "videos" tables

Add "pictures" and "videos" tables


<?php
$DIR_BASE_CORE = dirname(__DIR__);
define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackages();
}
$app->setupDefaultCommands();
$app->run();

<?php
$DIR_BASE_CORE = dirname(__DIR__);
define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackages();
}
$app->setupDefaultCommands();

\Events::dispatch('on_before_console_run');

$app->run();

\Events::dispatch('on_after_console_run');

Add events to the console dispatcher

Feature: Add events to the console dispatcher


<?php

namespace Oro\Bundle\UserBundle\Tests\Unit\Provider;

use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider;

class CategoryProviderTest extends \PHPUnit_Framework_TestCase
{
    /** @var RolePrivilegeCategoryProvider */
    private $categoryProvider;

    protected function setUp()
    {
        $this->categoryProvider = new RolePrivilegeCategoryProvider();
    }

    public function testCategoryListFetchSuccess()
    {
        $this->assertEquals(
            [
                'account_management' => [
                    'label' => 'Account Management',
                    'tab' => true
                ],
                'marketing' => [
                    'label' => 'Marketing',
                    'tab' => true
                ],
                'sales_data' => [
                    'label' => 'Sales Data',
                    'tab' => true
                ],
                'address' => [
                    'label' => 'Address',
                    'tab' => false
                ],
                'calendar' => [
                    'label' => 'Calendar',
                    'tab' => false
                ]
            ],
            $this->categoryProvider->getPermissionCategories()
        );
    }
}

<?php

namespace Oro\Bundle\UserBundle\Tests\Unit\Provider;

use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider;

class CategoryProviderTest extends \PHPUnit_Framework_TestCase
{
    /** @var RolePrivilegeCategoryProvider */
    private $categoryProvider;

    protected function setUp()
    {
        $this->categoryProvider = new RolePrivilegeCategoryProvider();
    }

    public function testCategoryListFetchSuccess()
    {
        $this->markTestIncomplete(
            'This test have to be rewritten because of interface changes'
        );
        $this->assertEquals(
            [
                'account_management' => [
                    'label' => 'Account Management',
                    'tab' => true
                ],
                'marketing' => [
                    'label' => 'Marketing',
                    'tab' => true
                ],
                'sales_data' => [
                    'label' => 'Sales Data',
                    'tab' => true
                ],
                'address' => [
                    'label' => 'Address',
                    'tab' => false
                ],
                'calendar' => [
                    'label' => 'Calendar',
                    'tab' => false
                ]
            ],
            $this->categoryProvider->getPermissionCategories()
        );
    }
}

BAP-10749: Develop data-collection provider for Permissions and Capabilities
- Mark unit tests as incomplete, because it's requre additional work


<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM;

use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Component\Core\Repository\ChannelPricingRepositoryInterface;

class ChannelPricingRepository extends EntityRepository implements ChannelPricingRepositoryInterface
{
    public function findWithDiscountedPrice(): array
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.originalPrice IS NOT NULL')
            ->getQuery()
            ->getResult()
        ;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM;

use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Component\Core\Repository\ChannelPricingRepositoryInterface;

class ChannelPricingRepository extends EntityRepository implements ChannelPricingRepositoryInterface
{
    public function findWithDiscountedPrice(): array
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.originalPrice IS NOT NULL')
            ->andWhere('o.originalPrice > o.price')
            ->getQuery()
            ->getResult()
        ;
    }
}

[ChannelPricing] Improve query for finding discounted pricings


<?php
namespace LBChat\Command\Chat;

use LBChat\ChatClient;
use LBChat\ChatServer;
use LBChat\Misc\ServerChatClient;

class SendCommand extends Command implements IChatCommand {
	protected $message;

	public function __construct(ChatServer $server, ChatClient $client, $message) {
		parent::__construct($server, $client);
		$this->message = $message;
	}

	public function execute() {
		ServerChatClient::sendMessage(true, null, $this->message);
	}

	public static function init(ChatServer $server, ChatClient $client, $rest) {
		return new SendCommand($server, $client, $rest);
	}

}

<?php
namespace LBChat\Command\Chat;

use LBChat\ChatClient;
use LBChat\ChatServer;
use LBChat\Command\ChatCommandFactory;
use LBChat\Command\Client\ChatCommand;
use LBChat\Misc\ServerChatClient;

class SendCommand extends Command implements IChatCommand {
	protected $message;

	public function __construct(ChatServer $server, ChatClient $client, $message) {
		parent::__construct($server, $client);
		$this->message = $message;
	}

	public function execute() {
		//Try to create a command from the server
		$client = ServerChatClient::getClient();

		//If we can find a chat command (/something) then we should use that instead of the default
		// chat command behavior.
		$command = ChatCommandFactory::construct($this->server, $client, $this->message);
		if ($command === null) {
			$command = new ChatCommand($this->server, $client, null, $this->message);
		}

		$command->execute();
	}

	public static function init(ChatServer $server, ChatClient $client, $rest) {
		return new SendCommand($server, $client, $rest);
	}

}

Make /send actually send chat commands (so you can mute people as the server and stuff)


            Moderadores

            Lectores QR

            Reportes

            Escritorio

            Reservas

            Ver Documentación

            Copyright (c) 2016 Trivial Box.

            Bugs y sugerencias en GitHub.

Add horizontal rule to footer

Add horizontal rule to footer


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use App\Copyable;
use App\SharedCopyableLogic;
use App\FormattingHelpers;

class TorrentEntry extends Model implements Copyable
{
    use SharedCopyableLogic;
    use FormattingHelpers;

    protected $guarded = [];

    protected $casts = [
        'was_copied' => 'boolean',
    ];

    protected $diskName = 'torrents';

    public function formattedEta()
    {
        if ($this->isStillDownloading()) {
            return intval($this->eta / 60) . 'min';
        }
        return 'Done';
    }

    public function isStillDownloading()
    {
        return $this->eta >= 0;
    }

    public function wasAlreadyCopied()
    {
        return $this->was_copied;
    }

    public function isFile()
    {
        return File::isFile($this->path);
    }

    public function isDirectory()
    {
        return ! $this->isFile();
    }

    public function getBasename()
    {
        return File::basename($this->path);
    }

    public function getFullPath()
    {
        return $this->path;
    }

    public function getPath()
    {
        return $this->getBasename();
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use App\Copyable;
use App\SharedCopyableLogic;
use App\FormattingHelpers;

class TorrentEntry extends Model implements Copyable
{
    use SharedCopyableLogic;
    use FormattingHelpers;

    protected $guarded = [];

    protected $casts = [
        'was_copied' => 'boolean',
    ];

    protected $diskName = 'torrents';

    public function formattedEta()
    {
        if ($this->isComplete()) {
            return 'Done';
        }

        $mins = intval($this->eta / 60);
        if ($mins < 60) {
            return $mins . 'min';
        }

        $hours = intval($mins / 60);
        $mins = $mins % 60;
        return "{$hours}hr {$mins}mins";
    }

    public function isStillDownloading()
    {
        return $this->percent < 1.0;
    }

    public function isComplete()
    {
        return ! $this->isStillDownloading();
    }

    public function wasAlreadyCopied()
    {
        return $this->was_copied;
    }

    public function isFile()
    {
        return File::isFile($this->path);
    }

    public function isDirectory()
    {
        return ! $this->isFile();
    }

    public function getBasename()
    {
        return File::basename($this->path);
    }

    public function getFullPath()
    {
        return $this->path;
    }

    public function getPath()
    {
        return $this->getBasename();
    }
}

Fix ETA display and possibly better checking of completed status


<?php
namespace AppBundle\Form;

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

/**
 * Asset form
 *
 * note: title is hidden (filled from the controller based on AssetTypeTitle form)
 */
class AssetType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', 'hidden') //use the AssetTypeTile to display the title
        ->add('value', 'number', [
            'grouping' => true,
            'precision' => 2,
            'invalid_message' => 'asset.value.type'
        ])
            ->add('description', 'textarea')
            ->add('valuationDate', 'date',[ 'widget' => 'text',
                'input' => 'datetime',
                'format' => 'dd-MM-yyyy',
                'invalid_message' => 'Enter a valid date'
            ])
            ->add('id', 'hidden')
            ->add('save', 'submit');
    }

    public function getName()
    {
        return 'asset';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults( [
            'translation_domain' => 'report-assets',
        ]);
    }
}

Fix formatting broken by phpstorm

Fix formatting broken by phpstorm


<?php

if (PHP_SAPI !== 'cli') {
    die('Command line access only' . PHP_EOL);
}

if (!isset($argv[1])) {
    die("Please supply a method to call, like so: php janus_client.php getMetadata https://example.edu" . PHP_EOL);
}

require './../library/EngineBlock/ApplicationSingleton.php';

$application = EngineBlock_ApplicationSingleton::getInstance();
$application->bootstrap();

$config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->serviceRegistry;
$restClient = new Janus_Rest_Client($config->location, $config->user, $config->user_secret);

$client = new Janus_Client();
$client->setRestClient($restClient);
$methodName = $argv[1];
$arguments = array_slice($argv, 2);
$result = call_user_func_array(array($client, $methodName), $arguments);

var_dump($restClient->getHttpClient()->getLastRequest());
var_dump($restClient->getHttpClient()->getLastResponse()->getHeadersAsString());
var_dump($restClient->getHttpClient()->getLastResponse()->getBody());
var_dump($result);

<?php

if (PHP_SAPI !== 'cli') {
    die('Command line access only' . PHP_EOL);
}

if (!isset($argv[1])) {
    die("Please supply a method to call, like so: php janus_client.php getMetadata https://example.edu" . PHP_EOL);
}
try {
require './../library/EngineBlock/ApplicationSingleton.php';

$application = EngineBlock_ApplicationSingleton::getInstance();
$application->bootstrap();

$config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->serviceRegistry;
$restClient = new Janus_Rest_Client($config->location, $config->user, $config->user_secret);

$client = new Janus_Client();
$client->setRestClient($restClient);
$methodName = $argv[1];
$arguments = array_slice($argv, 2);
$result = call_user_func_array(array($client, $methodName), $arguments);

var_dump($restClient->getHttpClient()->getLastRequest());
var_dump($restClient->getHttpClient()->getLastResponse()->getHeadersAsString());
var_dump($restClient->getHttpClient()->getLastResponse()->getBody());
var_dump($result);
} catch(Exception $e) {
  var_dump($e);
}

Use custom exception handling for test JANUS client


<?php
	namespace Bolt;

	class Handler
	{
		public static function error($level, $message, $file, $line, $context)
		{
			throw new Exceptions\Error($message, 0, $level, $file, $line);
		}

		public static function exception($exception)
		{
			$response = new Api\Response();
			$className = get_class($exception);

			if (DEPLOYMENT == "production")
			{
				$data = $className;
			}
			else
			{
				$data = array(
					"type" => $className,
					"message" => $exception->getMessage(),
					"code" => $exception->getCode(),
					"line" => $exception->getLine(),
					"file" => $exception->getFile(),
					"trace" => $exception->getTrace()
				);
			}

			$response->status(500, $data);
		}
	}
?>

<?php
	namespace Bolt;

	class Handler
	{
		public static function error($level, $message, $file, $line, $context)
		{
			throw new Exceptions\Error($message, 0, $level, $file, $line);
		}

		public static function exception($exception)
		{
			$response = new Api\Response();
			$className = get_class($exception);

			error_log($exception->getMessage());

			if (DEPLOYMENT == "production")
			{
				$data = $className;
			}
			else
			{
				$data = array(
					"type" => $className,
					"message" => $exception->getMessage(),
					"code" => $exception->getCode(),
					"line" => $exception->getLine(),
					"file" => $exception->getFile(),
					"trace" => $exception->getTrace()
				);
			}

			$response->status(500, $data);
		}
	}
?>

Add basic system error logging to exception handler