<?php

namespace Nails\Cron\Admin\Dashboard\Alert;

use Nails\Admin\Interfaces\Dashboard\Alert;
use Nails\Cron\Constants;
use Nails\Cron\Event\Listener;
use Nails\Factory;

/**
 * Class NotRunning
 *
 * @package Nails\Cron\Admin\Dashboard\Alert
 */
class NotRunning implements Alert
{
    const TIMEOUT = 90;

    // --------------------------------------------------------------------------

    /**
     * @inheritDoc
     */
    public function getTitle(): ?string
    {
        return 'Cron is not running';
    }

    // --------------------------------------------------------------------------

    /**
     * @inheritDoc
     */
    public function getBody(): ?string
    {
        return sprintf(
            'Cron jobs have not been run within the last %d seconds.',
            static::TIMEOUT
        );
    }

    // --------------------------------------------------------------------------

    /**
     * @inheritDoc
     */
    public function getSeverity(): string
    {
        return static::SEVERITY_WARNING;
    }

    // --------------------------------------------------------------------------

    /**
     * @inheritDoc
     */
    public function isAlerting(): bool
    {
        /** @var \DateTime $oNow */
        $oNow  = Factory::factory('DateTime');
        $sThen = appSetting(Listener\Start::SETTINGS_KEY, Constants::MODULE_SLUG);

        if (empty($sThen)) {
            return true;
        }

        $oThen = new \DateTime($sThen);
        $iDiff = $oNow->getTimestamp() - $oThen->getTimestamp();

        return $iDiff > static::TIMEOUT;
    }
}

Add Admin Dashboard alert for cron not running


<?php

namespace App\Console\Commands\Update;

use App\Models\Web\Event;
use App\Transformers\Inbound\Collections\Artwork as ArtworkTransformer;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class UpdateDescriptions extends BaseCommand
{

    protected $signature = 'update:events';

    protected $description = "Add Web CMS fields to a few sample events";

    public function handle()
    {

        $event = Event::find(61);
        $event->ticketed_event_id = 16859;
        $event->ticketed_event_type_id = 73;
        $event->image_url = 'https://cms-toolkit-dev.imgix.net/migrated-7f1e401bb00884f94cd16e52e4fc9aad/cal_ArtPlay_12022017.jpg';
        $event->save();

        $event = Event::find(24);
        $event->ticketed_event_id = 16865;
        $event->ticketed_event_type_id = 73;
        $event->image_url = 'https://cms-toolkit-dev.imgix.net/migrated-bed0f3a8ac6867c3ba5371fa90325158/2922_355206_480x360.png';
        $event->save();

        $event = Event::find(2);
        $event->ticketed_event_id = 16862;
        $event->ticketed_event_type_id = 73;
        $event->image_url = '';
        $event->save();

        $this->info( "Updated 3 events" );

    }

}

Add update command for Web Event ticketed fields


<?php

namespace Backend\Core\Tests;

use Backend\Core\Engine\TemplateModifiers;
use PHPUnit_Framework_TestCase;

defined('SPOON_CHARSET') || define('SPOON_CHARSET', 'UTF-8');

class TemplateModifiersTest extends PHPUnit_Framework_TestCase
{
    function test_stripnewlines()
    {
        $this->assertEquals(
            'Foo Bar',
            TemplateModifiers::stripNewlines("Foo\nBar")
        );

        $this->assertEquals(
            'Foo Bar',
            TemplateModifiers::stripNewlines("Foo\rBar")
        );

        $this->assertEquals(
            'Foo Bar',
            TemplateModifiers::stripNewlines("Foo\r\nBar")
        );
    }

    function test_truncate()
    {
        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 3, false, true),
            'foo'
        );

        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 4, false, true),
            'foo'
        );

        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 8, false, true),
            'foo bar'
        );

        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 100, false, true),
            'foo bar baz qux'
        );

        // Hellip
        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 5, true, true),
            'foo…'
        );

        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 14, true, true),
            'foo bar baz…'
        );

        $this->assertEquals(
            TemplateModifiers::truncate('foo bar baz qux', 15, true, true),
            'foo bar baz qux'
        );
    }
}

Copy some tests from the frontend test cases for templatemodifiers

Only copy the relevant ones...


<?php

function shoestrap_footer_css() {
  $bg = get_theme_mod( 'footer_bg' );
  $cl = get_theme_mod( 'footer_color' );

  echo '';
}
add_action( 'wp_head', 'shoestrap_footer_css' );

/*
 * Creates the customizer icon on the bottom-left corner of our site
 * (visible only by admins)
 */
function footer_icon() { ?>
  <?php if (current_user_can( 'edit_theme_options' )){ ?>

      <?php
      $current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
      $href = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ); ?>
      <a href="<?php echo $href; ?>">

  <?php } ?>

<?php }
add_action( 'shoestrap_after_footer', 'footer_icon' );

<?php

function shoestrap_footer_css() {
  $bg = get_theme_mod( 'footer_bg' );
  $cl = get_theme_mod( 'footer_color' );

  echo '';
}
add_action( 'wp_head', 'shoestrap_footer_css' );

/*
 * Creates the customizer icon on the bottom-left corner of our site
 * (visible only by admins)
 */
function footer_icon() {
  global $wp_customize;
  ?>
  <?php if (current_user_can( 'edit_theme_options' ) && !isset( $wp_customize ) ){ ?>

      <?php
      $current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
      $href = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ); ?>
      <a href="<?php echo $href; ?>">

  <?php } ?>

<?php }
add_action( 'shoestrap_after_footer', 'footer_icon' );

Remove the Customize icon from the customizer.php view. Redundant.


<?php

namespace Tests\Behat\Gherkin\Keywords;

use Behat\Gherkin\Keywords\ArrayKeywords;
use Behat\Gherkin\Node\StepNode;

class ArrayKeywordsTest extends KeywordsTest
{
    protected function getKeywords()
    {
        return new ArrayKeywords($this->getKeywordsArray());
    }

    protected function getKeywordsArray()
    {
        return array(
            'with_special_chars' => array(
                'and' => 'And/foo',
                'background' => 'Background.',
                'but' => 'But[',
                'examples' => 'Examples|Scenarios',
                'feature' => 'Feature|Business Need|Ability',
                'given' => 'Given',
                'name' => 'English',
                'native' => 'English',
                'scenario' => 'Scenario',
                'scenario_outline' => 'Scenario Outline|Scenario Template',
                'then' => 'Then',
                'when' => 'When',
            ),
        );
    }

    protected function getSteps($keywords, $text, &$line, $keywordType)
    {
        $steps = array();
        foreach (explode('|', $keywords) as $keyword) {
            if (false !== mb_strpos($keyword, '<')) {
                $keyword = mb_substr($keyword, 0, -1);
            }

            $steps[] = new StepNode($keyword, $text, array(), $line++, $keywordType);
        }

        return $steps;
    }
}

Add a test using keywords with special chars


<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\Tests\Models\DDC3597\DDC3597Image;
use Doctrine\Tests\Models\DDC3597\DDC3597Media;
use Doctrine\Tests\Models\DDC3597\DDC3597Root;

/**
 */
class EntityListenersOnMergeTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->_schemaTool->createSchema(
            [
                $this->_em->getClassMetadata(DDC3597Root::class),
                $this->_em->getClassMetadata(DDC3597Media::class),
                $this->_em->getClassMetadata(DDC3597Image::class),
            ]
        );
    }

    protected function tearDown()
    {
        parent::tearDown();
        $this->_schemaTool->dropSchema(
            [
                $this->_em->getClassMetadata(DDC3597Root::class),
                $this->_em->getClassMetadata(DDC3597Media::class),
                $this->_em->getClassMetadata(DDC3597Image::class),
            ]
        );
    }

    public function testMergeNewEntityLifecyleEventsModificationsShouldBeKept()
    {
        $imageEntity = new DDC3597Image('foobar');
        $imageEntity->setFormat('JPG');
        $imageEntity->setSize(123);
        $imageEntity->getDimension()->setWidth(300);
        $imageEntity->getDimension()->setHeight(500);

        $imageEntity = $this->_em->merge($imageEntity);

        $this->assertNotNull($imageEntity->getCreatedAt());
        $this->assertNotNull($imageEntity->getUpdatedAt());
    }
}

Create failing test to reveal the issue

Create failing test to reveal the issue


<?php

namespace Kibo\Phast\Services\Bundler;

use Kibo\Phast\Cache\File\Cache;
use Kibo\Phast\Filters\CSS;
use Kibo\Phast\Filters\Service\CachingServiceFilter;
use Kibo\Phast\Retrievers\CachingRetriever;
use Kibo\Phast\Retrievers\LocalRetriever;
use Kibo\Phast\Retrievers\RemoteRetriever;
use Kibo\Phast\Retrievers\UniversalRetriever;
use Kibo\Phast\Security\ServiceSignatureFactory;

class Factory {

    public function make(array $config) {
        $retriever = new UniversalRetriever();
        $retriever->addRetriever(new LocalRetriever($config['retrieverMap']));
        $retriever->addRetriever(
            new CachingRetriever(
                new Cache($config['cache'], 'css'),
                new RemoteRetriever()
            )
        );

        $cssComposite = (new CSS\Composite\Factory())->make($config);

        $caching = new CachingServiceFilter(
            new Cache($config['cache'], 'css-processing-2'),
            $cssComposite,
            new LocalRetriever($config['retrieverMap'])
        );

        return new Service(
            (new ServiceSignatureFactory())->make($config),
            $retriever,
            $caching
        );
    }

}

Create a factory for the bundler service


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UsedKeywordsMemory;

use Broadway\Serializer\SerializableInterface;

abstract class Event implements SerializableInterface {

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

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

    /**
     * @return mixed The object instance
     */
    public static function deserialize(array $data)
    {
        return new static($data['user_id']);
    }

    /**
     * @return array
     */
    public function serialize()
    {
        return array(
            'user_id' => $this->userId,
        );
    }

    /**
     * @return string
     */
    public function getUserId()
    {
        return $this->userId;
    }
}

Add base class for UsedKeywordsMemory events


<?php

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

class AddCanceledToEvents extends Migration {

	/**
	* Run the migrations.
	*
	* @return void
	*/
	public function up()
	{
		Schema::table('events', function(Blueprint $table)
		{
			$table->boolean('canceled')->after('active')->default(false);
		});
	}

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

}

Add canceled to the events table.

Migration: Add canceled to the events table.


<?php

use Phinx\Migration\AbstractMigration;

class MakeVendorItemVendorSkuUniqueKey extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('vendor_item', [ 'signed' => false ]);
      $table
        ->addIndex(['vendor_id','vendor_sku'], [ 'unique' => true ])
        ->update();
    }
}

Add unique key on vendor_item.{vendor_id,vendor_sku}


<?php
namespace Neos\Flow\Core\Migrations;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Utility\Files;

/**
 * This migration does not actually change any code. It just displays a warning if a PHP file still refers
 * to the no longer existing ComponentInterface
 */
class Version20201205172733 extends AbstractMigration
{
    public function getIdentifier(): string
    {
        return 'Neos.Flow-20201205172733';
    }

    public function up(): void
    {
        $affectedFiles = [];
        foreach (Files::getRecursiveDirectoryGenerator($this->targetPackageData['path'], '.php', true) as $pathAndFilename) {
            $fileContents = file_get_contents($pathAndFilename);
            if (preg_match('/(use|implements) Neos\\\Flow\\\Http\\\Component\\\ComponentInterface/', $fileContents) === 1) {
                $affectedFiles[] = substr($pathAndFilename, strlen($this->targetPackageData['path']) + 1);
            }
        }

        if ($affectedFiles !== array()) {
            $this->showWarning('Following files refer to the ComponentInterface that has been removed with Flow 7.0:' . PHP_EOL . PHP_EOL . '* ' . implode(PHP_EOL . '* ', $affectedFiles) . PHP_EOL . PHP_EOL . 'The component chain was replaced with a middleware chain in Flow 7. Please make sure you have read the upgrade instructions and converted your components to middlewares.');
        }
    }
}

TASK: Add core migration that warns about component chain usage

Provides a minimal core migration that will show a warning
when the migrated package contains PHP code that refers to
the no longer existing `ComponentInterface`.

Usage:

    ./flow flow:core:migrate <Package-Key> --version 20201205172733

Example output:

```
Warnings
--------------------------------------------------------------------------------
  * Following files refer to the ComponentInterface that has been removed
    with Flow 7.0:

    * Classes/Http/SomeComponent.php
    * Classes/Http/SomeOtherComponent.php

    The component chain was replaced with a middleware chain in Flow 7. Please make
    sure you have read the upgrade instructions and converted your components to
    middlewares.
--------------------------------------------------------------------------------
```


<?php

namespace Importer\Form;

/**
 * Description of ImportFormFactory
 *
 * @author Kevin Purrmann <k.purrmann@familie-redlich.de>
 */
class ImportFormFactory implements \Zend\ServiceManager\FactoryInterface
{

    public function createService(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
    {

        $form = new ImportForm();
        return $form;
    }

}

Set up import form factory

[BUGFIX] Set up import form factory


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

class AddThemeTemplateTest extends WebTestCase
{
    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/extensions/add_theme_template');

        // we should get redirected to authentication with a reference to blog index in our url
        self::assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fextensions%2Fadd_theme_template',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testFormIsDisplayed(): void
    {
        $client = static::createClient();
        $this->login($client);

        $client->request('GET', '/private/en/extensions/add_theme_template');
        self::assertContains(
            'The user can upload a file.',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Positions',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'If you want a position to display wider or higher in it\'s graphical representation',
            $client->getResponse()->getContent()
        );
    }
}

Add tests for the content extentions add theme template page


<?php
/**
 * This will make the Auto Renew checkbox unchecked by default
 * on the registration form.
 */

// Remove the default checkbox
function jp_override_autonew_checkbox() {
	remove_action( 'rcp_before_registration_submit_field', 'rcp_add_auto_renew' );
	add_action( 'rcp_before_registration_submit_field', 'jp_add_auto_renew' );
}
add_action( 'plugins_loaded', 'jp_override_autonew_checkbox' );

// Add back an unchecked checkbox
function jp_add_auto_renew( $levels = array() ) {
	if( '3' == rcp_get_auto_renew_behavior() ) :
?>

			<input name="rcp_auto_renew" id="rcp_auto_renew" type="checkbox" />
			<?php echo apply_filters ( 'rcp_registration_auto_renew', __( 'Auto Renew', 'rcp' ) ); ?>

<?php
	endif;
}

Add snippet for unchecked auto renew checkbox


<?php
/**
 * @package        CleverStyle CMS
 * @subpackage     System module
 * @category       modules
 * @author         Nazar Mokrynskyi <nazar@mokrynskyi.com>
 * @copyright      Copyright (c) 2014, Nazar Mokrynskyi
 * @license        MIT License, see license.txt
 */
namespace cs;

$Config = Config::instance();
$core   = &$Config->core;
unset(
	$core['auto_translation'],
	$core['auto_translation_engine']
);
unset(
	$core['show_footer_info'],
	$core['footer_text']
);
Text::instance()->del($Config->module('System')->db('texts'), 'System/Config/core', 'footer_text');
file_put_contents(
	DIR.'/config/main.php',
	str_replace(
		"/**
* If true - language can't be changed, it can be useful if there are several domains,
* every of which must work with fixed language (en.domain.com, ru.domain.com, de.domain.com)
*
* Usually, system care about this automatically and there is no need to change this
*/
//define('FIXED_LANGUAGE',	false);
",
		'',
		file_get_contents(DIR.'/config/main.php')
	)
);
unset($core['og_support']);
unset(
	$core['show_db_queries'],
	$core['show_cookies']
);
unset(
	$core['color_schemes'],
	$core['color_scheme']
);
$Config->save();

Update script for system core

Update script for system core


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

namespace ZendTest\Db\Sql\Platform\Mysql\Ddl;

use Zend\Db\Adapter\Platform\Mysql;
use Zend\Db\Sql\Ddl\Column\Column;
use Zend\Db\Sql\Ddl\Constraint\PrimaryKey;
use Zend\Db\Sql\Ddl\CreateTable;
use Zend\Db\Sql\Platform\Mysql\Ddl\CreateTableDecorator;

class CreateTableTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Platform\Mysql\Ddl\CreateTableDecorator::setSubject
     */
    public function testSetSubject()
    {
        $ctd = new CreateTableDecorator();
        $ct = new CreateTable;
        $this->assertSame($ctd, $ctd->setSubject($ct));
    }

    /**
     * @covers Zend\Db\Sql\Platform\Mysql\Ddl\CreateTableDecorator::getSqlString
     */
    public function testGetSqlString()
    {
        $ctd = new CreateTableDecorator();
        $ct = new CreateTable('foo');
        $ctd->setSubject($ct);

        $col = new Column('bar');
        $col->setOption('zerofill', true);
        $col->setOption('unsigned', true);
        $col->setOption('identity', true);
        $col->setOption('column-format', 'FIXED');
        $col->setOption('storage', 'memory');
        $col->setOption('comment', 'baz');
        $col->addConstraint(new PrimaryKey());
        $ct->addColumn($col);

        $this->assertEquals(
            "CREATE TABLE `foo` (\n    `bar` INTEGER UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'baz' COLUMN_FORMAT FIXED STORAGE MEMORY\n)",
            @$ctd->getSqlString(new Mysql())
        );
    }
}

Add test case for checking the MySQL create table decorator

Ensures the decorator properly inserts the MySQL specific column options
into the generated SQL string


<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:op:title_no_user}',
	);
}

openidProvider: Add frontpage hook with link to user page.

Fixes issue 227


<?php
$exit_status = 0;
go(function () {
    try {
        exit(123);
    } catch (\Swoole\ExitException $e) {
        global $exit_status;
        $exit_status = $e->getStatus();
    }
});
swoole_event_wait();
exit($exit_status);

Add example of exit with status.

Add example of exit with status.


<?php

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

class AddEmailToCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('companies', function (Blueprint $table) {
            $table->string('email')->nullable()->after('name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('companies', function (Blueprint $table) {
            if (Schema::hasColumn('companies', 'email')) {
                $table->dropColumn('email');
            }
        });
    }
}

Add email field for company

Add email field for company


<?php

class sfPropelCustomSelectPluginConfiguration extends sfPluginConfiguration
{
  public function initialize()
  {
    if (false === strpos(Propel::VERSION, '1.4'))
    {
      throw new sfException('This plugin is intended for propel 1.4');
    }
  }
}

[config]
Throw an exception if propel version not equal 1.4


<?php

declare(strict_types=1);

namespace RomansTest\Package;

use PHPUnit\Framework\TestCase;

/**
 * License Test
 */
class LicenseTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        $this->content = file_get_contents(dirname(dirname(__DIR__)) . '/LICENSE');
    }

    /**
     * Test Year
     */
    public function testYear(): void
    {
        $currentYear = date('Y');
        $copyright   = "Copyright (c) $currentYear https://github.com/wandersonwhcr/romans";

        $this->assertStringContainsString($copyright, $this->content, 'Invalid Current Year on Licence Copyright');
    }
}

Test current year on copyright

Test current year on copyright


<?php namespace Modules\Dashboard\Foundation\Widgets;

use Illuminate\Contracts\View\Factory;
use Illuminate\Support\ServiceProvider;

abstract class BaseWidget
{
    /**
     * Boot the widget and add the data to the dashboard view composer
     */
    public function boot()
    {
        $widgetViewComposer = app('Modules\Dashboard\Composers\WidgetViewComposer');
        /** @var \Illuminate\Contracts\View\Factory $view */
        $view = app('Illuminate\Contracts\View\Factory');

        if ($view->exists($this->view())) {
            $html = $view->make($this->view())
                         ->with($this->data())
                         ->render();

            $widgetViewComposer
                ->addSubView($this->name(), $html)
                ->addWidgetType($this->name(), $this->type());
        }

        $view->composer('dashboard::admin.dashboard', 'Modules\Dashboard\Composers\WidgetViewComposer');
    }

    /**
     * Get the widget name
     * @return string
     */
    abstract protected function name();

    /**
     * Get the widget type
     * @return string
     */
    abstract protected function type();

    /**
     * Get the widget view
     * @return string
     */
    abstract protected function view();

    /**
     * Get the widget data to send to the view
     * @return string
     */
    abstract protected function data();
}

Add a base widget class which boots the widgets


<?php

namespace Kanboard\Action;

use Kanboard\Model\TaskModel;

/**
 * Move a task to another swimlane when the category is changed
 *
 * @package Kanboard\Action
 * @author  @Interleaved
 */
class TaskMoveSwimlaneCategoryChange extends Base
{
    /**
     * Get automatic action description
     *
     * @access public
     * @return string
     */
    public function getDescription()
    {
        return t('Move the task to another swimlane when the category is changed');
    }

    /**
     * Get the list of compatible events
     *
     * @access public
     * @return array
     */
    public function getCompatibleEvents()
    {
        return array(
            TaskModel::EVENT_UPDATE,
        );
    }

    /**
     * Get the required parameter for the action (defined by the user)
     *
     * @access public
     * @return array
     */
    public function getActionRequiredParameters()
    {
        return array(
            'dest_swimlane_id' => t('Destination swimlane'),
            'category_id' => t('Category'),
        );
    }

    /**
     * Get the required parameter for the event
     *
     * @access public
     * @return string[]
     */
    public function getEventRequiredParameters()
    {
        return array(
            'task_id',
            'task' => array(
                'project_id',
                'column_id',
                'category_id',
                'position',
                'swimlane_id',
            )
        );
    }

    /**
     * Execute the action (move the task to another swimlane)
     *
     * @access public
     * @param  array   $data   Event data dictionary
     * @return bool            True if the action was executed or false when not executed
     */
    public function doAction(array $data)
    {
        return $this->taskPositionModel->movePosition(
            $data['task']['project_id'],
            $data['task_id'],
            $data['task']['column_id'],
            $data['task']['position'],
            $this->getParam('dest_swimlane_id'),
            false
        );
    }

    /**
     * Check if the event data meet the action condition
     *
     * @access public
     * @param  array   $data   Event data dictionary
     * @return bool
     */
    public function hasRequiredCondition(array $data)
    {
        return $data['task']['swimlane_id'] != $this->getParam('dest_swimlane_id') && $data['task']['category_id'] == $this->getParam('category_id');
    }
}

Add action for moving a task to swimlane based on category change


<?php

class Test{
    public function A($param) {
        $query  = "INSERT INTO some_table (some_value) VALUES ('".$param."')";
        $this->dbexec($query);
    }
    public function B($param){
        $param = $this->sanitise($param);
        $query  = "INSERT INTO some_table (some_value) VALUES ('".$param."')";
        $this->dbexec($query);
    }
    public function C($param){
        $param = $this->D($param);
        $query  = "INSERT INTO some_table (some_value) VALUES ('".$param."')";
        $this->dbexec($query);
    }
    public function D($param){
        $param = $this->sanitise($param);
        return $param;
    }
    public function E($param){
        $param = $this->F($param);
        $query  = "INSERT INTO some_table (some_value) VALUES ('".$param."')";
        $this->dbexec($query);
    }
    public function F($param){
        return $param;
    }
    public function dbexec($query) {
        echo $query."\n";
    }
    public function sanitise($unsafe_value){
        $safe_value = substr($unsafe_value,2);
        return $safe_value;
    }
    public function httpGetRequest(){
        $userinput_unsafe = "unsafe value";
        return $userinput_unsafe;
    }
}

$test = new Test();
$userinput = $test->httpGetRequest();
$safeinput = $test->sanitise($userinput);
$test->A($safeinput);
$test->A($userinput);
$test->B($userinput);
$test->C($userinput);
$test->E($userinput);

Add an example to check on callgraph and control flow graph functionality


<?php
namespace EAMann\Sessionz\Handlers;

use EAMann\Sessionz\Handler;
use PHPUnit\Framework\TestCase;

/**
 * @codeCoverageIgnore
 */
class ConcreteHandler extends NoopHandler {}

/**
 * The BaseHandler doesn't actually do anything, but we need to ensure
 * it passes method calls down to the next item in the stack.
 */
class NoopHandlerTest extends TestCase {

    public function test_delete()
    {
        $handler = new ConcreteHandler();
        $called = false;

        $callback = function($id) use (&$called) {
            $this->assertEquals('doesntmatter', $id);
            $called = true;

            return true;
        };

        $this->assertTrue($handler->delete('doesntmatter', $callback));

        $this->assertTrue($called);
    }

    public function test_clean()
    {
        $handler = new ConcreteHandler();
        $called = false;

        $callback = function($lifetime) use (&$called) {
            $this->assertEquals(50, $lifetime);
            $called = true;

            return true;
        };

        $this->assertTrue($handler->clean(50, $callback));

        $this->assertTrue($called);
    }

    public function test_create()
    {
        $handler = new ConcreteHandler();
        $called = false;

        $callback = function($path, $name) use (&$called) {
            $this->assertEquals('path', $path);
            $this->assertEquals('name', $name);
            $called = true;

            return true;
        };

        $this->assertTrue($handler->create('path', 'name', $callback));

        $this->assertTrue($called);
    }

    public function test_read()
    {
        $handler = new ConcreteHandler();
        $called = false;

        $callback = function($id) use (&$called) {
            $this->assertEquals('doesntmatter', $id);
            $called = true;

            return 'data';
        };

        $this->assertEquals('data', $handler->read('doesntmatter', $callback));

        $this->assertTrue($called);
    }

    public function test_write()
    {
        $handler = new ConcreteHandler();
        $called = false;

        $callback = function($id, $data) use (&$called) {
            $this->assertEquals('someid', $id);
            $this->assertEquals('data', $data);
            $called = true;

            return true;
        };

        $this->assertTrue($handler->write('someid', 'data', $callback));

        $this->assertTrue($called);
    }
}

Test the Noop base handler

Test the Noop base handler


<?php

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

namespace Symfony\Component\Routing\Tests\Loader;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Resource\GlobResource;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\GlobFileLoader;
use Symfony\Component\Routing\RouteCollection;

class GlobFileLoaderTest extends TestCase
{
    public function testSupports()
    {
        $loader = new GlobFileLoader(new FileLocator());

        $this->assertTrue($loader->supports('any-path', 'glob'), '->supports() returns true if the resource has the glob type');
        $this->assertFalse($loader->supports('any-path'), '->supports() returns false if the resource is not of glob type');
    }

    public function testLoadAddsTheGlobResourceToTheContainer()
    {
        $loader = new GlobFileLoaderWithoutImport(new FileLocator());
        $collection = $loader->load(__DIR__.'/../Fixtures/directory/*.yml');

        $this->assertEquals(new GlobResource(__DIR__.'/../Fixtures/directory', '/*.yml', false), $collection->getResources()[0]);
    }
}

class GlobFileLoaderWithoutImport extends GlobFileLoader
{
    public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null)
    {
        return new RouteCollection();
    }
}

Add tests for glob loaders

Add tests for glob loaders


<?php
/**
 * A dependency injection container for lazy-evaluated shared resources.
**/
namespace Ob_Ivan\ResourceContainer;

use ArrayAccess;

class ResourceContainer implements ArrayAccess
{
    /**
     * @var [<string name> => <mixed(self) factory>]
    **/
    private $factories = [];

    /**
     * @var [<string name> => <mixed value>]
    **/
    private $values = [];

    // public : ArrayAccess //

    public function offsetExists($name)
    {
        return isset($this->values[$name]) || isset($this->factories[$name]);
    }

    public function offsetGet($name)
    {
        if (isset($this->values[$name])) {
            return $this->values[$name];
        }
        if (isset($this->factories[$name])) {
            return $this->factories[$name]($this);
        }
        throw new Exception('Unknown resource "' . $name . '"');
    }

    public function offsetSet($name, $value)
    {
        $this->values[$name] = $value;
        unset($this->factories[$name]);
    }

    public function offsetUnset($name)
    {
        unset($this->values[$name]);
        unset($this->factories[$name]);
    }

    // public : ResourceContainer //

    public function __construct(array $values = [])
    {
        foreach ($values as $name => $value) {
            $this[$name] = $value;
        }
    }

    public function register($name, callable $factory)
    {
        $this->factories[$name] = $this->share($factory);
        unset($this->values[$name]);
    }

    // private //

    private function share(callable $factory)
    {
        return function ($container) use ($factory) {
            static $value;
            if (is_null($value)) {
                $value = $factory($container);
            }
            return $value;
        };
    }
}

Add a prototype for dependency injection container of my choice


<?php

namespace DCS\User\CoreBundle\Tests\DependencyInjection\Command;

use DCS\User\CoreBundle\Command\CreateUserCommand;
use DCS\User\CoreBundle\Helper\PasswordHelperInterface;
use DCS\User\CoreBundle\Manager\Save;
use DCS\User\CoreBundle\Model\UserInterface;
use DCS\User\CoreBundle\Service\UserFactoryInterface;
use DCS\User\CoreBundle\Tests\TestUser;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\Input;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;

class CreateUserCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testConfigureMethod()
    {
        $container = new Container();

        $command = new CreateUserCommand();
        $command->setContainer($container);

        $this->assertEquals('dcs_user:core:create_user', $command->getName());

        $this->assertTrue($command->getDefinition()->hasOption('username'));
        $this->assertTrue($command->getDefinition()->hasOption('password'));

        $this->assertTrue($command->getDefinition()->getOption('username')->isValueRequired());
        $this->assertTrue($command->getDefinition()->getOption('password')->isValueRequired());
    }

    public function testExecuteMethod()
    {
        $input = $this->getMockBuilder(InputInterface::class)->getMock();
        $input->expects($this->at(0))->method('getOption')->willReturn('acme');
        $input->expects($this->at(1))->method('getOption')->willReturn('password');

        $output = $this->getMockBuilder(OutputInterface::class)->getMock();

        $userFactory = $this->getMockBuilder(UserFactoryInterface::class)->getMock();
        $userFactory->expects($this->once())->method('create')->willReturn(new TestUser());

        $passwordHelper = $this->getMockBuilder(PasswordHelperInterface::class)->getMock();
        $passwordHelper->expects($this->once())->method('updateUserPassword');

        $save = $this->getMockBuilder(Save::class)->disableOriginalConstructor()->getMock();
        $save->expects($this->once())->method('__invoke')->with($this->isInstanceOf(UserInterface::class));

        $container = $this->getMockBuilder(ContainerInterface::class)->getMock();
        $container->expects($this->at(0))->method('get')->with('dcs_user.factory')->willReturn($userFactory);
        $container->expects($this->at(1))->method('get')->with('dcs_user.core.helper.password')->willReturn($passwordHelper);
        $container->expects($this->at(2))->method('get')->with('dcs_user.manager.save')->willReturn($save);

        $command = new CreateUserCommand();
        $command->setContainer($container);

        $command->run($input, $output);
    }
}

Add test for the CreateUserCommand class


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiWebfontsService.php';

$client = new apiClient();
$client->setApplicationName("Google WebFonts PHP Starter Application");

// Visit https://code.google.com/apis/console?api=webfonts
// to generate your developer key.
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiWebfontsService($client);
$fonts = $service->webfonts->listWebfonts();
print "
Fonts

" . print_r($fonts, true) . "
";

Add a sample application for the webfonts API.


<?php

namespace Project\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Project\AppBundle\Entity\User;
use Project\AppBundle\Form\UserType;

class DefaultController extends Controller
{
    /**
     * Lists all User entities.
     *
     * @Secure(roles={"ROLE_MANAGER", "ROLE_SPEAKER", "ROLE_STUDENT"})
     * @Route("/", name="project_app_index")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        // Get logged in user
        $user = $this->getUser();
        $userRoles = $user->getRoles();

        if(in_array('ROLE_MANAGER', $userRoles)) {
            return $this->redirect($this->generateUrl('promotion'));
        } elseif(in_array('ROLE_SPEAKER', $userRoles)) {
            return $this->redirect($this->generateUrl('missing'));
        } elseif(in_array('ROLE_STUDENT', $userRoles)) {
            return $this->redirect($this->generateUrl('project_app_agenda_index'));
        }
    }
}

Implement default controller to redirect in function of role


<?php

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

class ModifyUsersTableToRemoveUsername extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table) {
            $table->dropColumn('username');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {}
}

Add migration to drop 'username' column from 'users' table


<?php
namespace CfdiUtils\CadenaOrigen;

abstract class AbstractXsltBuilder implements XsltBuilderInterface
{
    protected function assertBuildArguments(string $xmlContent, string $xsltLocation): string
    {
        if ('' === $xmlContent) {
            throw new \UnexpectedValueException('The XML content to transform is empty');
        }
        if ('' === $xsltLocation) {
            throw new \UnexpectedValueException('Xslt location was not set');
        }
        return '';
    }
}

Add abstract class to avoid duplicate of checking input parameters


<?php

namespace SparkTests\Configuration;

use Spark\Adr\PayloadInterface;
use Spark\Configuration\PayloadConfiguration;
use Spark\Payload;

class PayloadConfigurationTest extends ConfigurationTestCase
{
    protected function getConfigurations()
    {
        return [
            new PayloadConfiguration,
        ];
    }

    public function testApply()
    {
        $payload = $this->injector->make(PayloadInterface::class);

        $this->assertInstanceOf(Payload::class, $payload);
    }
}

Add test for payload configuration

Add test for payload configuration


<?php
/**
 * Test Case
 *
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://getfrapi.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@getfrapi.com so we can send you a copy immediately.
 *
 * This class contains the rules about errors
 *
 * It mostly contains methods that are there to validate
 * the errors.
 *
 * @license   New BSD
 * @package   frapi-tests
 */
class Frapi_ErrorTest extends PHPUnit_Framework_TestCase
{

    /**
     * @var Frapi_Error
     */
    private $_e;

    public function setUp()
    {
        $this->_e = new Frapi_Error(
                'Frapi_Error',
                'Frapi Error Message',
                400,
                'Frapi Error'
        );
    }

    public function testErrorNameIsException()
    {
        $e = new Frapi_Error(new Exception('Exception thrown', '99'));
        $error = $e->getErrorArray();
        $this->assertEquals(400, $e->getCode());
        $this->assertEquals('Bad Request', $e->getReasonPhrase());
        $this->assertEquals('Exception thrown', $error['errors'][0]['message']);
        $this->assertEquals(99, $error['errors'][0]['name']);
        $this->assertEquals('', $error['errors'][0]['at']);
    }

    public function testLoadErrorFromName()
    {
        $this->markTestIncomplete('Can we guarantee our default errors will always be there');
    }

    public function testReasonPhraseSetByErrorMsg()
    {
        $e = new Frapi_Error('SOME_ERROR', 'Error Message', 666);
        $this->assertEquals('Error Message', $e->getReasonPhrase());
    }

    public function testReasonPhraseSetByStandardCode()
    {
        $e = new Frapi_Error('SOME_ERROR', 'Error Message', 400);
        $this->assertEquals('Bad Request', $e->getReasonPhrase());
    }

    public function testErrorHandler()
    {
        try {
            Frapi_Error::errorHandler(E_ERROR, 'This is a PHP error', 'ErrorFile.php', '99');
        } catch (Frapi_Error $e) {
            $error = $e->getErrorArray();
        }
        $this->assertEquals(400, $e->getCode());
        $this->assertEquals('Bad Request', $e->getReasonPhrase());
        $this->assertEquals('This is a PHP error (Error Number: 1), (File: ErrorFile.php at line 99)', $error['errors'][0]['message']);
        $this->assertEquals('PHP Fatal error', $error['errors'][0]['name']);
        $this->assertEquals('', $error['errors'][0]['at']);
    }

    public function testCallStaticMesage()
    {
        $this->markTestIncomplete('Need to guarantee we have default errors. Also, is this even used? I cant find it in code.');
    }
}

Add tests for Frapi_Error class.

Add tests for Frapi_Error class.


<?php

namespace Oro\Bundle\ActionBundle\Helper;

use Symfony\Component\HttpFoundation\RequestStack;

class RequestHelper
{
    /** @var RequestStack */
    protected $requestStack;

    /** @var ApplicationsHelper */
    protected $applicationsHelper;

    /**
     * @param RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack, ApplicationsHelper $applicationsHelper)
    {
        $this->requestStack = $requestStack;
        $this->applicationsHelper = $applicationsHelper;
    }

    /**
     * @return string
     */
    public function getRequestRoute()
    {
        if (null === ($request = $this->requestStack->getMasterRequest())) {
            return;
        }

        $route = $request->get('_route');

        return $route !== $this->applicationsHelper->getExecutionRoute() ? $route : null;
    }
}

<?php

namespace Oro\Bundle\ActionBundle\Helper;

use Symfony\Component\HttpFoundation\RequestStack;

class RequestHelper
{
    /** @var RequestStack */
    protected $requestStack;

    /** @var ApplicationsHelper */
    protected $applicationsHelper;

    /**
     * @param RequestStack $requestStack
     * @param ApplicationsHelper $applicationsHelper
     */
    public function __construct(RequestStack $requestStack, ApplicationsHelper $applicationsHelper)
    {
        $this->requestStack = $requestStack;
        $this->applicationsHelper = $applicationsHelper;
    }

    /**
     * @return string
     */
    public function getRequestRoute()
    {
        if (null === ($request = $this->requestStack->getMasterRequest())) {
            return;
        }

        $route = $request->get('_route');

        return $route !== $this->applicationsHelper->getExecutionRoute() ? $route : null;
    }
}

BB-3192: Make default delete operation available only in main entity management grids
- cs updates


<?php

namespace Chromabits\Illuminated\Database\Commands;

use Chromabits\Illuminated\Database\Interfaces\StructuredMigratorInterface;
use Illuminate\Console\Command;
use Illuminate\Database\Console\Migrations\RollbackCommand;

/**
 * Class StructuredRollbackCommand
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Database\Commands
 */
class StructuredRollbackCommand extends RollbackCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'structured:rollback';

    /**
     * Construct an instance of a StructuredRollbackCommand.
     *
     * @param StructuredMigratorInterface $migrator
     */
    public function __construct(StructuredMigratorInterface $migrator)
    {
        Command::__construct();

        $this->migrator = $migrator;
    }
}

Add rollback command for structured migrations


<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

class AlterTableMetricsAddVisibleColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('metrics', function (Blueprint $table) {
            $table->boolean('visible')->after('order')->default(1);

            $table->index('visible');
        });
    }

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

<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

class AlterTableMetricsAddVisibleColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('metrics', function (Blueprint $table) {
            $table->unsignedTinyInteger('visible')->after('order')->default(1);

            $table->index('visible');
        });
    }

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

Use unsigned tiny int instead of boolean for visible metrics


<?php
namespace App\Test\TestCase\Model\Behavior;

use App\Model\Behavior\LimitResultsBehavior;
use Cake\TestSuite\TestCase;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;

class LimitResultsBehaviorTest extends TestCase
{
    private $query;
    private $behavior;

    public $fixtures = [
        'app.Sentences',
        'app.Users',
    ];

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

        $s = TableRegistry::getTableLocator()->get('Sentences');
        $this->behavior = new LimitResultsBehavior($s);
        // PHPUnit annoying warnings silenced
        // Please someone check if this gets fixed in version 7.0 or newer
        $this->query = @$this->createTestProxy(Query::class, [$s->getConnection(), $s]);
        $this->query->order(['Sentences.id' => 'DESC']);
    }

    public function tearDown()
    {
        unset($this->query);
        unset($this->behavior);

        parent::tearDown();
    }

    public function testFindLatest_simple()
    {
        $this->query
             ->expects($this->once())
             ->method('where')
             ->with(['Sentences.id >=' => 38]);

        $this->behavior->findLatest($this->query, ['maxResults' => 20]);
    }

    public function testFindLatest_whereOnMainTable()
    {
        $this->query
             ->where(['Sentences.lang' => 'cmn']);

        $this->query
             ->expects($this->once())
             ->method('where')
             ->with(['Sentences.id >=' => 2]);

        $this->behavior->findLatest($this->query, ['maxResults' => 20]);
    }

    public function testFindLatest_whereOnJoinedTable()
    {
        $this->query
             ->where(['Users.role' => 'contributor'])
             ->contain(['Users']);

        $this->query
             ->expects($this->once())
             ->method('where')
             ->with(['Sentences.id >=' => 11]);

        $this->behavior->findLatest($this->query, ['maxResults' => 20]);
    }
}

Add unit tests for our 'latest' custom finder


<?php defined('SYSPATH') or die('No direct script access.');

class Migration_Boom_20131021155200 extends Minion_Migration_Base
{

	public function up(Kohana_Database $db)
	{
		$db->query(NULL, "alter table chunk_slideshow_slides change caption caption varchar(255)");
	}

	public function down(Kohana_Database $db)
	{
	}
}

Increase slideshow caption max length to 22


<?php
use Migrations\AbstractMigration;

class UserLangIndex extends AbstractMigration
{
    public function up()
    {
        $table = $this->table('sentences');
        $table->addIndex(['user_id', 'lang'], ['name' => 'user_lang_idx'])
              ->removeIndexByName('user_id')
              ->update();
    }

    public function down()
    {
        $table = $this->table('sentences');
        $table->addIndex(['user_id'], ['name' => 'user_id'])
              ->removeIndexByName('user_lang_idx')
              ->update();
    }
}

Optimize querying sentences owned by a given user

While sentence queries generated by /sentences/of_user/xxx
are fine, queries generated by /sentences/of_user/xxx/yyy
can result in very poor performance, hitting PHP script
execution timeout. This especially happens when user xxx
owns less than 10 sentences in language yyy, but a lot of
sentences in other languages. In this case, mysql needs to
go through all xxx’s sentences just to be sure xxx owns
less than 10 sentences in yyy. To make things worse, the
interface currently makes it quite easy to fall in this
case because the language dropdown does not limit choices
to languages in which xxx owns sentences (making it likely
to select a language in which xxx owns no sentences).

Closes #2630.


<?php

/*
 * This file is part of the TomahawkPHP package.
 *
 * (c) Tom Ellis
 *
 * The is based on code originally distributed inside the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 * (c) Doctrine Project, Benjamin Eberlei <kontakt@beberlei.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tomahawk\Bundle\DoctrineBundle\Command\Proxy;

use Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand as BaseGenerateProxiesCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateProxiesCommand extends BaseGenerateProxiesCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('doctrine:generate:proxies')
            ->setAliases(['orm:generate:proxies'])
            ->setDescription('Generates proxy classes for entity classes.')
            ->setDefinition([
                new InputOption(
                    'em', null, InputOption::VALUE_OPTIONAL,
                    'The entity manager to use for this command.'
                ),
                new InputOption(
                    'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
                    'A string pattern used to match entities that should be processed.'
                ),
                new InputArgument(
                    'dest-path', InputArgument::OPTIONAL,
                    'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.'
                ),
            ])
            ->setHelp(<<<EOT
Generates proxy classes for entity classes.
EOT
            );
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        CommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em'));

        return parent::execute($input, $output);
    }
}

Add doctrine generate proxies command

Add doctrine generate proxies command


<?php if ( ! defined('EXT')) exit('Invalid file request.');

/**
 * Campaigner Multi-Select extension tests.
 *
 * @author          Stephen Lewis (http://github.com/experience/)
 * @copyright       Experience Internet
 * @package         Campaigner_multiselect
 */

require_once PATH_THIRD .'campaigner_multiselect/ext.campaigner_multiselect.php';
require_once PATH_THIRD .'campaigner_multiselect/tests/mocks/mock.campaigner_multiselect_model.php';

class Test_campaigner_multiselect_ext extends Testee_unit_test_case {

  private $_model;
  private $_subject;

  /* --------------------------------------------------------------
   * PUBLIC METHODS
   * ------------------------------------------------------------ */

  /**
   * Set up.
   *
   * @access  public
   * @return  void
   */
  public function setUp()
  {
    parent::setUp();

    Mock::generate(
      'Mock_campaigner_multiselect_model',
      get_class($this) .'_mock_model'
    );

    $this->_model = $this->_get_mock('model');
    $this->_ee->campaigner_multiselect_model =& $this->_model;
    $this->_subject = new Campaigner_multiselect_ext();
  }

/* End of file      : test.campaigner_multiselect_ext.php */
/* File location    : third_party/campaigner_multiselect/tests/
 *                    test.campaigner_multiselect_ext.php */

Implement shell extension unit tests file.


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.7.5
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Test\TestCase\Database\Expression;

use Cake\Database\Expression\Comparison;
use Cake\Database\Expression\QueryExpression;
use Cake\TestSuite\TestCase;

/**
 * Tests Comparison class
 */
class ComparisonTest extends TestCase
{
    /**
     * Tests that cloning Comparion instance clones it's value and field expressions.
     *
     * @return void
     */
    public function testClone()
    {
        $exp = new Comparison(new QueryExpression('field1'), 1, 'integer', '<');
        $exp2 = clone $exp;

        $this->assertNotSame($exp->getField(), $exp2->getField());
    }
}

Add test for previous commit.

Add test for previous commit.


<?php namespace Illuminate\Contracts\Bus;

interface PipingDispatcher extends Dispatcher {

	/**
	 * Set the pipes commands should be piped through before dispatching.
	 *
	 * @param  array  $pipes
	 * @return $this
	 */
	public function pipeThrough(array $pipes);

}

Add contract to let dispatcher use pipelines


<?php

require BASEPATH . 'helpers/path_helper.php';

class Path_helper_test extends CI_TestCase
{
	public function test_set_realpath()
	{
		$expected = getcwd() . '/';
		$this->assertEquals($expected, set_realpath(getcwd()));
	}

	public function test_set_realpath_nonexistent_directory()
	{
		$expected = '/path/to/nowhere';
		$this->assertEquals($expected, set_realpath('/path/to/nowhere', FALSE));
	}

	public function test_set_realpath_error_trigger()
	{
		$this->setExpectedException(
				'RuntimeException', 'CI Error: Not a valid path: /path/to/nowhere'
		);

		set_realpath('/path/to/nowhere', TRUE);
	}
}

/* End of file path_helper_test.php */

Add unit tests for path helper

Add unit tests for path helper


<?php
/**
 * Copyright 2005-2015 Centreon
 * Centreon is developped by : Julien Mathis and Romain Le Merlus under
 * GPL Licence 2.0.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation ; either version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses>.
 *
 * Linking this program statically or dynamically with other modules is making a
 * combined work based on this program. Thus, the terms and conditions of the GNU
 * General Public License cover the whole combination.
 *
 * As a special exception, the copyright holders of this program give Centreon
 * permission to link this program with independent modules to produce an executable,
 * regardless of the license terms of these independent modules, and to copy and
 * distribute the resulting executable under terms of Centreon choice, provided that
 * Centreon also meet, for each linked independent module, the terms  and conditions
 * of the license of that module. An independent module is a module which is not
 * derived from this program. If you modify this program, you may extend this
 * exception to your version of the program, but you are not obliged to do so. If you
 * do not wish to do so, delete this exception statement from your version.
 *
 * For more information : contact@centreon.com
 *
 */

require_once "class/centreonWidget/Params/Select2.class.php";

class CentreonWidgetParamsConnectorServiceGroupMulti extends CentreonWidgetParamsSelect2
{
    public function __construct($db, $quickform, $userId)
    {
        parent::__construct($db, $quickform, $userId);
    }

    public function getParameters()
    {
        return array (
            'datasourceOrigin' => 'ajax',
            'availableDatasetRoute' => './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup&action=list',
            'multiple' => true,
            'linkedObject' => 'centreonServicegroups'
        );
    }

}

Add ServieGroupMulti connector for Select2


<?php

use Codeception\Configuration;

/**
 * Data Path
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
trait DataPath
{

    /**
     * Returns the path to the test data directory
     *
     * @return string
     */
    public function dataPath()
    {
        return Configuration::dataDir();
    }

}

Add Data Path test utility

Add Data Path test utility


<?php

namespace Backend\Modules\ContentBlocks\ValueObject;

use InvalidArgumentException;

final class Status
{
    const STATUS_ARCHIVED = 'archived';
    const STATUS_ACTIVE = 'active';

    /**
     * @var string
     */
    private $status;

    /**
     * @param string $status
     */
    private function __construct($status)
    {
        $this->setStatus($status);
    }

    /**
     * @return array
     */
    private function getPossibleStatuses()
    {
        return [
            self::STATUS_ARCHIVED,
            self::STATUS_ACTIVE,
        ];
    }

    /**
     * @param $status
     *
     * @return self
     */
    public static function fromString($status)
    {
        return new self($status);
    }

    /**
     * @param string $status
     *
     * @throws InvalidArgumentException
     *
     * @return $this
     */
    private function setStatus($status)
    {
        if (!in_array($status, $this->getPossibleStatuses())) {
            throw new InvalidArgumentException('Invalid status');
        }

        $this->status = $status;

        return $this;
    }

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

    /**
     * @return bool
     */
    public function isActive()
    {
        return $this->status === self::STATUS_ACTIVE;
    }

    /**
     * @return bool
     */
    public function isArchived()
    {
        return $this->status === self::STATUS_ARCHIVED;
    }

    /**
     * @return self
     */
    public static function active()
    {
        return new self(self::STATUS_ACTIVE);
    }

    /**
     * @return self
     */
    public static function archived()
    {
        return new self(self::STATUS_ARCHIVED);
    }
}

Add the Satus as a ValueObject

Add the Satus as a ValueObject


<?php
namespace Math\Probability\Distribution\Continuous;

class LimitsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Limits should look like:
     *  (a,b)
     *  [a,b)
     *  (a,b]
     *  [a,b]
     */
    private function limitTest($limits)
    {
        foreach ($limits as $parameter => $limit) {
            $this->assertRegExp('/^ ([[(]) (.+) , (.+?) ([])]) $/x', $limit);
        }

    }

    public function testBetaParameterLimits()
    {
        $this->limitTest(Beta::LIMITS);
    }
}

Add unit test for testing Continuous Distribution limits.


<?php

class CMTest_SplittedUnitTest {

    public static function suite($suiteClassName) {
        $matches = [];
        $range = getenv('PHPUNIT_TEST_RANGE') ?: '';
        if (preg_match('/(?P<chunk>\d+)\/(?P<parts>\d+)/', $range, $matches)) {
            $chunk = (int) $matches['chunk'] - 1;
            $parts = isset($matches['parts']) ? (int) $matches['parts'] : null;
        } else {
            throw new CM_Exception_Invalid('PHPUNIT_TEST_RANGE environment variable must be set');
        }

        $facade = new File_Iterator_Facade();
        $files = $facade->getFilesAsArray(
            DIR_ROOT . '/tests',
            'Test.php'
        );
        $filesChunks = array_chunk($files, ceil(count($files) / $parts));
        $suite = new PHPUnit_Framework_TestSuite('SplittedUnitTest');
        $suite->addTestFiles(isset($filesChunks[$chunk]) ? $filesChunks[$chunk] : []);
        return $suite;
    }
}

Allow to run tests by range via a custom suite


<?php
namespace frontend\controllers\erp;

use yii\base\Action;
use yii\data\ActiveDataProvider;
use common\models\SaleOrder;
use common\models\ResUsers;
use yii\data\SqlDataProvider;

class SaleordersAction extends Action{
    public function run(){
        $provider = New ActiveDataProvider([
            'query' => SaleOrder::find()->joinWith('createU.partner'),
        ]);

        return $this->controller->render('saleorders', [
            'provider' => $provider,
        ]);
    }
}

Add a sale orders action

Add a sale orders action


<?php
class DenpendencyFailureTest extends PHPUnit_Framework_TestCase
{
	public function testOne()
	{
		$this->assertTrue(FALSE);
	}

	/**
	 * @depends testOne
	 */
	public function testTwo()
	{

	}
}

Add test/DenpendencyFailureTest.php to implement denpendency test ignore case


<?php

namespace ApiRecipe\Controller;

class JarvisController extends Controller
{
    private $url;

    /**
     * @return array
     */
    public function indexAction()
    {
        $this->url = sprintf('%s:%s', $this->getConfig('server')['address'], $this->getConfig('server')['port']);
        $recipes = $this->getRecipeManager()->getAll();
        $responseContent = '';
        foreach ($recipes as $recipeName => $recipe) {
            if (!isset($recipe->voices)) {
                continue;
            }

            $responseContent = $this->appendRecipeToResponse($recipeName, $recipe, $responseContent);
        }

        die($responseContent);
    }

    private function appendRecipeToResponse($recipeName, $recipe, $responseContent)
    {
        foreach ($recipe->voices as $state => $triggers) {
            if (!isset($triggers['triggers'])) {
                continue;
            }
            foreach ($triggers['triggers'] as $trigger) {
                $trigger = str_replace(['%', '(.*?)'], ['', '*'], $trigger);
                $trigger = sprintf('%s=$(curl -s "http://%s/recipes/%s/exec?state=%s" > /dev/null)', $trigger, $this->url, $recipeName, $state);
                $responseContent .= $trigger."\n";
            }
        }

        return $responseContent;
    }
}

Add Jarvis generator conf endpoint

Add Jarvis generator conf endpoint


<?php

namespace CSP\Test\Header;

use CSP\Test\TestCase;
use CSP\Header\ContentSecurityPolicyHeader;
use CSP\Policy;

class ContentSecurityPolicyHeaderTest extends TestCase {

	/**
	 * @coversNothing
	 */
	public function testHeader()
	{
		$header = new ContentSecurityPolicyHeader;
		$this->assertInstanceOf('CSP\Header\Header', $header);
	}

	/**
	 * @covers CSP\Header\ContentSecurityPolicyHeader::__construct
	 */
	public function testConstructor()
	{
		$header = new ContentSecurityPolicyHeader;
		$this->assertNull($header->getValue());

		$header = new ContentSecurityPolicyHeader(NULL);
		$this->assertNull($header->getValue());

		$policy = new Policy;
		$header = new ContentSecurityPolicyHeader($policy);
		$this->assertSame($policy, $header->getValue());
	}

	/**
	 * @covers CSP\Header\ContentSecurityPolicyHeader::getValue
	 */
	public function testGetValue()
	{
		$header = new ContentSecurityPolicyHeader;
		$this->assertNull($header->getValue());

		$policy = new Policy;
		$header->setValue($policy);
		$this->assertSame($policy, $header->getValue());
	}

	/**
	 * @covers CSP\Header\ContentSecurityPolicyHeader::setValue
	 */
	public function testSetValue()
	{
		$header = new ContentSecurityPolicyHeader;
		$policy = new Policy;
		$header->setValue($policy);
		$this->assertSame($policy, $header->getValue());
	}

	/**
	 * @covers CSP\Header\ContentSecurityPolicyHeader::setValue
	 */
	public function testSetValueArgumentException()
	{
		$this->setExpectedException('InvalidArgumentException', 'ContentSecurityPolicyHeader value must be an instance of PolicyInterface');
		$header = new ContentSecurityPolicyHeader;
		$header->setValue('ABCDE');
	}

	public function testGetName()
	{
		$header = new ContentSecurityPolicyHeader;
		$this->assertSame(ContentSecurityPolicyHeader::NAME, $header->getName());
	}

}

Add test for CSP header class

Add test for CSP header class


<?php

class Denkmal_Mail_UserInviteTest extends CMTest_TestCase {

    protected function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testRender() {
        $user = Denkmal_Model_User::create('foo@example.com', 'foo', 'passwd');
        $userInvite = Denkmal_Model_UserInvite::create($user, 'bar@example.com');

        $mail = new Denkmal_Mail_UserInvite($userInvite);
        list($subject, $html, $text) = $mail->render();

        $this->assertSame([['address' => 'bar@example.com', 'name' => null]], $mail->getTo());
        $this->assertContains('Einladung', $subject);
        $this->assertContains('Account Erstellen', $html);
    }
}

Add test for userInvite email

Add test for userInvite email


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type\Census;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class CensusStepConditionsType extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('conditions', 'choice', array(
				        'choices' => array('yes' => 'SI', 'no' => 'NO'),
        				'preferred_choices' => array('no'),
        				'data' => 'no',
				        'multiple' => false,
				        'expanded' => true,
				        'required' => true,
				    ))
        		->add('continue', 'submit', array('attr' => array('class' => 'submit','style' => 'margin-left:0px')));
    }

    // 		{{ form_widget(form.conditions, 'candidacy.step_conditions.accept'|trans) }}
	//	{{ form_errors(form.conditions) }}
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Update form type for step conditions

Update form type for step conditions


<?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 / Test / Unit / App / System / Core / Classes
 */

namespace PH7\Test\Unit\App\System\Core\Classes;

require_once PH7_PATH_SYS . 'core/classes/AdsCore.php';

use PH7\Framework\Layout\Html\Design;
use PH7\Framework\Session\Session;
use PH7\ValidateSiteCore;
use Phake;
use Phake_IMock;
use PHPUnit_Framework_TestCase;

class ValidateSiteCoreTest extends PHPUnit_Framework_TestCase
{
    /** @var ValidateSiteCore|Phake_IMock */
    private $oValidateSite;

    protected function setUp(): void
    {
        $oSession = Phake::mock(Session::class);
        $this->oValidateSite = new ValidateSiteCore($oSession);
    }

    public function testInjectJsSuggestionBox()
    {
        $oDesign = Phake::mock(Design::class);

        $this->oValidateSite->injectJsSuggestionBox($oDesign);

        Phake::verify($oDesign)->addJs(Phake::anyParameters());
    }
}

Add unit test for ValidateSiteCore

Add unit test for ValidateSiteCore


<?php

use Mockery as m;
use JasonLewis\Basset\FilterFactory;

class FilterFactoryTest extends PHPUnit_Framework_TestCase {

    public function tearDown()
    {
        m::close();
    }

    public function testMakeNewFilterInstance()
    {
        $filterFactory = $this->getFilterFactoryInstance();
        $resource = $this->getResourceMock();

        $filter = $filterFactory->make('FooFilter', null, $resource);

        $this->assertInstanceOf('JasonLewis\Basset\Filter', $filter);
    }

    public function testFilterClosureIsFired()
    {
        $filterFactory = $this->getFilterFactoryInstance();
        $resource = $this->getResourceMock();

        $fired = false;

        $filter = $filterFactory->make('FooFilter', function($filter) use (&$fired)
        {
            $fired = true;
        }, $resource);

        $this->assertTrue($fired);
    }

    public function testMakeExistingFilter()
    {
        $filterFactory = $this->getFilterFactoryInstance();
        $resource = $this->getResourceMock();

        $existingFilter = $this->getFilterMock();

        $filter = $filterFactory->make($existingFilter, null, $resource);

        $this->assertEquals($existingFilter, $filter);
    }

    public function testMakeNamedFilter()
    {
        $config = $this->getConfigMock();
        $config->shouldReceive('has')->once()->with('basset::filters.Foo')->andReturn(true);
        $config->shouldReceive('get')->once()->with('basset::filters.Foo')->andReturn('FooFilter');

        $filterFactory = new FilterFactory($config);
        $resource = $this->getResourceMock();

        $filter = $filterFactory->make('Foo', null, $resource);

        $this->assertEquals('FooFilter', $filter->getFilter());
    }

    public function testMakeNamedFilterWithCallback()
    {
        $fired = false;

        $config = $this->getConfigMock();
        $config->shouldReceive('has')->once()->with('basset::filters.Foo')->andReturn(true);
        $config->shouldReceive('get')->once()->with('basset::filters.Foo')->andReturn(array('FooFilter' => function($filter) use (&$fired)
        {
            $fired = true;
        }));

        $filterFactory = new FilterFactory($config);
        $resource = $this->getResourceMock();

        $filter = $filterFactory->make('Foo', null, $resource);

        $this->assertEquals('FooFilter', $filter->getFilter());
        $this->assertTrue($fired);
    }

    protected function getFilterFactoryInstance()
    {
        $config = $this->getConfigMock();
        $config->shouldReceive('has')->with('basset::filters.FooFilter')->andReturn(false);

        return new FilterFactory($config);
    }

    protected function getConfigMock()
    {
        return m::mock('Illuminate\Config\Repository');
    }

    protected function getFilterMock()
    {
        return m::mock('JasonLewis\Basset\Filter');
    }

    protected function getResourceMock()
    {
        return m::mock('JasonLewis\Basset\FilterableInterface');
    }

}

Test coverage for filter factory.

Test coverage for filter factory.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<?php
declare(strict_types = 1);

namespace Apha\Saga;

class AssociationValuesTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function sizeReturnsTheNumberOfItems()
    {
        $values = new AssociationValues([]);
        self::assertEquals(0, $values->size());

        $values->add(new AssociationValue('foo', 'bar'));
        self::assertEquals(1, $values->size());
    }

    /**
     * @test
     */
    public function clearEmptiesAllItems()
    {
        $values = new AssociationValues([]);
        $values->add(new AssociationValue('foo', 'bar'));

        self::assertEquals(1, $values->size());

        $values->clear();
        self::assertEquals(0, $values->size());
    }
}

Implement tests for association values.

Implement tests for association values.


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, 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 / System / Core / Class
 */

namespace PH7;

class SmsVerificationCore
{
    const PROFILE_ID_SESS_NAME = 'sms_verification_profile_id';
    const PHONE_NUMBER_SESS_NAME = 'user_phone_number';
}

Store useful constants in SmsVerification for sms-verification


<?php namespace Illuminate\Foundation\Support\Providers;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Stack\Builder as Stack;

class AppServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap any necessary services.
	 *
	 * @return void
	 */
	public function boot()
	{
		$router = $this->app['router'];

		foreach ($this->middleware as $key => $class)
		{
			$router->middleware($key, $class);
		}

		if (method_exists($this, 'stack'))
		{
			$this->app->call([$this, 'stack']);
		}
		else
		{
			$this->buildStack();
		}
	}

	/**
	 * Build the application stack based on the provider properties.
	 *
	 * @return void
	 */
	public function buildStack()
	{
		$this->app->stack(function(Stack $stack, Router $router)
		{
			return $stack
				->middleware($this->stack)
				->then(function($request) use ($router)
				{
					return $router->dispatch($request);
				});
			});
	}

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

}

Write a base app service provider.

Write a base app service provider.


<?php

namespace Marein\Nchan\Http;

use PHPUnit\Framework\TestCase;

class RequestTest extends TestCase
{
    /**
     * @test
     */
    public function itShouldBeCreatedWithItsValues(): void
    {
        $expectedUrl = 'http://localhost/my-url';
        $expectedHeaders = ['Accept' => 'application/json'];
        $expectedBody = 'my body';

        $request = new Request($expectedUrl, $expectedHeaders, $expectedBody);

        $this->assertEquals($expectedUrl, $request->url());
        $this->assertEquals($expectedHeaders, $request->headers());
        $this->assertEquals($expectedBody, $request->body());
    }

    /**
     * @test
     */
    public function itShouldBeCreatedWithEmptyBody(): void
    {
        $expectedUrl = 'http://localhost/my-url';
        $expectedHeaders = ['Accept' => 'application/json'];
        $expectedBody = '';

        $request = new Request($expectedUrl, $expectedHeaders);

        $this->assertEquals($expectedUrl, $request->url());
        $this->assertEquals($expectedHeaders, $request->headers());
        $this->assertEquals($expectedBody, $request->body());
    }
}

Add unit test for Request

Add unit test for Request


<?php

/*
 * Copyright 2014 郷.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Chigi\Bundle\ChijiBundle\Project;

use Chigi\Bundle\ChijiBundle\Util\StaticsManager;
use Chigi\Chiji\Project\ProjectConfig;
use Chigi\Chiji\Util\PathHelper;

/**
 * Description of SymfonyBundleProject
 *
 * @author 郷
 */
abstract class SymfonyBundleProjectConfig extends ProjectConfig {

    public function getReleaseRootPath() {
        $bundle_name = strtolower(preg_replace('#[A-Z][a-z0-9]#', '_$0', $this->getProjectName()));
        return PathHelper::searchRealPath(StaticsManager::getKernel()->getRootDir(), "../web/chiji/" . $bundle_name) . '/%s';
    }

    public function getReleaseRootUrl() {
        $bundle_name = strtolower(preg_replace('#[A-Z][a-z0-9]#', '_$0', $this->getProjectName()));
        return "{{ asset(\"chiji/" . $bundle_name . "/%s\") }}";
    }

    public function getProjectName() {
        return StaticsManager::getBundle()->getName();
    }

}

ADD Symfony Project quick Config.

ADD Symfony Project quick Config.

Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>


<?php

class Admin_Paging_Event_VenueDate extends Denkmal_Paging_Event_Abstract {

	/**
	 * @param DateTime                 $date
	 * @param Denkmal_Model_Venue|null $venue
	 */
	public function __construct(DateTime $date, Denkmal_Model_Venue $venue) {
		$date = clone $date;
		$startStamp = $date->getTimestamp();
		$date->add(new DateInterval('P1D'));
		$endStamp = $date->getTimestamp();
		$where = '`from` >= ' . $startStamp . ' AND `from` < ' . $endStamp . ' AND `venue` = ' . $venue->getId();

		$source = new CM_PagingSource_Sql('id', 'denkmal_model_event', $where);
		parent::__construct($source);
	}
}

Add admin paging for events on date in venue


<?php

  $meetup_key = "";

  $twitter_keys_and_tokens = array(
    "key"=>"",
    "key_secret"=>"",
    "token"=>"",
    "token_secret"=>""
  );

  $facebook_keys_and_tokens = array(
    "app_id"=>"",
    "app_secret"=>""
  );

  $slack_token = ""

?>

Create file to store all API keys and tokens


<?php
/**
 * @copyright Copyright (C) 2015-2017 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 */

use app\components\db\Migration;

class m171103_185043_gear2 extends Migration
{
    public function safeUp()
    {
        foreach ($this->getData() as $d) {
            $this->update('gear2', ['key' => $d[1]], ['key' => $d[0]]);
        }
    }

    public function safeDown()
    {
        foreach ($this->getData() as $d) {
            $this->update('gear2', ['key' => $d[0]], ['key' => $d[1]]);
        }
    }

    public function getData() : array
    {
        return [
            ['baby_jelly_shirt_tie', 'baby_jelly_shirt_and_tie'],
            ['shirt_tie', 'shirt_and_tie'],
            ['blue_black_squidkid_iv', 'blue_and_black_squidkid_iv'],
            ['red_black_squidkid_iv', 'red_and_black_squidkid_iv'],
        ];
    }
}

Update gear keys (have "&")

Update gear keys (have "&")

Signed-off-by: AIZAWA Hina <07c779d48779c322a7c5324109202f9012f7aebf@bouhime.com>


<?php

/**
 * This example demonstrates (in a very rudimentary way) how to create a case
 * using a JSON encoded request body.
 *
 * Please note, this example is for educational purposes only, and should not be
 * considered quality production code.
 */

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

use Trackops\Api\Client;

date_default_timezone_set('UTC');

// Create a new API Client using the customer subdomain, username, and api token
$api = new Client(getenv('TRACKOPS_API_SUBDOMAIN'), getenv('TRACKOPS_API_USERNAME'), getenv('TRACKOPS_API_TOKEN'));

// define the parameters we will use in our request
$request = ['casefile' => [
    'case_type_id' => 1,
    'client_id' => 4,
    'primary_contact_id' => 2,
    'case_region_id' => 1,
    'company_location_id' => 2,
    'created_on' => '2019-06-14',
    'due_on' => '2019-06-21',
    'reference_value_1' => 'ClaimNumber123',
    'reference_value_2' => 'AltClaimNumber456',
    'reference_value_3' => 'SomeOtherReference',
    'case_location' => 'Denver, CO',
    'budget_money' => 1500.00,
    'budget_hours' => 8,
    'notes' => 'Determine if the claimant is injured.',
    'scheduling_notes' => 'Schedule surveillance for 1 weekday and 1 weekend day.',
    'admin_notes' => 'Created by the API',
    'case_services_list' => [1, 2],
    'case_flags_list' => [1],
    'custom_fields' => [
        [
            'id' => 1,
            'value' => 'field 1 value here',
        ],
        [
            'id' => 2,
            'value' => 'field 2 value here',
        ],
    ],
    'subjects' => [
        [
            'subject_type_id' => 1,
            'is_primary' => true,
            'is_pinned' => true,
            'custom_fields' => [
                [
                    'id' => 1,
                    'value' => [
                        'first_name' => 'John',
                        'middle_name' => 'B',
                        'last_name' => 'Doe',
                    ],
                ],
                [
                    'id'  => 2,
                    'value' => 'Big John',
                ],
                [
                    'id'  => 3,
                    'value' => [
                        'address_1' => '123 Main Street',
                        'address_2' => '#456',
                        'city'  => 'Denver',
                        'state' => 'CO',
                        'zip' => '80202',
                        'country' => 'US',
                    ]
                ],
            ]
        ]
    ],
]];

// Call out to the API using a json encoded request body as defined
$response = $api->createRequest()->post('cases', json_encode($request));

echo $response."\n\n";
exit;

Add sample create case script

Add sample create case script


<?php
namespace Vfs\Stream\StreamWrapper;

use Vfs\Test\AcceptanceTestCase;

class SymlinkAcceptanceTest extends AcceptanceTestCase
{
    protected $tree = [
        'foo' => [
            'bar' => 'baz'
        ]
    ];

    public function testIsLink()
    {
        $factory = $this->fs->getNodeFactory();

        $file = $this->fs->get('/foo/bar');
        $this->fs->get('/')->add('symlink', $factory->buildFileLink($file));

        $this->assertTrue(is_link("$this->scheme:///symlink"));
    }

    public function testDirectoryLink()
    {
        $this->markTestSkipped('`symlink()` isn\'t supported by PHP Stream Wrappers');

        symlink("$this->scheme:///foo/bar", "$this->scheme:///symlink");

        $this->assertTrue(is_link("$this->scheme:///symlink"));
    }

    public function testFileLink()
    {
        $this->markTestSkipped('`symlink()` isn\'t supported by PHP Stream Wrappers');

        symlink("$this->scheme:///foo", "$this->scheme:///symlink");

        $this->assertTrue(is_link("$this->scheme:///symlink"));
    }
}

Add `symlink` and `is_link` acceptance tests


<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
        ));
    }
}

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
        ));
    }
}

Make use of getParameter() shortcut method


<?php namespace Modules\Dashboard\Composers;

use Illuminate\Contracts\View\View;

class WidgetViewComposer
{
    /**
     * @var array
     */
    private $subViews;

    /**
     * @param View $view
     */
    public function compose(View $view)
    {
        $view->with(['widgets' => $this->subViews]);
    }

    /**
     * Add the html of the widget view to the given widget name
     * @param string $name
     * @param string $view
     * @return $this
     */
    public function addSubview($name, $view)
    {
        $this->subViews[$name]['html'] = $view;

        return $this;
    }

    /**
     * Add the widget type to the given widget name
     * @param string $name
     * @param string $type
     * @return $this
     */
    public function addWidgetType($name, $type)
    {
        $this->subViews[$name]['type'] = $type;

        return $this;
    }
}

Add a widget view composer

Add a widget view composer


<?php

namespace Sensio\Bundle\FrameworkExtraBunde\Tests\Configuration;

class ConfigurationAnnotationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException RuntimeException
     */
    public function testUndefinedSetterThrowsException()
    {
        $this->getMockForAbstractClass('Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationAnnotation', array(
            array(
                'doesNotExists' => true,
            ),
        ));
    }
}

Add simple test for ConfigurationAnnotation


<?php
namespace EngineWorks\Slim;

use Slim\Interfaces\RouterInterface;
use EngineWorks\Templates\Plugin;

class SlimPlugin implements Plugin
{
    public function getCallablesTable()
    {
        return [
            'pathFor' => 'pathFor',
            'baseUrl' => 'baseUrl',
        ];
    }

    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var string
     */
    private $baseUrl;

    /**
     * SlimPlugin constructor.
     * @param RouterInterface $router
     * @param string $baseUrl
     */
    public function __construct(RouterInterface $router, $baseUrl)
    {
        if (! is_string($baseUrl)) {
            throw new \InvalidArgumentException("baseUrl must be a string or an Uri instance");
        }
        $this->router = $router;
        $this->baseUrl = $baseUrl;
    }

    public function pathFor($name, array $data = [], array $queryParams = [])
    {
        return $this->router->pathFor($name, $data, $queryParams);
    }

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

Add plugin to integrate with Slim and provide functions pathFor and baseUrl


<?php

namespace Illuminate\Encryption;

use RuntimeException;
use Illuminate\Support\ServiceProvider;

class EncryptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     *
     * @throws \RuntimeException
     */
    public function register()
    {
        $this->app->singleton('encrypter', function ($app) {
            $config = $app->make('config')->get('app');

            $key = $config['key'];

            $cipher = $config['cipher'];

            if (Encrypter::supported($key, $cipher)) {
                return new Encrypter($key, $cipher);
            } elseif (McryptEncrypter::supported($key, $cipher)) {
                return new McryptEncrypter($key, $cipher);
            } else {
                throw new RuntimeException('No supported encrypter found. The cipher and / or key length are invalid.');
            }
        });
    }
}

<?php

namespace Illuminate\Encryption;

use RuntimeException;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

class EncryptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('encrypter', function ($app) {
            $config = $app->make('config')->get('app');

            if (Str::startsWith($key = $config['key'], 'base64:')) {
                $key = base64_decode(substr($key, 7));
            }

            return $this->getEncrypterForKeyAndCipher($key, $config['cipher']);
        });
    }

    /**
     * Get the proper encrypter instance for the given key and cipher.
     *
     * @param  string  $key
     * @param  string  $cipher
     * @return mixed
     *
     * @throws \RuntimeException
     */
    protected function getEncrypterForKeyAndCipher($key, $cipher)
    {
        if (Encrypter::supported($key, $cipher)) {
            return new Encrypter($key, $cipher);
        } elseif (McryptEncrypter::supported($key, $cipher)) {
            return new McryptEncrypter($key, $cipher);
        } else {
            throw new RuntimeException('No supported encrypter found. The cipher and / or key length are invalid.');
        }
    }
}

Work on encryption service provider.

Work on encryption service provider.


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Event\TestRunner;

use PHPUnit\Event\AbstractEventTestCase;
use PHPUnit\Framework\Attributes\CoversClass;

#[CoversClass(ExecutionStarted::class)]
final class ExecutionStartedTest extends AbstractEventTestCase
{
    public function testConstructorSetsValues(): void
    {
        $telemetryInfo = $this->telemetryInfo();
        $testSuite     = $this->testSuiteValueObject();

        $event = new ExecutionStarted($telemetryInfo, $testSuite);

        $this->assertSame($telemetryInfo, $event->telemetryInfo());
    }

    public function testCanBeRepresentedAsString(): void
    {
        $telemetryInfo = $this->telemetryInfo();
        $testSuite     = $this->testSuiteValueObject();

        $event = new ExecutionStarted($telemetryInfo, $testSuite);

        $this->assertSame('Test Runner Execution Started (9001 tests)', $event->asString());
    }
}

Add tests for TestRunner\ExecutionStarted event


<?php

class Adyen_Payment_Model_Mysql4_Adyen_Event_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected function _construct()
    {
        $this->_init('adyen/adyen_event');
        $this->setItemObjectClass('adyen/event');
    }
}

[develop-2.1.1] +: Add adyen_event collection model to be able to query collections instead of querying the DB directly


<?php
namespace Inanimatt\SiteBuilder;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2012-05-28 at 14:28:43.
 */
class SiteBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var SiteBuilder
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new SiteBuilder;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @expectedException Inanimatt\SiteBuilder\Exception\ArgumentException
     */
    public function testRegisterRendererException()
    {
        $renderer = $this->getMock('Inanimatt\\SiteBuilder\\Renderer\\RendererInterface');
        $this->object->registerRenderer($renderer, 'invalid');
    }

    /**
     * @covers Inanimatt\SiteBuilder\SiteBuilder::getRenderers
     * @covers Inanimatt\SiteBuilder\SiteBuilder::registerRenderer
     */
    public function testGetSetRenderers()
    {
        $renderer = $this->getMock('Inanimatt\\SiteBuilder\\Renderer\\RendererInterface');
        $this->object->registerRenderer($renderer, array('test'));

        $result = $this->object->getRenderers();
        $this->assertArrayHasKey('test', $result);
        $this->assertEquals($result['test'], $renderer);

    }

    /**
     * @covers Inanimatt\SiteBuilder\SiteBuilder::setDefaultTemplate
     * @covers Inanimatt\SiteBuilder\SiteBuilder::getDefaultTemplate
     */
    public function testGetSetDefaultTemplate()
    {
        $this->object->setDefaultTemplate('test');
        $this->assertEquals('test', $this->object->getDefaultTemplate());
    }

    /**
     * @covers Inanimatt\SiteBuilder\SiteBuilder::setTemplatePath
     * @covers Inanimatt\SiteBuilder\SiteBuilder::getTemplatePath
     */
    public function testGetSetTemplatePath()
    {
        $this->object->setTemplatePath('test');
        $this->assertEquals('test', $this->object->getTemplatePath());
    }

    /**
     * @covers Inanimatt\SiteBuilder\SiteBuilder::renderSite
     * @todo   Implement testRenderSite().
     */
    public function testRenderSite()
    {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
          'This test has not been implemented yet.'
        );
    }

    /**
     * @covers Inanimatt\SiteBuilder\SiteBuilder::renderFile
     * @todo   Implement testRenderFile().
     */
    public function testRenderFile()
    {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
          'This test has not been implemented yet.'
        );
    }
}

Add (incomplete) unit tests for SiteBuilder class


<?php

namespace Sabre\VObject\Parser;

use
    Sabre\VObject;

class XmlTest extends \PHPUnit_Framework_TestCase {

    function testRFC6321Example1() {

        $xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0">
 <vcalendar>
  <properties>
   <calscale>
     <text>GREGORIAN</text>
   </calscale>
   <prodid>
    <text>-//Example Inc.//Example Calendar//EN</text>
   </prodid>
   <version>
     <text>2.0</text>
   </version>
  </properties>
  <components>
   <vevent>
    <properties>
     <dtstamp>
       <date-time>2008-02-05T19:12:24Z</date-time>
     </dtstamp>
     <dtstart>
       <date>2008-10-06</date>
     </dtstart>
     <summary>
      <text>Planning meeting</text>
     </summary>
     <uid>
      <text>4088E990AD89CB3DBB484909</text>
     </uid>
    </properties>
   </vevent>
  </components>
 </vcalendar>
</icalendar>
XML;

        $component = VObject\Reader::readXML($xml);
        $this->assertEquals(
            'BEGIN:VCALENDAR' . "\r\n" .
            'VERSION:2.0' . "\r\n" .
            'CALSCALE:GREGORIAN' . "\r\n" .
            'PRODID:-//Example Inc.//Example Calendar//EN' . "\r\n" .
            'BEGIN:VEVENT' . "\r\n" .
            'DTSTAMP:20080205T191224Z' . "\r\n" .
            'DTSTART:20081006' . "\r\n" .
            'SUMMARY:Planning meeting' . "\r\n" .
            'UID:4088E990AD89CB3DBB484909' . "\r\n" .
            'END:VEVENT' . "\r\n" .
            'END:VCALENDAR' . "\r\n",
            Vobject\Writer::write($component)
        );

    }
}

Add the Example 1 of the RFC6321 as a test.