<?php

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

class UpdateMessageAddExtraData extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('server_messages', function (Blueprint $table) {
            $table->boolean('deleted')->default(false)->after('message');
            $table->integer('edit_count')->default(0)->after('message');
        });
    }

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

Store deleted messages and keep track of edited count


<?php

class Stripe_ErrorTest extends Stripe_TestCase
{
  public function testCreation()
  {
    try {
      throw new Stripe_Error(
          "hello",
          500,
          "{'foo':'bar'}",
          array('foo' => 'bar')
      );
      $this->fail("Did not raise error");
    } catch (Stripe_Error $e) {
      $this->assertSame("hello", $e->getMessage());
      $this->assertSame(500, $e->getHttpStatus());
      $this->assertSame("{'foo':'bar'}", $e->getHttpBody());
      $this->assertSame(array('foo' => 'bar'), $e->getJsonBody());
    }
  }
}

Add PHPUnit test for Stripe_Error

Add PHPUnit test for Stripe_Error


<?php

namespace Tests\Concerns;

use App\Models\User;
use Illuminate\Support\Facades\Auth;

trait InteractsWithPermissions
{
    public function assertUserCan(User $user, string $permission): self
    {
        $this->assertTrue($user->can($permission));

        return $this;
    }

    public function assertUserCannot(User $user, string $permission): self
    {
        $this->assertTrue($user->cannot($permission));

        return $this;
    }

    public function assertUserCant(User $user, string $permission): self
    {
        return $this->assertUserCannot($user, $permission);
    }
}

Add test trait to check for user permissions


<?php if ( !defined( 'HABARI_PATH' ) ) { die('No direct access'); } ?>

	<?php

		if ( $previous = $post->descend() ) {
			?>

« <a href="<?php echo $previous->permalink; ?>" title="<?php echo _t( 'Go to previous post' ); ?>"><?php echo $previous->title; ?>

			<?php
		}

		if ( $next = $post->ascend() ) {
			?>

<a href="<?php echo $next->permalink; ?>" title="<?php echo _t( 'Go to next post' ); ?>"><?php echo $next->title; ?> »

			<?php
		}

	?>

Add the template for displaying post navigation controls.


<?php

class Mock_Requests_Transport implements Requests_Transport {
	public $requests = array();

	public function request( $url, $headers = array(), $data = array(), $options = array() ) {
		$this->requests[] = compact( 'url', 'headers', 'data', 'options' );

		return 'HTTP/1.1 418' . "\r\n"
			. 'Content-Type: water/leaf-infused' . "\r\n"
			. "\r\n\r\n"; // This last line is actually important or the request will error.
	}

	public function request_multiple( $requests, $options ) {
		throw new Exception( 'Method not implemented: ' . __METHOD__ );
	}

	public static function test() {
		return true;
	}
}

Add mock Requests transport transport.

Add mock Requests transport transport.


<?php

namespace MS\PHPMD\Tests\Unit\CleanCode;

use MS\PHPMD\Rule\CleanCode\MethodOneTryCatch;
use MS\PHPMD\Tests\Unit\AbstractApplyTest;

/**
 * Class MethodOneTryCatchTest
 *
 * @package MS\PHPMD\Tests\Unit\CleanCode
 */
class MethodOneTryCatchTest extends AbstractApplyTest
{
    /**
     * @covers MS\PHPMD\Rule\CleanCode\MethodOneTryCatch
     */
    public function testApplyNoMethodNode()
    {
        $node = \Mockery::mock('PHPMD\Node\ClassNode');

        $this->assertRule($node, 0);
    }

    /**
     * @covers MS\PHPMD\Rule\CleanCode\MethodOneTryCatch
     */
    public function testMoreTryStatements()
    {
        $node = $this->getMethodNode('TestClass', 'tryMore', [
            'TryStatement' => array_fill(0, 2, $this->getNode('try'))
        ]);

        $this->assertRule($node, 1);
    }

    /**
     * @covers MS\PHPMD\Rule\CleanCode\MethodOneTryCatch
     */
    public function testOneTryStatementWithCatchFinally()
    {
        $node = $this->getMethodNode('TestClass', 'tryMore', [
            'TryStatement' => array_fill(0, 1, $this->getNode('try')),
            'ScopeStatement' => array_merge(
                array_fill(0, 2, $this->getNode('catch')),
                array_fill(0, 1, $this->getNode('finally'))
            )
        ]);

        $this->assertRule($node, 0);
    }

    /**
     * @covers MS\PHPMD\Rule\CleanCode\MethodOneTryCatch
     */
    public function testOneTryStatementWithScopeStatements()
    {
        $tryNode = \Mockery::mock('PHPMD\AbstractNode');
        $tryNode->shouldReceive('isInstanceOf')->andReturn(true);

        $proxyNode = \Mockery::mock('PHPMD\AbstractNode');
        $proxyNode->shouldReceive('getImage')->andReturn('while');
        $proxyNode->shouldReceive('isInstanceOf')->andReturn(false);
        $proxyNode->shouldReceive('getParent')->andReturn($tryNode);

        $notAllowedNode = \Mockery::mock('PHPMD\AbstractNode');
        $notAllowedNode->shouldReceive('getImage')->andReturn('if');
        $notAllowedNode->shouldReceive('getParent')->andReturn(null);

        $allowedNode = \Mockery::mock('PHPMD\AbstractNode');
        $allowedNode->shouldReceive('getImage')->andReturn('if');
        $allowedNode->shouldReceive('getParent')->andReturn($proxyNode);

        $node = $this->getMethodNode('TestClass', 'tryMore', [
            'TryStatement' => array_fill(0, 1, $this->getNode('try')),
            'ScopeStatement' => [
                $allowedNode,
                $notAllowedNode
            ]
        ]);

        $this->assertRule($node, 1);
    }

    /**
     * @return MethodOneTryCatch
     */
    protected function getRule()
    {
        $rule =  new MethodOneTryCatch();
        $rule->addProperty('delimiter', ',');
        $rule->addProperty('allowedChildren', 'catch,finally');

        return $rule;
    }
}

Add unit test for try rule

Add unit test for try rule


<?php
namespace Networkteam\SentryClient\Command;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cli\CommandController;

class SentryCommandController extends CommandController
{
    /**
     * Test the sentry client
     */
    public function testCommand()
    {
        throw new \Exception('Testing the Sentry client', 1568995699);
    }
}

Task: Add simple command to test the sentry client

./flow sentry:test


<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App\Spending;

class SpendingTest extends TestCase {
    public function testFormattedAmount() {
        $spending = new Spending;

        $spending->user_id = 1;
        // $spending->tag_id = null;
        $spending->happened_on = date('Y-m-d');
        $spending->description = 'SpendingTest testExample';
        $spending->amount = 92;
        $spending->save();

        $this->assertEquals('92.00', $spending->formatted_amount);
    }
}

Add test for formatted_amount attribute of spendings


<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

class EditTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

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

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }
}

Test that you need to be authenticated to edit a tag


<?php
/**
 * Show all available columns in this list
 */
require_once '../../vendor/autoload.php';
$settings = include('../../../tests/Settings.php');

use Office365\Runtime\Auth\ClientCredential;
use Office365\SharePoint\ClientContext;
use Office365\SharePoint\ListItem;

$credentials = new ClientCredential($settings['ClientId'], $settings['ClientSecret']);
$siteUrl = $settings['TeamSiteUrl'];
$ctx = (new ClientContext($siteUrl))->withCredentials($credentials);

$list = $ctx->getWeb()->getLists()->getByTitle("Documents");
$items = $list->getItems()->top(1)->get()->executeQuery();
/** @var ListItem $item */
foreach ($items as $item) {
    var_dump(array_keys($item->toJson()));
}

Add example to obtain available fields of a list

This feels like a workaround


<?php
namespace Netlogix\JsonApiOrg\Http\Request;

/*
 * This file is part of the Netlogix.JsonApiOrg package.
 *
 * 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 TYPO3\Flow\Annotations as Flow;

/**
 * @Flow\Aspect
 * @Flow\Scope("singleton")
 */
class SetFormatByAcceptHeaderAspect {

	/**
	 * Sets the request format according th the given accept header.
	 *
	 * @Flow\After("method(TYPO3\Flow\Mvc\ActionRequest->setArguments())")
	 * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current joinpoint
	 */
	public function setRequestFormatByAcceptHeader(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {

		/** @var \TYPO3\Flow\Mvc\ActionRequest $actionRequest */
		$actionRequest = $joinPoint->getProxy();

		/**
		 * The Accept header should be the only one to determine which resulting
		 * data format the client is able to understand. But since some JS libs
		 * do send Accept XML but Content-Type Json even when the expect to process
		 * jsonapi.org format data we care about both, the Accept header as well
		 * as the Content-Type header.
		 */
		foreach (array('Accept', 'Http-Accept', 'Content-Type') as $fieldName) {
			$headerValue = $actionRequest->getHttpRequest()->getHeader($fieldName);
			foreach (array('application/json', 'application/vnd.api+json') as $acceptableValue) {
				if (strpos($headerValue, $acceptableValue) !== FALSE) {
					$actionRequest->setFormat('json');
					return;
				}
			}
		}
	}

}

Set format by Accept header

Set format by Accept header


<?php

/**
 * This file is part of CodeIgniter 4 framework.
 *
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace CodeIgniter\Database\Live\OCI8;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;

/**
 * @group DatabaseLive
 *
 * @internal
 */
final class LastInsertIDTest extends CIUnitTestCase
{
    use DatabaseTestTrait;

    protected $refresh = true;
    protected $seed    = 'Tests\Support\Database\Seeds\CITestSeeder';

    public function testGetInsertIDWithInsert()
    {
        $jobData = [
            'name'        => 'Grocery Sales',
            'description' => 'Discount!',
        ];

        $this->db->table('job')->insert($jobData);
        $actual = $this->db->insertID();

        $this->assertSame($actual, 5);
    }

    public function testGetInsertIDWithQuery()
    {
        $this->db->query('INSERT INTO "db_job" ("name", "description") VALUES (?, ?)', ['Grocery Sales', 'Discount!']);
        $actual = $this->db->insertID();

        $this->assertSame($actual, 5);
    }

    public function testGetInsertIDWithHasCommentQuery()
    {
        $sql = <<<SQL
-- INSERT INTO "db_misc" ("key", "value") VALUES ('key', 'value')
/* INSERT INTO "db_misc" ("key", "value") VALUES ('key', 'value') */
INSERT /* INTO "db_misc" */ INTO "db_job"  ("name", "description") VALUES (' INTO "abc"', ?)
SQL;
        $this->db->query($sql, ['Discount!']);
        $actual = $this->db->insertID();

        $this->assertSame($actual, 5);
    }
}

Add a test for lastInsertId.

test: Add a test for lastInsertId.


<?php
/**
 * @author Christoph Bessei
 */

namespace BIT\TYPO3\Install\Task;

use TYPO3\Surf\Domain\Model\Application;
use TYPO3\Surf\Domain\Model\Deployment;
use TYPO3\Surf\Domain\Model\Node;
use TYPO3\Surf\Domain\Model\Task;
use TYPO3\Surf\Domain\Service\ShellCommandServiceAwareInterface;
use TYPO3\Surf\Domain\Service\ShellCommandServiceAwareTrait;

class RsyncConfigurationTask extends Task implements ShellCommandServiceAwareInterface
{
    use ShellCommandServiceAwareTrait;

    /**
     * Executes this task
     *
     * @param \TYPO3\Surf\Domain\Model\Node $node
     * @param \TYPO3\Surf\Domain\Model\Application $application
     * @param \TYPO3\Surf\Domain\Model\Deployment $deployment
     * @param array $options
     * @return void
     */
    public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {

        $sharedPath = $application->getSharedPath();
        $sharedConfigurationPath = escapeshellarg($sharedPath . '/Configuration/');

        $releasePath = $deployment->getApplicationReleasePath($application);
        $targetConfigurationPath = escapeshellarg($releasePath . '/config/');

        $rsyncWithoutOverwriteCommand = 'rsync -r --ignore-existing --include=*.php ';
        $commands = [
            'cd ' . $sharedConfigurationPath,
            $rsyncWithoutOverwriteCommand . ' ' . $sharedConfigurationPath . ' ' . $targetConfigurationPath,
        ];

        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }

    /**
     * Simulate this task
     *
     * @param Node $node
     * @param Application $application
     * @param Deployment $deployment
     * @param array $options
     * @return void
     */
    public function simulate(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $this->execute($node, $application, $deployment, $options);
    }
}

Add TYPO3 Surf Task which rsync config files from $sharedPath/Configuration/ to $currentReleasePath/config/. This task does not overwrite existing files


<?php

use VotingApp\LocalizedDate;

class LocalizedDateTest extends TestCase
{

    /**
     * Verify that US-style MM/DD/YYYY dates can be parsed.
     * @test
     */
    public function testMMDDYYYYDates()
    {
        $date = new LocalizedDate('1/2/1990', 'US');

        $this->assertInstanceOf('VotingApp\LocalizedDate', $date);

        $this->assertSame(631238400, $date->getTimestamp());
    }

    /**
     * Verify that international-style DD/MM/YYYY dates can be parsed.
     * @test
     */
    public function testDDMMYYYYDates()
    {
        $date = new LocalizedDate('2/1/1990', 'GB');

        $this->assertInstanceOf('VotingApp\LocalizedDate', $date);

        $this->assertSame(631238400, $date->getTimestamp());
    }

    /**
     * Test that other non-standard strtotime() formats
     * still work as expected.
     * @test
     */
    public function testOtherFormats()
    {
        $date = new LocalizedDate('January 2nd 1990', 'US');
        $this->assertSame(631238400, $date->getTimestamp());

        $date2 = new LocalizedDate('January 2, 1990', 'US');
        $this->assertSame(631238400, $date2->getTimestamp());

        $date3 = new LocalizedDate('2 January 1990', 'US');
        $this->assertSame(631238400, $date3->getTimestamp());
    }

    /**
     * Test that given strings are validated/invalidated.
     * @test
     */
    public function testValidate()
    {
        $this->assertTrue(LocalizedDate::validate('1/25/1990', 'US'));

        $this->assertTrue(LocalizedDate::validate('1-25-1990', 'US'));

        $this->assertTrue(LocalizedDate::validate('1.25.1990', 'US'));

        $this->assertTrue(LocalizedDate::validate('25/1/1990', 'GB'));

        $this->assertTrue(LocalizedDate::validate('25-1-1990', 'GB'));

        $this->assertFalse(LocalizedDate::validate('25/1/1990', 'US'));

        $this->assertTrue(LocalizedDate::validate('January 2nd 1990', 'US'));
    }

}

Add unit tests for LocalizedDate.

Add unit tests for LocalizedDate.


<?php

namespace Hodor\JobQueue;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass Hodor\JobQueue\QueueManager
 */
class QueueManagerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var QueueManager
     */
    private $queue_manager;

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

        $this->queue_manager = new QueueManager(new Config(__FILE__, [
            'superqueue' => ['database' => ['type' => 'testing']],
        ]));
    }

    /**
     * @covers ::__construct
     * @covers ::getSuperqueue
     * @covers ::<private>
     */
    public function testSuperqueueIsReused()
    {
        $this->assertSame(
            $this->queue_manager->getSuperqueue(),
            $this->queue_manager->getSuperqueue()
        );
    }

    /**
     * @covers ::__construct
     * @covers ::getBufferQueueFactory
     * @covers ::<private>
     */
    public function testBufferQueueFactoryIsReused()
    {
        $this->assertSame(
            $this->queue_manager->getBufferQueueFactory(),
            $this->queue_manager->getBufferQueueFactory()
        );
    }

    /**
     * @covers ::__construct
     * @covers ::getWorkerQueueFactory
     * @covers ::<private>
     */
    public function testWorkerQueueFactoryIsReused()
    {
        $this->assertSame(
            $this->queue_manager->getWorkerQueueFactory(),
            $this->queue_manager->getWorkerQueueFactory()
        );
    }
}

Test the basics of QueueManager

Test the basics of QueueManager


<?php

class ApplicationTest extends PHPUnit_Framework_TestCase
{
    public function testName()
    {
        $application = new Silexor\Application();

        $this->assertEquals('silexor', $application->getName());
        $this->assertTrue($application->has('project:generate'));
    }
}

Add test for Application class (others to come :))


<?php

/*
 * @author Etienne Lamoureux <etienne.lamoureux@crystalgorithm.com>
 * @copyright 2014 Etienne Lamoureux
 * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 */

namespace Crystalgorithm\PhpJsonIterator\Iterators;

use PHPUnit_Framework_TestCase;
use Crystalgorithm\PhpJsonIterator\JsonIteratorFactory;

final class JsonIteratorTest extends PHPUnit_Framework_TestCase {

    const FLAT_JSON_OBJECT_AS_STRING = '{"foo":"bar","fizz":"buzz"}';
    const NESTED_JSON_OBJECT_AS_STRING = '{"foo":"bar","fizz":{"id":1,"nested":true}}';

    protected $counter;

    protected function setUp() {
        $this->counter = 0;
    }

    public function testGivenFlatJsonObjectsThenParseOneByOne() {
        $json = $this::buildTestJson(5, self::FLAT_JSON_OBJECT_AS_STRING);
        $iterator = JsonIteratorFactory::buildJsonIterator($json);

        $this->goThroughIterator($iterator);

        $this->assertEquals(5, $this->counter);
    }

    protected static function buildTestJson($nbObjects, $jsonObject) {
        $jsonObjects = array_fill(0, $nbObjects, $jsonObject);
        $json = implode(",", $jsonObjects);

        return $json;
    }

    protected function goThroughIterator($iterator) {
        foreach ($iterator as $parsedJsonObject) {
            // Here you can do something with $parsedJsonObject as an array,
            // has it had gone through json_decode already
            $this->counter++;
        }
    }

}

Implement trivial case for JsonIterator

Implement trivial case for JsonIterator


<?php

namespace Robin\AddressBookBundle\Controller;

class Controller extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
{
    /**
     * Make the method overrideable with the ?method= query string
     * as suggested in: http://info.apigee.com/Portals/62317/docs/web%20api.pdf
     */
    protected function httpMethod()
    {
        return $this->getRequest()->query->get('method', $this->getRequest()->getMethod());
    }

    /**
     * Return a Response from a twig template of the correct format
     *
     * @param string $name
     * @return Symfony\Component\HttpFoundation\Response
     */
    protected function templateResponse($name, array $data = array())
    {
        $format = $this->getRequest()->get('_format');

        return $this->render('RobinAddressBookBundle:' . $name . '.' . $format . '.twig', $data);
    }
}

Extend the controller to provide HTTP method and template parsing


<?php

namespace DevGroup\AdminUtils\traits;

use yii\db\ActiveRecord;

trait FetchModels
{
    /**
     * Workaround to have ability use Model::load() method instead assigning values from request by hand
     *
     * @param array $params
     * @param string $fromClass class name
     * @param ActiveRecord $toModel
     * @return array
     */
    public static function fetchParams($params, $fromClass, $toModel)
    {
        if (true === empty($params)
            || false === class_exists($fromClass)
            || false === $toModel instanceof ActiveRecord
        ) {
            return [];
        }
        $outParams = [];
        $toClass = get_class($toModel);
        $fromName = array_pop(explode('\\', $fromClass));
        $toName = array_pop(explode('\\', $toClass));
        if (true === isset($params[$fromName])) {
            foreach ($params[$fromName] as $key => $value) {
                if (true === in_array($key, $toModel->attributes(), true)) {
                    $outParams[$toName][$key] = $value;
                }
            }
        }
        return $outParams;
    }
}

Move fetchModels helper to trait

Move fetchModels helper to trait


<?php
$question = trim($_REQUEST['question']);
if($_REQUEST['action'] == 'Preview Vote')
{
	$container = create_container('skeleton.php','vote_create.php');
	$container['PreviewVote'] = $question;
	$container['Days'] = $_REQUEST['days'];
	forward($container);
}
$option = trim($_REQUEST['option']);
if($_REQUEST['action'] == 'Preview Option')
{
	$container = create_container('skeleton.php','vote_create.php');
	$container['PreviewOption'] = $option;
	$container['VoteID'] = $_REQUEST['vote'];
	forward($container);
}

if($_REQUEST['action'] == 'Create Vote')
{
	$end = TIME+86400*$_REQUEST['days'];

	// put the msg into the database
	$db->query('INSERT INTO voting (question, end) VALUES('.$db->escapeString($question).','.$db->escapeNumber($end).')');
}
else if($_REQUEST['action'] == 'Add Option')
{
	$voteID = $_REQUEST['vote'];

	// put the msg into the database
	$db->query('INSERT INTO voting_options (vote_id, text) VALUES('.$db->escapeNumber($voteID).','.$db->escapeString($option).')');
}
forward(create_container('skeleton.php', 'vote_create.php'))

?>

<?php
$question = trim($_REQUEST['question']);
if($_REQUEST['action'] == 'Preview Vote')
{
	$container = create_container('skeleton.php','vote_create.php');
	$container['PreviewVote'] = $question;
	$container['Days'] = $_REQUEST['days'];
	forward($container);
}
$option = trim($_REQUEST['option']);
if($_REQUEST['action'] == 'Preview Option')
{
	$container = create_container('skeleton.php','vote_create.php');
	$container['PreviewOption'] = $option;
	$container['VoteID'] = $_REQUEST['vote'];
	forward($container);
}

if($_REQUEST['action'] == 'Create Vote')
{
	if(empty($question))
		create_error('You have to specify a vote message.');
	if(empty($_REQUEST['days']))
		create_error('You have to specify the amount of time to run the vote for.');
	$end = TIME+86400*$_REQUEST['days'];

	// put the msg into the database
	$db->query('INSERT INTO voting (question, end) VALUES('.$db->escapeString($question).','.$db->escapeNumber($end).')');
}
else if($_REQUEST['action'] == 'Add Option')
{
	if(empty($option))
		create_error('You have to specify an option message.');
	if(empty($_REQUEST['vote']))
		create_error('You have to select a vote to add the option to.');

	// put the msg into the database
	$db->query('INSERT INTO voting_options (vote_id, text) VALUES('.$db->escapeNumber($_REQUEST['vote']).','.$db->escapeString($option).')');
}
forward(create_container('skeleton.php', 'vote_create.php'))

?>

Add extra validation for vote creation.

Add extra validation for vote creation.


<?php

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

class CreatePairingTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pairing', function (Blueprint $table) {
            $table->integer("male", false, true);
            $table->integer("female", false, true);
            $table->decimal("compatibility", 6,3);
            $table->dateTime('created_at');
            $table->dateTime('updated_at');
        });

        Schema::table('pairing', function (Blueprint $table) {
            $table->foreign("male")->references("id")->on("animal");
            $table->foreign("female")->references("id")->on("animal");
            $table->unique(["male", "female"]);
        });
    }

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

Create table for holding the pairing calculations


<?php
	namespace Bolt\Traits;

	trait Outputable
	{
		public function toJson()
		{
			$results = null;
			$properties = $this->getProperties();

			foreach ($properties as $property)
			{
				$value = $this->{$property->name};

				if ($value !== null)
				{
					if (is_array($value))
					{
						foreach ($value as &$element)
						{
							if (is_object($element) && get_class($element) != "stdClass")
							{
								$element = json_decode($element->toJson());
							}
						}

						if ($value === array())
						{
							$value = null;
						}
					}

					if (is_object($value))
					{
						if (get_class($value) != "stdClass")
						{
							$value = json_decode($value->toJson());
						}
					}

					if ($value !== null)
					{
						$results[$property->name] = $value;
					}
				}
			}

			return json_encode($results);
		}
	}
?>

Add outputable trait with toJson method

Add outputable trait with toJson method


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

/**
 * Add custom image output converter for testing
 */
return [
    'outputConverters' => [
        'Imbo\Image\OutputConverter\Webp',
    ],
];

Add behat test configuration for output converters


<?php

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

declare(strict_types=1);

namespace ActiveCollab\Payments\TaxRates;

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

Add tax ID validator interface

Add tax ID validator interface


<?php
/**
 * Setup autoloading
 */

// Setup autoloading for ZendTest assets
require_once __DIR__ . '/../library/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(
    array(
            Zend\Loader\StandardAutoloader::LOAD_NS => array(
                'ZendTest' => __DIR__ . '/ZendTest',
            ),
    ));
$loader->register();

if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    include_once __DIR__ . '/../vendor/autoload.php';
} else {
    // if composer autoloader is missing, explicitly add the ZF library path
    $loader->registerNamespace('Zend', __DIR__ . '/../library/Zend');
}

<?php
/**
 * Setup autoloading
 */

if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    include_once __DIR__ . '/../vendor/autoload.php';
} else {
    // if composer autoloader is missing, explicitly add the ZF library path
    require_once __DIR__ . '/../library/Zend/Loader/StandardAutoloader.php';
    $loader = new Zend\Loader\StandardAutoloader(
        array(
             Zend\Loader\StandardAutoloader::LOAD_NS => array(
                 'Zend'     => __DIR__ . '/../library/Zend',
                 'ZendTest' => __DIR__ . '/ZendTest',
             ),
        ));
    $loader->register();
}

[Tests] Use Zend_Autoloader when Composer's autoloader is not present.

Note: If your tests are failing after this patch probably you need to do "php composer.phat update" to update Composer's autoloader with the new lists of namespaces


<?php

namespace Tests\Feature;

use App\User;
use App\Space;
use App\Tag;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase {
    public function testUnauthorizedUserCantEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(403);
    }
}

Create (feature) test for tags

Create (feature) test for tags


<?php

namespace Tests\Unit;

use App\Helper;
use PHPUnit\Framework\TestCase;

class HelperTest extends TestCase
{
    public function testRawNumberConversion(): void
    {
        $cases = [
            [
                'rawNumber' => 9.70,
                'expected' => 970
            ],
            [
                'rawNumber' => 0.01,
                'expected' => 1
            ],
            [
                'rawNumber' => 123,
                'expected' => 12300
            ],
            [
                'rawNumber' => 9.99,
                'expected' => 999
            ]
        ];

        foreach ($cases as $case) {
            $result = Helper::rawNumberToInteger($case['rawNumber']);

            $this->assertEquals($case['expected'], $result);
        }
    }
}

Create test for Helper class

Create test for Helper class


<?php

use yii\db\Schema;
use yii\db\Migration;

class m151016_000058_create_jobs_table extends Migration
{
    public function up()
    {
        $this->createTable('jobs',[
            'id' => Schema::TYPE_PK,
            'date' => Schema::TYPE_TIMESTAMP,
            'started' => Schema::TYPE_DATETIME,
            'completed' => Schema::TYPE_DATETIME,
            'status' => Schema::TYPE_STRING,
            'type' => Schema::TYPE_STRING,
            'arguments' => Schema::TYPE_TEXT,
        ]);
    }

    public function down()
    {
        $this->dropTable('jobs');
    }
}

Add migration for jobs tables in the database

This creates the schema for a jobs table.
To be used for storing jobs that will be executed asynchronously.


<?php
/**
*    Copyright (C) 2014 Ibrahim Yusuf <ibrahim7usuf@gmail.com>.
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/
class Activity extends Eloquent
{
	function log($activity)
	{
		DB::table('activities')->insert(array(
			'message' => $activity,
			'user_id' => Auth::user()->id
		));
	}
}

<?php
/**
*    Copyright (C) 2014 Ibrahim Yusuf <ibrahim7usuf@gmail.com>.
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/
class Activity extends Eloquent
{
	function log($activity)
	{
		$act = new Activity;
		$act->message = $activity;
		$act->user_id = Auth::user()->id;
		$act->save();
	}
}

Change fluent to eloquent to fix timestamps


<?php

    /**
     * Vendor Class
     *
     * Manage vendor and can automatically detect vendor.
     *
     * @package Core
     */
    class Vendor
    {
        public function __construct()
        {
            $dirs = scandir(BASE_PATH);
            $length = count($dirs);
            $arr = array();
            for ($i=0;$i<count($dirs);$i++)
            {
                if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
                    is_dir($dirs[$i]))
                {
                    $arr[] = $dirs[$i];
                }
            }

            $config =& loadClass('Config', 'Core');
            $config->save('Vendor', $arr);
        }
    }

?>

Add vendor class to automatically manage vendor


<?php

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

class InsertTurkishLiraIntoCurrenciesTable extends Migration
{
    public function up(): void
    {
        DB::table('currencies')->insert([
            'name' => 'Turkish lira',
            'symbol' => 'TRY',
            'iso' => 'TRY'
        ]);
    }

    public function down(): void
    {
        //
    }
}

Insert Turkish lira into currencies table


<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Calls the given Statusnet IM architecture enqueuing method to enqueue
 * a new incoming message
 *
 * @category  Phergie
 * @package   Phergie_Plugin_Statusnet_Callback
 * @author    Luke Fitzgerald <lw.fitzgerald@googlemail.com
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

class Phergie_Plugin_Statusnet_Callback extends Phergie_Plugin_Abstract {
    /**
    * Callback details
    *
    * @var array
    */
    protected $callback;

    /**
    * Load callback from config
    */
    public function onLoad() {
        $callback = $this->config['statusnet_callback.callback'];
        if (is_callable($callback)) {
            $this->callback = $callback;
        } else {
            $this->callback = NULL;
        }
    }

    /**
     * Passes incoming messages to StatusNet
     *
     * @return void
     */
    public function onPrivmsg() {
        if ($this->callback !== NULL) {
            $event = $this->getEvent();
            $source = $event->getSource();
            $message = trim($event->getText());

            call_user_func($this->callback, array('sender' => $source, 'message' => $message);
        }
    }
}

Add StatusNet Phergie plugin to pass messages received to IM architecture


<?php
/**
* Template file for DamnIt's pretty error output.
* Check the $v global variable (stdClass) for what's available
* to work with.
* @var $v
*/
?>
<!DOCTYPE html>

    <title>Damn it! - An error ocurred.</title>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/2.1.0/normalize.css">

There was an error

        But it's gone now.

Add skeleton for PrettyPage handler template


<?php
namespace PhpSlackBot\Command;

class CountCommand extends BaseCommand {

    private $count = 0;

    protected function configure() {
        $this->setName('count');
    }

    protected function execute($message, $context) {
        $this->send($this->getCurrentChannel(), null, $this->count);
        $this->count++;
        return $response;
    }

}

Add "count" command as example command

Add "count" command as example command


<?php  namespace Phonebook\Resolvers;

class EloquentTenantResolver implements TenantResolver {

    protected $tenant;

    protected $config;

    public function __construct(Repository $config, Application $app, Request $request)
    {
        $this->config = $config;

        $this->tenant = $app->make($this->config->get('phonebook.tenant.model'))->where($this->config->get('phonebook.tenant.database.column', 'slug'),
            $request->route($this->config->get('phonebook.tenant.route.parameter', 'tenant'))
        )->first();
    }

    /**
     * Get the ID for the tenant the request is directed to.
     *
     * @return integer
     */
    public function getTenantId()
    {
        return $this->tenant->id;
    }
}

Add eloquent tenant resolver implementation


<?php
$currentPage = "link_4";
require_once("config.php");
?>
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>AdaptiveNav v2.0 - Responsive Navigation Menu</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php echo "\t\n"; ?>

    <link rel="stylesheet" type="text/css" href="<?php echo $config['paths']['css']['expanded'] . $config['info']['cacheVer']; ?>">

    <?php require_once(TEMPLATES_PATH . "/header.php"); ?>

Link 4

    <?php require_once(TEMPLATES_PATH . "/loadScripts.php"); ?>

Add example page for link 4

Add example page for link 4


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for sort Mimic library function.
 *
 * @since 0.1.0
 */
class SortFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(false, F\sortable(), array(4, 2, 1, 3), array(1, 2, 3, 4)),
			array(true, F\sortable(), array(4, 2, 1, 3), array(2 => 1, 1 => 2, 3 => 3, 0 => 4)),
			array(false, 'natcasesort',
				array('2', '1', 'world', 'hello'),
				array('1', '2', 'hello', 'world')
			),
			array(true, 'natcasesort',
				array('2', '1', 'world', 'hello'),
				array(2 => '1', 0 => '2', 4 => 'hello', 3 => 'world')
			),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\sort
	 */
	public function testResults($preserveKeys, $callback, $collection, $expected) {
		$this->assertEquals($expected, F\sort($collection, $callback, $preserveKeys));
	}
}

Add sort function test suite.

Add sort function test suite.


<?php

use Clx\Xms\Api as XA;

class PagesTest extends PHPUnit\Framework\TestCase
{

    public function testIterationOverPages()
    {
        $results = [
            ["element0", "element1"],
            ["element2"],
            []
        ];

        $pages = new XA\Pages(
            function ($pageno) use ($results) {
                $page = new XA\Page();

                $page->page = $pageno;
                $page->content = $results[$pageno];
                $page->size = count($results[$pageno]);
                $page->totalSize = 3;

                return $page;
            }
        );

        foreach ($pages as $pageno => $page) {
            $this->assertSame($results[$pageno], $page->content);

            foreach ($page as $k => $v) {
                $this->assertSame($results[$pageno][$k], $v);
            }
        }
    }

}

?>

Add test of Pages class

Add test of Pages class


<?php

require_once("../class/config.php");

$fields = array (
    "name" => array ("request", "string", ""),
);
getFields($fields);

if (!empty($name)) {
  $error = "";

  $borgbackup->mount($name);

  include("borgbackup_list.php");
  exit();
}

Enable mount action from panel

Enable mount action from panel

* Account can mount his archive backup


<?php

namespace Chromabits\Illuminated\Database\Migrations;

use Exception;
use Illuminate\Database\Schema\Blueprint;

/**
 * Class TableMigration
 *
 * A base migration for migrations that simply create/drop a table. Applications
 * usually have one or more of this kind. This base class simply reduces the
 * amount of repeated code and allows the table name to be defined in
 * declarative way.
 *
 * If you need to modify columns or perform other operations, please consider
 * using a different base migration class.
 *
 * To use this migration class:
 * - Extend it.
 * - Set the name of the table by overriding the `$name` property.
 * - Implement the `create(Blueprint $table)` method.
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Database\Migrations
 */
abstract class TableMigration extends BaseMigration
{
    /**
     * Name of the table.
     *
     * @var string
     */
    protected $name = null;

    /**
     * Create the table schema.
     *
     * @param Blueprint $table
     *
     * @return mixed
     */
    abstract protected function create(Blueprint $table);

    /**
     * Perform some sanity checks on the migration.
     *
     * @throws Exception
     */
    final protected function validate()
    {
        if ($this->name === null) {
            throw new Exception(
                'Invalid table name in migration: ' . static::class
            );
        }
    }

    /**
     * Run the migration.
     *
     * @throws Exception
     */
    final public function up()
    {
        $this->validate();

        $this->builder->create($this->name, function (Blueprint $table) {
            $this->create($table);
        });
    }

    /**
     * Rollback the migration.
     *
     * @throws Exception
     */
    final public function down()
    {
        $this->validate();

        $this->builder->drop($this->name);
    }
}

Add base table migration class

Add base table migration class


<?php

namespace Frontend\Modules\Profiles\Tests\Engine;

use Common\WebTestCase;
use DateTime;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use SpoonDatabase;

final class AuthenticationTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client);
    }

    public function testOldSessionCleanUp()
    {
        $dateWithinAMonthAgo = new DateTime('-1 week');
        $dateOverAMonthAgo = new DateTime('-2 months');

        /** @var SpoonDatabase $database */
        $database = FrontendModel::get('database');

        $database->insert(
            'profiles_sessions',
            [
                [
                    'session_id' => '0123456789',
                    'profile_id' => 1,
                    'secret_key' => 'NotSoSecretNowIsIt',
                    'date' => $dateWithinAMonthAgo->format('Y-m-d H:i:s'),
                ],
                [
                    'session_id' => '1234567890',
                    'profile_id' => 1,
                    'secret_key' => 'WeNeedToTalk',
                    'date' => $dateOverAMonthAgo->format('Y-m-d H:i:s'),
                ],
            ]
        );

        $this->assertEquals('2', $database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));

        Authentication::cleanupOldSessions();

        $this->assertEquals('1', $database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
    }
}

Test the cleanup of old sessions

Test the cleanup of old sessions


<?php

namespace GrowthOptimized\OAuth2\Client\Provider;

/**
 * Class OptimizelyX
 * @package GrowthOptimized\OAuth2\Client\Provider
 */
class OptimizelyX extends Optimizely
{
    /**
     * Api domain
     *
     * @var string
     */
    protected $apiDomain = 'https://api.optimizely.com/v2';
}

Add a class to support Optimizely X

Add a class to support Optimizely X


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

namespace Zend\Mvc\Service;

use Zend\Console\Console;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mvc\View\Console\ViewManager as ConsoleViewManager;
use Zend\Mvc\View\Http\ViewManager as HttpViewManager;

/**
 * @category   Zend
 * @package    Zend_Mvc
 * @subpackage Service
 */
class ViewManagerFactory implements FactoryInterface
{
    /**
     * Create and return a request instance, according to current environment.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return \Zend\Stdlib\Message
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        if (Console::isConsole()) {
            return new ConsoleViewManager();
        }

        return new HttpViewManager();
    }
}

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

namespace Zend\Mvc\Service;

use Zend\Console\Console;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mvc\View\Console\ViewManager as ConsoleViewManager;
use Zend\Mvc\View\Http\ViewManager as HttpViewManager;

/**
 * @category   Zend
 * @package    Zend_Mvc
 * @subpackage Service
 */
class ViewManagerFactory implements FactoryInterface
{
    /**
     * Create and return a request instance, according to current environment.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return HttpViewManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        if (Console::isConsole()) {
            return new ConsoleViewManager();
        }

        return new HttpViewManager();
    }
}

Resolve inconsistent return statements in phpDoc


<?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;

use Fsv\TypographyBundle\Form\DataTransformer\TypographyTransformer;
use Symfony\Component\Form\Test\TypeTestCase;

class TypographyTransformerTest extends TypeTestCase
{
    public function testTransformationDuringReverseTransform()
    {
        $input = 'Типограф - это здорово!';
        $output = 'Типограф — это здорово!';

        $typograph = $this->getMock('Fsv\TypographyBundle\Typograph\TypographInterface');
        $typograph
            ->expects($this->any())
            ->method('apply')
            ->with($input)
            ->will($this->returnValue($output))
        ;

        $typographyTransformer = new TypographyTransformer($typograph);

        $this->assertEquals($output, $typographyTransformer->reverseTransform($input));
        $this->assertEquals($input, $typographyTransformer->transform($input));
    }
}

Add test for data transformer

Add test for data transformer


<?php

/**
 * @package    Grav\Common\Twig
 *
 * @copyright  Copyright (c) 2015 - 2021 Trilby Media, LLC. All rights reserved.
 * @license    MIT License; see LICENSE file for details.
 */

namespace Grav\Common\Twig;

use Grav\Common\Twig\Extension\GravExtension;

/**
 * Class TwigExtension
 * @package Grav\Common\Twig
 * @deprecated 1.7 Use GravExtension instead
 */
class TwigExtension extends GravExtension
{
}

Add back alias for moved class

Add back alias for moved class


<?php

namespace Nitrapi\Services\Gameservers\Games;

class TS3Musicbot extends Game
{
    protected $game = "ts3musicbot";

    /**
     * Reinstalls the TS3Musicbot
     *
     * @return bool
     */
    public function doReinstall() {
        $url = "services/" . $this->service->getId() . "/gameservers/games/ts3musicbot/reinstall";
        $this->service->getApi()->dataPost($url);

        return true;
    }

}

Update Fri Feb 5 11:51:56 CET 2016

Update Fri Feb  5 11:51:56 CET 2016


<?php

//*****************************************************************
//	Database Configuration
//*****************************************************************

define('HOST', '');
define ('USER', '');
define ('PWD', '');
define ('DB', '');

class Database_DBConn {

	private static $connection;		//	the connection itself

	private function __construct() { }

	public static function getConnection() {
		if ( empty( self::$connection ) ) {
			try {
				self::$connection =  new mysqli( HOST, USER, PWD, DB );
			} catch ( Exception $e ) {
				die( "I'm sorry. The database is temporarily down. Please try again later.\n" );
			}
		}
		return self::$connection;
	}

}

?>

Add singleton DB connection class to repo.


<?php
/**
 * Search class for frontend users to search for events.
 *
 *
 * @package UNL_UCBCN_Frontend
 * @author Brett Bieber
 */

require_once 'UNL/UCBCN/Frontend.php';

class UNL_UCBCN_Frontend_Search extends UNL_UCBCN_Frontend
{
    var $calendar;
    var $output;
    var $query;
    var $starttime;
    var $endtime;

    function __construct($options=array())
	{
		$this->setOptions($options);
		$this->run();
	}

    function run()
    {
        $this->query = trim($this->query);
        if (!empty($this->query)) {
            $mdb2 = $this->getDatabaseConnection();
            $sql = 'SELECT eventdatetime.id FROM event, eventdatetime, calendar_has_event WHERE ' .
						'eventdatetime.event_id = event.id AND
						calendar_has_event.event_id = event.id AND
						calendar_has_event.status != \'pending\' AND ';
			if ($t = strtotime($this->query)) {
				// This is a time...
				$sql .= 'eventdatetime.starttime LIKE \''.date('Y-m-d',$t).'%\' ORDER BY eventdatetime.starttime DESC';
			} else {
				// Do a textual search.
				$sql .= 'event.title LIKE \'%'.$q.'%\' ORDERBY event.title';
			}

			$res = $mdb2->query($sql);
			$this->output = new UNL_UCBCN_EventListing();
			while ($row = $res->fetchRow()) {
				$this->output->events[] =  new UNL_UCBCN_EventInstance($row[0]);
			}
        } else {
            $this->output = new UNL_UCBCN_Error('No search string entered.');
        }
    }

}

?>

Add initial search class for the frontend.


<?php namespace Illuminate\Database\Eloquent\Relations;

use Illuminate\Database\Eloquent\Builder;

class MorphPivot extends Pivot {

	/**
	 * Set the keys for a save update query.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $query
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	protected function setKeysForSaveQuery(Builder $query)
	{
		$query->where($this->morphType, $this->getAttribute($this->morphType));

		return parent::setKeysForSaveQuery($query);
	}

	/**
	 * Delete the pivot model record from the database.
	 *
	 * @return int
	 */
	public function delete()
	{
		$query = $this->getDeleteQuery();

		$query->where($this->morphType, $this->getAttribute($this->morphType));

		return $query->delete();
	}

	/**
	 * Set the morph type for the pivot.
	 *
	 * @param  string  $morphType
	 * @return \Illuminate\Database\Eloquent\Relations\MorphPivot
	 */
	public function setMorphType($morphType)
	{
		$this->morphType = $morphType;

		return $this;
	}

}

<?php namespace Illuminate\Database\Eloquent\Relations;

use Illuminate\Database\Eloquent\Builder;

class MorphPivot extends Pivot {

	/**
	 * The type of the polymorphic relation.
	 *
	 * @var string
	 */
	protected $morphType;

	/**
	 * Set the keys for a save update query.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $query
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	protected function setKeysForSaveQuery(Builder $query)
	{
		$query->where($this->morphType, $this->getAttribute($this->morphType));

		return parent::setKeysForSaveQuery($query);
	}

	/**
	 * Delete the pivot model record from the database.
	 *
	 * @return int
	 */
	public function delete()
	{
		$query = $this->getDeleteQuery();

		$query->where($this->morphType, $this->getAttribute($this->morphType));

		return $query->delete();
	}

	/**
	 * Set the morph type for the pivot.
	 *
	 * @param  string  $morphType
	 * @return \Illuminate\Database\Eloquent\Relations\MorphPivot
	 */
	public function setMorphType($morphType)
	{
		$this->morphType = $morphType;

		return $this;
	}

}

Fix many to many polymorphic pivot updates

`$morphType ` set by `setMorphType` is being included in queries from x->pivot->save() and the like. As the object is being added as a public data member on an object with an empty original, it is treated as an attribute and added as a column to the queries. As this column doesn't exist, the query will be erroneous.

https://github.com/laravel/framework/issues/3693


<?php

/**
 * A naive brainfuck interpreter in PHP
 *
 * @author Reeze Xia <reeze@php.net>
 */

$buffer = "";
$pos = 0;

$code = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]
        >++.>+.+++++++..+++.>++.<<+++++++++++++++.
        >.+++.------.--------.>+.>.";

if ($argc > 1) {
	$code = $argv[1];
}

$i = 0;
while ($i < strlen($code)) {
	$c = $code[$i];

	if (!isset($buffer[$pos])) {
		$buffer[$pos] = 0;
	}

	switch($c) {
	case '>':
		++$pos;
		break;
	case '<':
		--$pos;
		break;
	case '+':
		$buffer[$pos]++;
		break;
	case '-':
		$buffer[$pos]--;
		break;
	case '.':
		echo chr($buffer[$pos]);
		break;
	case ',':
		$buffer[$pos] = ord(fgetc(STDIN));
		break;
	case '[':
		// JMPZ
		if (!$buffer[$pos]) {
			// find the position of next ']'
			$stack = array();
			while($i < strlen($code)) {
				++$i;
				if ($code[$i] == '[') {
					$stack[] = $i;
				} else if ($code[$i] == ']') {
					if (count($stack) == 0) {
						continue 2;
					}
					array_pop($stack);
				}
			}

			echo "Not found ]\n";
			exit;
		}
		break;
	case ']':
		// JMPNZ
		if ($buffer[$pos]) {
			$stack = array();
			while($i > -1) {
				--$i;
				if ($code[$i] == ']') {
					$stack[] = $i;
				} else if ($code[$i] == '[') {
					if (count($stack) == 0) {
						continue 2;
					}

					array_pop($stack);
				}
			}

			echo "Not found [\n";
			exit;
		}
		break;
	default:
		// ignore all of other chars
		break;
	}

	++$i;
}

Add a naive PHP implementation first

Add a naive PHP implementation first


<?php

use carlosV2\Communism\Communist;
use carlosV2\Communism\ExtractorInterface;
use carlosV2\Communism\InjectorInterface;

if (!function_exists('From')) {
    /**
     * @param object $object
     *
     * @return ExtractorInterface
     */
    function From($object)
    {
        return new Communist($object);
    }
}

if (!function_exists('To')) {
    /**
     * @param object $object
     *
     * @return InjectorInterface
     */
    function To($object)
    {
        return new Communist($object);
    }
}

Add couple of functions as helpers

Add couple of functions as helpers


<?php

namespace KawaiiGherkinTest\Formatter;

use KawaiiGherkin\Formatter\Tags;

final class TagsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Tags
     */
    private $formatter;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        $this->formatter = new Tags();
    }

    public function testCanFormatTag()
    {
        $wrongTagsInput = [
            '  user  ',
            '      feature-123',
            'bug-345     ',
        ];
        $expected       = '@user @feature-123 @bug-345';

        self::assertSame($expected, $this->formatter->format($wrongTagsInput));
    }
}

Add tests for tag formatter

Add tests for tag formatter


<?php

use Northstar\Models\ApiKey;

class ApiKeyTest extends TestCase
{
    protected $adminScope;

    protected $userScope;

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

        // Migrate & seed database
        $this->artisan('migrate');
        $this->seed();

        $this->adminScope = [
            'CONTENT_TYPE' => 'application/json',
            'HTTP_Accept' => 'application/json',
            'HTTP_X-DS-Application-Id' => '456',
            'HTTP_X-DS-REST-API-Key' => 'abc4324',
            'HTTP_Session' => 'S0FyZmlRNmVpMzVsSzJMNUFreEFWa3g0RHBMWlJRd0tiQmhSRUNxWXh6cz0=',
        ];

        $this->userScope = [
            'CONTENT_TYPE' => 'application/json',
            'HTTP_Accept' => 'application/json',
            'HTTP_X-DS-Application-Id' => '123',
            'HTTP_X-DS-REST-API-Key' => '5464utyrs',
            'HTTP_Session' => 'S0FyZmlRNmVpMzVsSzJMNUFreEFWa3g0RHBMWlJRd0tiQmhSRUNxWXh6cz0=',
        ];

    }

    /**
     * Test authentication & functionality of key index endpoint.
     * @test
     */
    public function testIndex()
    {
        // Verify a "user" scoped key is not able to list keys
        $response = $this->call('GET', 'v1/keys', [], [], [], $this->userScope);
        $this->assertEquals(403, $response->getStatusCode());

        // Verify an admin key is able to view all keys
        $response = $this->call('GET', 'v1/keys', [], [], [], $this->adminScope);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertCount(2, json_decode($response->getContent())->data);
    }

    /**
     * Test authentication & functionality of key details endpoint.
     * @test
     */
    public function testStore()
    {
        // Verify a "user" scoped key is not able to list keys
        $response = $this->call('POST', 'v1/keys', [], [], [], $this->userScope, json_encode([
            'app_name' => 'test'
        ]));
        $this->assertEquals(403, $response->getStatusCode());

        // Verify an admin key is able to create a new key
        $response = $this->call('POST', 'v1/keys', [], [], [], $this->adminScope, json_encode([
            'app_name' => 'test'
        ]));
        $this->assertEquals(201, $response->getStatusCode());
    }

}

Add tests for API key routes & authorization.


<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 *
 * NOTE:
 * If for any reason arrays are required in this file, only ever use array()
 * syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

Add note about array syntax

Add note about array syntax


<?php

namespace Punkstar\RugbyFeedTest\Calendar;

use PHPUnit\Framework\TestCase;
use Punkstar\RugbyFeed\DataManager;
use Punkstar\RugbyFeedService\App;
use Symfony\Component\HttpFoundation\Request;

class IntegrationTest extends TestCase
{

    /**
     * @param $route
     * @dataProvider routeDataProvider
     */
    public function testAllRoutesReturnSuccessfulResponse($route)
    {
        $app = (new App())->getApp();

        $request = Request::create('/' . $route);
        $response = $app->handle($request);

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

    /**
     * @return array
     */
    public function routeDataProvider()
    {
        $routes = [];

        $data = new DataManager();
        $leagues = $data->getLeagues();

        foreach ($leagues as $league) {
            $fixtures_url = 'fixtures/' . $league->getUrlKey();
            $table_url = 'table/' . $league->getUrlKey();

            $routes[] = [$fixtures_url];

            foreach ($league->getTeams() as $team) {
                $team_url = 'fixtures/' . $league->getUrlKey() . '/' . $team->getUrlKey();

                $routes[] = [$team_url];
            }

            $routes[] = [$table_url];
        }

        return $routes;
    }
}

Add integration test to check all routes


<?php
/**
 * Approve email addresses for users and non spam, non rejected comments.
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$values = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$values = $values->filter('spam = 0')->filter('active = 1')->values();

foreach($values as $record) {
	$toDo = false;

	if(!\FelixOnline\Core\EmailValidation::isEmailValidated($record->getEmail())) {
		echo $record->getEmail()."\n";
		$r = new \FelixOnline\Core\EmailValidation();
		$r->setEmail($record->getEmail())->setCode("")->setConfirmed(1)->save();
	}
}

$values = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\User', 'user', 'user');
$values = $values->values();

foreach($values as $record) {
	$toDo = false;

	if(!\FelixOnline\Core\EmailValidation::isEmailValidated($record->getEmail())) {
		echo $record->getEmail()."\n";
		$r = new \FelixOnline\Core\EmailValidation();
		$r->setEmail($record->getEmail())->setCode("")->setConfirmed(1)->save();
	}
}

echo "All done.\n";
exit(0);

Add script to pre-approve all email addresses for users, and commenters who's comments are not spam or rejected


<?php

namespace spec\Laracasts\TestDummy;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Laracasts\TestDummy\TestDummyException;

class FactoriesLoaderSpec extends ObjectBehavior {

    function it_gets_pissed_if_the_given_factories_directory_path_does_not_exist()
    {
        $this->shouldThrow(TestDummyException::class)->duringLoad(__DIR__.'/nonexistent-folder');
    }

    function it_loads_a_directory_of_user_provided_factories()
    {
        $factories = $this->load(__DIR__.'/helpers');

        $factories->shouldBeArray();
        $factories->shouldHaveCount(1);
        $factories[0]->attributes->shouldHaveKey('name');
        $factories[0]->attributes->shouldHaveKey('artist');
    }

    public function getMatchers()
    {
        return [
            'haveKey' => function($subject, $key) {
                return array_key_exists($key, $subject);
            }
        ];
    }
}

Add couple tests for factories loader

Add couple tests for factories loader


<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script to turn collections ID into auto increment field
 **/
class Migration20160623112527ComStorefront extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableExists('#__storefront_collections') && $this->db->tableHasField('#__storefront_collections', 'cId'))
		{
			$query = "ALTER TABLE `#__storefront_collections` CHANGE `cId` `cId` int(16) unsigned NOT NULL AUTO_INCREMENT";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableExists('#__storefront_collections') && $this->db->tableHasField('#__storefront_collections', 'cId'))
		{
			$query = "ALTER TABLE `#__storefront_collections` CHANGE `cId` `cId` char(50) NOT NULL AUTO_INCREMENT";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}
}

[COM_STOREFRONT] Fix case where storefront_collections ID isn't auto increment


<?php

namespace Laratrust\Tests\Checkers\Model;

class LaratrustModelDefaultCheckerTest extends LaratrustModelCheckerTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        $this->app['config']->set('laratrust.checker', 'default');
    }

    public function testModelCanDisableTheRolesAndPermissionsCaching()
    {
        $this->modelCanDisableTheRolesAndPermissionsCachingAssertions();
    }
}

Add TestFile to validate cache name for polymorphic configuration


<?php

namespace Oro\Component\Layout\Extension\Theme\DataProvider;

use Oro\Component\Layout\Extension\Theme\Model\Theme;
use Oro\Component\Layout\Extension\Theme\Model\ThemeManager;

class ThemeProvider
{
    /** @var ThemeManager */
    protected $themeManager;

    /** @var Theme[] */
    protected $themes = [];

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

    /**
     * @param string $themeName
     *
     * @return string
     */
    public function getIcon($themeName)
    {
        return $this->getTheme($themeName)->getIcon();
    }

    /**
     * @param string $themeName
     *
     * @return string|null
     */
    public function getStylesOutput($themeName)
    {
        $assets = $this->getTheme($themeName)->getDataByKey('assets');
        if ($assets && array_key_exists('styles', $assets)) {
            return array_key_exists('output', $assets['styles']) ? $assets['styles']['output'] : null;
        }

        return null;
    }

    /**
     * @param string $themeName
     *
     * @return Theme
     */
    private function getTheme($themeName)
    {
        if (!array_key_exists($themeName, $this->themes)) {
            $this->themes[$themeName] = $this->themeManager->getTheme($themeName);
        }

        return $this->themes[$themeName];
    }
}

<?php

namespace Oro\Component\Layout\Extension\Theme\DataProvider;

use Oro\Component\Layout\Extension\Theme\Model\Theme;
use Oro\Component\Layout\Extension\Theme\Model\ThemeManager;

class ThemeProvider
{
    /** @var ThemeManager */
    protected $themeManager;

    /** @var Theme[] */
    protected $themes = [];

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

    /**
     * @param string $themeName
     *
     * @return string
     */
    public function getIcon($themeName)
    {
        return $this->getTheme($themeName)->getIcon();
    }

    /**
     * @param string $themeName
     *
     * @return string|null
     */
    public function getStylesOutput($themeName)
    {
        $assets = $this->getTheme($themeName)->getConfigByKey('assets');
        if ($assets && array_key_exists('styles', $assets)) {
            return array_key_exists('output', $assets['styles']) ? $assets['styles']['output'] : null;
        }

        return null;
    }

    /**
     * @param string $themeName
     *
     * @return Theme
     */
    private function getTheme($themeName)
    {
        if (!array_key_exists($themeName, $this->themes)) {
            $this->themes[$themeName] = $this->themeManager->getTheme($themeName);
        }

        return $this->themes[$themeName];
    }
}

BB-2188: Add posibility to use parameters in data providers
- fixed old-style data-providers after master backmerge


<?php
/**
 * Copyright (c) 2017 Roman Lakhtadyr
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace app\project\handlers\fixed\api\track;

use app\core\db\builder\InsertQuery;
use app\core\view\JsonResponse;
use app\project\models\single\LoggedIn;
use app\project\models\tracklist\Songs;
use app\project\persistence\db\tables\TVideoDlQueue;

class DoCreateFromVideo
{
    public function doPost($video_url, JsonResponse $response, LoggedIn $user)
    {
        $song_id = Songs::create();
        try {
            $query = new InsertQuery(TVideoDlQueue::_NAME);
            $query->values([
                TVideoDlQueue::STATUS => 1,
                TVideoDlQueue::URL => $video_url,
                TVideoDlQueue::USER_ID => $user->getId(),
                TVideoDlQueue::TRACK_ID => $song_id
            ]);
            $query->returning(TVideoDlQueue::ID);
            $id = $query->fetchColumn()->get();
            $response->write(["id" => $id], 200);
        } catch (\Exception $exception) {
            Songs::delete($song_id);
            $response->write(["error" => $exception->getMessage()], 400);
        }
    }
}

Create controller for adding video to queue


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace ProxyManagerTestAsset;

interface VoidMethodTypeHintedInterface
{
    public function returnVoid() : void;
}

Test asset: interface with a `void` return type


<?php

namespace Desk\Test\Unit\Command;

use Desk\Test\Helper\UnitTestCase;

class NullResponseCommandTest extends UnitTestCase
{

    /**
     * {@inheritdoc}
     */
    public function getMockedClass()
    {
        return 'Desk\\Command\\NullResponseCommand';
    }

    /**
     * @covers Desk\Command\NullResponseCommand::process
     */
    public function testProcess()
    {
        $command = $this->mock(array('process', 'getResult'))
            ->shouldReceive('isExecuted')
                ->andReturn(true)
            ->getMock();

        $this->assertNull($command->getResult());
    }
}

Add missing test for NullResponseCommand


<?php

use yii\db\Schema;
use yii\db\Migration;

class m150108_095524_modify_faculty_table extends Migration
{
    public function up()
    {
    	$this->addColumn('{{%faculty}}', 'short_name', Schema::TYPE_STRING . ' AFTER `name`');

        $this->createIndex('SHORT_NAME', '{{%faculty}}', 'short_name', true);
    }

    public function down()
    {
        $this->dropIndex('SHORT_NAME', '{{%faculty}}');

        $this->dropColumn('{{%faculty}}', 'short_name');
    }
}

Add migration for ShortName property of Faculty entity


<?php namespace Nwidart\Modules\Tests;

class GenerateRouteServiceProviderTest extends BaseTestCase
{
    /**
     * @var \Illuminate\Filesystem\Filesystem
     */
    private $finder;
    /**
     * @var string
     */
    private $modulePath;

    public function setUp()
    {
        parent::setUp();
        $this->modulePath = base_path('modules/Blog');
        $this->finder = $this->app['files'];
        $this->artisan('module:make', ['name' => ['Blog']]);
    }

    public function tearDown()
    {
        $this->finder->deleteDirectory($this->modulePath);
        parent::tearDown();
    }

    /** @test */
    public function it_generates_a_new_service_provider_class()
    {
        $this->artisan('module:route-provider', ['module' => 'Blog']);

        $this->assertTrue(is_file($this->modulePath . '/Providers/RouteServiceProvider.php'));
    }

    /** @test */
    public function it_generated_correct_file_with_content()
    {
        $this->artisan('module:route-provider', ['module' => 'Blog']);

        $file = $this->finder->get($this->modulePath . '/Providers/RouteServiceProvider.php');

        $this->assertEquals($this->expectedContent(), $file);
    }

    private function expectedContent()
    {
        return <<<TEXT
<?php

namespace Modules\Blog\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The root namespace to assume when generating URLs to actions.
     *
     * @var string
     */
    protected \$rootUrlNamespace = 'Modules\Blog\Http\Controllers';

    /**
     * Called before routes are registered.
     *
     * Register any model bindings or pattern based filters.
     *
     * @param  Router \$router
     * @return void
     */
    public function before(Router \$router)
    {
        //
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map(Router \$router)
    {
        // require __DIR__ . '/../Http/routes.php';
    }
}

TEXT;

    }
}

Test the route service provider generate method


<?php

class ProfileElementTest extends PHPUnit_Framework_TestCase
{
    public function testListAttributesHaveLists()
    {
        $basePath = dirname(dirname(__DIR__));
        $doc = new DOMDocument();
        $doc->load("$basePath/profile/rwahs.xml");
        $xpath = new DOMXPath($doc);
        $list_elements = $xpath->query('/profile/elementSets/metadataElement[@datatype="List"]');
        $this->assertEquals(8, $list_elements->length, 'Number of list attributes should match.');
        /** @var DOMElement $list_element */
        foreach($list_elements as $list_element){
            $list_code = $list_element->getAttribute('list');
            $element_code = $list_element->getAttribute('code');
            $this->assertNotNull($list_code, "The list attribute needs to be set for the {$list_element->getNodePath()} element");
            $this->assertEquals(1, $xpath->query("/profile/lists/list[@code='$list_code']")->length, "List attributes require a matching list. The list '$list_code' does not exist and is required for the $element_code element.");
        }
    }
}

Test that list attributes have corresponding lists


<?php

namespace HbgEventImporter\Helper;

class AcfSync
{
    public function __construct()
    {
        //add_action('save_post', array($this,'saveAcfPHP'));
    }

    public function savePath()
    {
    }

    public function saveAcfPHP($post)
    {
        var_dump($post);
    }
}

Prepare for new function: automatic sync acf.


<?php

namespace Drupal\adtechmedia\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'AtmModal' block.
 *
 * @Block(
 *  id = "atm_modal",
 *  admin_label = @Translation("ATM Modal"),
 * )
 */
class AtmModal extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'description' => [
        'value' => $this->t('Support quality journalism. Get involved and PLEDGE 5¢ now.'),
        'format' => 'full_html',
      ]
    ] + parent::defaultConfiguration();
 }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['description'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Description'),
      '#description' => $this->t('Add description for ATM modal.'),
      '#default_value' => $this->configuration['description']['value'],
      '#format' => $this->configuration['description']['format'],
      '#weight' => '10',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['description'] = $form_state->getValue('description');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [
      '#theme' => 'atm_modal',
    ];

    $build['#attached']['library'][] = 'adtechmedia/adtechmedia.api';

    return $build;
  }

}

Create ATM modal block for modal functionality


<?php

namespace Marein\Nchan\Api;

use Marein\Nchan\Api\Model\StatusInformation;
use Marein\Nchan\Exception\AuthenticationRequiredException;
use Marein\Nchan\Exception\NchanException;
use Marein\Nchan\Http\Client;
use Marein\Nchan\Http\Response;
use Marein\Nchan\Http\Url;
use PHPUnit\Framework\TestCase;

class StatusTest extends TestCase
{
    /**
     * @test
     */
    public function itShouldReturnInformation(): void
    {
        $response = $this->createMock(Response::class);
        $response->method('body')->willReturn(<<< STRING
total published messages: 1
stored messages: 2
shared memory used: 3K
channels: 4
subscribers: 5
redis pending commands: 6
redis connected servers: 7
total interprocess alerts received: 8
interprocess alerts in transit: 9
interprocess queued alerts: 10
total interprocess send delay: 11
total interprocess receive delay: 12
STRING
        );
        $response->method('statusCode')->willReturn(200);

        $client = $this->createMock(Client::class);
        $client->method('get')->willReturn($response);

        $status = new Status(new Url('http://localhost'), $client);
        $information = $status->information();

        $this->assertInstanceOf(StatusInformation::class, $information);
    }

    /**
     * @test
     */
    public function itShouldThrowExceptionOnForbiddenRequest()
    {
        $this->expectException(AuthenticationRequiredException::class);

        $response = $this->createMock(Response::class);
        $response->method('statusCode')->willReturn(403);

        $client = $this->createMock(Client::class);
        $client->method('get')->willReturn($response);

        $status = new Status(new Url('http://localhost'), $client);
        $status->information();
    }

    /**
     * @test
     */
    public function itShouldThrowExceptionOnInvalidRequest()
    {
        $this->expectException(NchanException::class);

        $response = $this->createMock(Response::class);
        $response->method('statusCode')->willReturn(201);

        $client = $this->createMock(Client::class);
        $client->method('get')->willReturn($response);

        $status = new Status(new Url('http://localhost'), $client);
        $status->information();
    }
}

Add unit test for Status

Add unit test for Status


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

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

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

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

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

        $client->request('GET', '/private/en/content_blocks/add');
        self::assertContains(
            'Title<abbr title="Required field">*</abbr>',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Visible on site',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Add content block',
            $client->getResponse()->getContent()
        );
    }
}

Add tests for the content blocks add page


<?php

namespace ForkCMS\Core\Domain\Doctrine;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

final class CollectionHelper
{
    public static function updateCollection(
        Collection $newCollection,
        Collection $currentCollection,
        callable $addCallback,
        callable $removeCallback
    ): void {
        $newCollection->map($addCallback);
        $currentCollection->filter(fn($item) => !$newCollection->contains($item))->map($removeCallback);
    }

    public static function toArrayCollection(Collection|null $collection): ArrayCollection
    {
        return new ArrayCollection($collection?->toArray() ?? []);
    }
}

Add a collection helper class

Add a collection helper class


<?php
namespace Vfs\Stream\StreamWrapper;

use Vfs\Test\AcceptanceTestCase;

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

    public function testIsDir()
    {
        $this->assertTrue(is_dir("$this->scheme://foo"));
    }

    public function testIsFile()
    {
        $this->assertTrue(is_file("$this->scheme://foo/bar"));
    }
}

Add `is_dir` and `is_file` acceptance tests


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

namespace ZendTest\Stdlib\Strategy;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Stdlib\Hydrator\Strategy\SerializableStrategy;
use Zend\Serializer\Serializer;

class SerializableStrategyTest extends TestCase
{
    public function testCannotUseBadArgumentSerilizer()
    {
        $this->setExpectedException('Zend\Stdlib\Exception\InvalidArgumentException');
        $serializerStrategy = new SerializableStrategy(false);
    }

    public function testUseBadSerilizerObject()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $this->assertEquals($serializer, $serializerStrategy->getSerializer());
    }

    public function testUseBadSerilizerString()
    {
        $serializerStrategy = new SerializableStrategy('phpserialize');
        $this->assertEquals('Zend\Serializer\Adapter\PhpSerialize', get_class($serializerStrategy->getSerializer()));
    }

    public function testCanSerialize()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $serialized = $serializerStrategy->extract('foo');
        $this->assertEquals($serialized, 's:3:"foo";');
    }

    public function testCanUnserialize()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $serialized = $serializerStrategy->hydrate('s:3:"foo";');
        $this->assertEquals($serialized, 'foo');
    }
}

Add unit tests for serializable strategy

Add unit tests for serializable strategy


<?php

namespace AppBundle\Controller;

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

class SecurityController extends Controller
{
    /**
     * @Route("/login-demo", name="login_demo")
     */
    public function demologinAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', array(
            'dbversion' => $this->container->get('doctrine')->getDefaultConnectionName(),
            'type' => 'organism',
            'last_username' => $lastUsername,
            'error'         => $error,
        ));
    }
}

Add controller for demo user login

Add controller for demo user login


<?php

/**
   Copyright (C) 2010-2016 by the FusionInventory Development Team
   Copyright (C) 2016 Teclib'

   This file is part of Armadito Plugin for GLPI.

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

   Armadito Plugin for GLPI 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 Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include_once ("../../../../inc/includes.php");

$rawdata = file_get_contents("php://input");
if (!empty($rawdata)) { // POST /states

   // init GLPI stuff
   $communication  = new PluginArmaditoCommunication();
   $communication->init();

   // Check plugin installation
   if (!class_exists("PluginArmaditoArmadito")) {
      $response = '"error" : "Plugin armadito is not installed."';
      PluginArmaditoToolbox::logE($response);
      $communication->setMessage($response);
      $communication->sendMessage();
      session_destroy();
      exit();
   }

   // Parse json obj
   $jobj = PluginArmaditoToolbox::parseJSON($rawdata);

   if(!$jobj){
      $response = '"error" : "error when parsing incoming json : '.json_last_error_msg().'"';
      PluginArmaditoToolbox::logE($response);
      $communication->setMessage($response);
      $communication->sendMessage();
      session_destroy();
      exit();
   }

   $enrolment = new PluginArmaditoEnrolment($jobj);
   $response = $enrolment->enroll();

   $communication->setMessage($response);
   $communication->sendMessage();

   session_destroy();
}
else{
  http_response_code(400);
  header("Content-Type: application/json");
  echo '{ "plugin_response" : { "version": "'.PLUGIN_ARMADITO_VERSION.'", "error": "Invalid request sent to plugin index." }}';
}

?>

Add rest api for enrollment

Add rest api for enrollment


<?php

use yii\db\Migration;

class m160721_204739_alter_junction_table extends Migration
{
    public function up()
    {
        $this->dropPrimaryKey("news_news_tags", "news_news_tags");
        $this->addColumn("news_news_tags", "id", $this->primaryKey());
        $this->createIndex(
            'idx-news_news_tags-unique',
            'news_news_tags',
            ['news_id', 'news_tags_id'],
            true
        );

    }

    public function down()
    {
        $this->dropIndex("idx-news_news_tags-unique", "news_news_tags");
        $this->dropColumn("news_news_tags", "id");
        $this->addPrimaryKey("news_news_tags", "news_news_tags", ['news_id', 'news_tags_id']);
    }

}

Add id column to news junction table

Add id column to news junction table


<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Functional\Controller\Api\Rest;

use Oro\Bundle\EntityBundle\Provider\EntityWithFieldsProvider;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

class EntityControllerTest extends WebTestCase
{
    /**
     * @var EntityWithFieldsProvider
     */
    protected $provider;

    protected function setUp()
    {
        $this->initClient([], $this->generateWsseAuthHeader());
        $this->provider = $this->client->getContainer()->get('oro_entity.entity_field_list_provider');
    }

    public function testGetAction()
    {
        $this->client->request('GET', $this->getUrl('oro_api_workflow_entity_get'));

        $this->assertEquals(
            array_keys($this->provider->getFields()),
            array_keys($this->getJsonResponseContent($this->client->getResponse(), 200))
        );
    }
}

BAP-10818: Add Functional test webtest cases
- Covered `Oro\Bundle\WorkflowBundle\Controller\Api\Rest\EntityController`


<?php

namespace Rebilly\examples;

use Exception;
use HttpException;
use Rebilly\v2_1\Plan;
use RebillyHttpStatusCode;
use RebillyRequest;

/**
 * This is an example on how to copy the "SANDBOX" plans to "LIVE" account.
 *
 * ### Usage:
 * ```php
 * $class = new CopyPlansExample(['liveAPIKey' => 'LIVE_API_KEY', 'sandboxAPIKey' => 'SANDBOX_API_KEY']);
 * $class->copyPlans(100, 0);
 * ```
 */
final class CopyPlansExample
{
    /**
     * @var string Live API key
     */
    public $liveAPIKey;
    /**
     * @var string Sandbox API key
     */
    public $sandboxAPIKey;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        if (empty($this->liveAPIKey)) {
            throw new Exception('Live API key must be set.');
        }
        if (empty($this->sandboxAPIKey)) {
            throw new Exception('Sandbox API key must be set.');
        }
    }

    /**
     * Copy the plans from sandbox account to live one.
     *
     * @param int $limit Limit
     * @param int $offset Offset
     *
     * @throws HttpException
     */
    public function copyPlans($limit = 50, $offset = 0)
    {
        $plans = $this->getSandboxPlans($limit, $offset);

        if (!empty($plans)) {
            foreach ($plans as $plan) {
                $this->saveLivePlan($plan);
            }
            $this->copyPlans($limit, $offset + $limit);
        }
    }

    /**
     * Get sandbox plans list.
     *
     * @param int $limit Limit
     * @param int $offset Offset
     *
     * @return array The plan list.
     *
     * @throws HttpException
     */
    protected function getSandboxPlans($limit = 50, $offset = 0)
    {
        $plan = new Plan();
        $plan->setApiKey($this->sandboxAPIKey);
        $plan->setEnvironment(RebillyRequest::ENV_SANDBOX);
        $plan->setQueryParam(['limit' => $limit, 'offset' => $offset]);

        $response = $plan->listAll();

        if ($response->statusCode === RebillyHttpStatusCode::STATUS_OK) {
            return $response->getRawResponse();
        } else {
            $exception = $response->getRawResponse();
            throw new HttpException($exception->error, $exception->status);
        }
    }

    /**
     * Save live plan.
     *
     * @param object $data The plan data
     *
     * @throws HttpException
     */
    protected function saveLivePlan($data)
    {
        $plan = new Plan($data->id);
        $plan->setApiKey($this->liveAPIKey);
        $plan->setEnvironment(RebillyRequest::ENV_LIVE);
        unset($data->id);

        foreach ($data as $attribute => $value) {
            $plan->{$attribute} = $value;
        }

        $response = $plan->update();

        if (!in_array($response->statusCode, [RebillyHttpStatusCode::STATUS_OK, RebillyHttpStatusCode::STATUS_CREATED])) {
            $exception = $response->getRawResponse();
            throw new HttpException($exception->error, $exception->status);
        }
    }
}

GWY-2901: Add example of how to copy the sandbox plans to live account.


<?php

/*
 * This file is part of the Predis\Async package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use React\EventLoop\StreamSelectLoop as EventLoop;

$server = 'tcp://127.0.0.1:6379';
$loop = new EventLoop();

$consumer = new Predis\Async\Client($server, $loop);
$producer = new Predis\Async\Client($server, $loop);

$consumer->connect(function ($consumer) use ($producer) {
    echo "Connected to Redis, will BLPOP for max 10 seconds on `nrk:queue` and produce an item in ~5 seconds.\n";

    $start = microtime(true);

    $consumer->blpop('nrk:queue', 10, function ($response) use ($consumer, $producer, $start) {
        list($queue, $stop) = $response;

        $seconds = round((float) $stop - $start, 3);
        echo "Received item from `$queue` after $seconds seconds!\n";

        $consumer->disconnect();
        $producer->disconnect();
    });

    $consumer->getEventLoop()->addTimer(5, function () use ($producer) {
        $producer->lpush('nrk:queue', $microtime = microtime(true), function () use ($microtime) {
            echo "Just pushed $microtime to `nrk:queue`.\n";
        });
    });
});

$loop->run();

Add an example of BLPOP.

Add an example of BLPOP.


<?php declare(strict_types=1);
namespace Wisembly\AmqpBundle;

use PHPUnit\Framework\TestCase;

use Prophecy\Argument;

use Swarrot\Broker\Message;
use Swarrot\Broker\MessagePublisher\MessagePublisherInterface;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Wisembly\AmqpBundle\EventListener\MessagePublishedEvent;

class PublisherTest extends TestCase
{
    public function test_the_publisher_can_be_instantiated(): void
    {
        $broker = $this->prophesize(BrokerInterface::class);
        $dispatcher = $this->prophesize(EventDispatcherInterface::class);

        $publisher = new Publisher($dispatcher->reveal(), $broker->reveal());

        $this->assertInstanceOf(Publisher::class, $publisher);
    }

    public function test_publisher_publishes_messages_and_dispatch_event(): void
    {
        $message = new Message;

        $connection = new UriConnection('foo', 'amqp://localhost');
        $gate = new Gate($connection, 'foo', 'bar', 'baz');

        $callback = function (MessagePublishedEvent $event) use ($message, $gate): bool {
            return
                $gate === $event->getGate()
                && $message === $event->getMessage()
            ;
        };

        $dispatcher = $this->prophesize(EventDispatcherInterface::class);
        $dispatcher->dispatch(MessagePublishedEvent::NAME, Argument::that($callback))->shouldBeCalled();

        $provider = $this->prophesize(MessagePublisherInterface::class);
        $provider->publish($message, null)->shouldBeCalled();

        $broker = $this->prophesize(BrokerInterface::class);
        $broker->getProducer($gate)->willReturn($provider)->shouldBeCalled();

        $publisher = new Publisher($dispatcher->reveal(), $broker->reveal());
        $publisher->publish($message, $gate);
    }
}

Add tests for the publisher

Add tests for the publisher


<?php
/**
 * Class Google\Site_Kit\Modules\Thank_With_Google\Supporter_Wall_Widget
 *
 * @package   Google\Site_Kit\Modules\Thank_With_Google
 * @copyright 2022 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Modules\Thank_With_Google;

use WP_Widget;

/**
 * The supporter wall widget for Thank with Google.
 *
 * @since n.e.x.t
 * @access private
 * @ignore
 */
class Supporter_Wall_Widget extends WP_Widget {

	/**
	 * Constructor.
	 *
	 * @since n.e.x.t
	 */
	public function __construct() {
		parent::__construct(
			'googlesitekit-twg-supporter-wall',
			sprintf( 'Thank with Google: %s', __( 'Supporter Wall', 'google-site-kit' ) )
		);
	}

	/**
	 * Renders the widget form.
	 *
	 * @since n.e.x.t
	 *
	 * @param array $instance The widget instance.
	 */
	public function form( $instance ) {
		$title    = ! empty( $instance['title'] ) ? $instance['title'] : '';
		$title_id = $this->get_field_id( 'title' );

		echo '
';
			echo '';
				esc_html_e( 'Title:', 'google-site-kit' );
			echo '';
			printf(
				'<input type="text" id="%s" class="widefat" name="%s" value="%s">',
				esc_attr( $title_id ),
				esc_attr( $this->get_field_name( 'title' ) ),
				esc_attr( $title )
			);
		echo '
';
	}

	/**
	 * Updates the widget settings.
	 *
	 * @since n.e.x.t
	 *
	 * @param array $new_instance The array with new settings for the widget.
	 * @param array $old_instance The array with old settings for the widget.
	 * @return array New settings widgets.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();

		$instance['title'] = ! empty( $new_instance['title'] )
			? sanitize_text_field( $new_instance['title'] )
			: '';

		return $instance;
	}

}

Add the initial supporter wall widget.

Add the initial supporter wall widget.


<?php

namespace OpenDominion\Tests\Unit\Calculators\Dominion;

use OpenDominion\Tests\BaseTestCase;

class EmploymentCalculatorTest extends BaseTestCase
{
    public function testGetEploymentJobs()
    {
        $this->markTestIncomplete();
    }

    public function testGetPopulationEmployed()
    {
        $this->markTestIncomplete();
    }

    public function testGetEmploymentPercentage()
    {
        $this->markTestIncomplete();
    }
}

Add employment calculator test stub

Add employment calculator test stub


<?php

namespace McCool\LaravelAutoPresenter\Decorators;

abstract class BaseDecorator
{
	/**
	 * Some decorators depend on others to complete their task. This is a helper method
	 * to easily create decorators that are available.
	 *
	 * @param $class
	 * @return mixed
	 */
	public function createDecorator($class)
	{
		$decoratorClass = implode('\\', [__NAMESPACE__, $class.'Decorator']);

		if (!class_exists($decoratorClass)) {
			throw new DecoratorNotFoundException($decoratorClass);
		}

		return new $decoratorClass;
	}
}

<?php

namespace McCool\LaravelAutoPresenter\Decorators;

abstract class BaseDecorator
{
	/**
	 * Some decorators depend on others to complete their task. This is a helper method
	 * to easily create decorators that are available.
	 *
	 * @param $class
	 * @return mixed
	 * @throws DecoratorNotFoundException
	 */
	public function createDecorator($class)
	{
		$decoratorClass = implode('\\', [__NAMESPACE__, $class.'Decorator']);

		if (!class_exists($decoratorClass)) {
			throw new DecoratorNotFoundException($decoratorClass);
		}

		return new $decoratorClass;
	}
}

Comment updated for base decorator.

Comment updated for base decorator.