<?php
namespace Gamegos\NoSql\Tests\Storage\Event;

/* Imports from PHPUnit */
use PHPUnit_Framework_TestCase;

/* Imports from gamegos/nosql */
use Gamegos\NoSql\Storage\Event\OperationEvent;
use Gamegos\NoSql\Storage\StorageInterface;
use Gamegos\NoSql\Storage\OperationArguments;

/* Imports from PHP core */
use Exception;

/**
 * Test Class for OperationEvent
 * @author Safak Ozpinar <safak@gamegos.com>
 */
class OperationEventTest extends PHPUnit_Framework_TestCase
{
    public function testConstructorArguments()
    {
        $eventName = 'beforeOperation';
        $storage   = $this->getMockForAbstractClass(StorageInterface::class);
        $operation = 'get';
        $arguments = (new OperationArguments($operation))->setKey($key = 'foo');
        $returnVal = 'bar';
        $exception = new Exception();

        $event = new OperationEvent($eventName, $storage, $operation, $arguments, $returnVal, $exception);

        $this->assertSame($eventName, $event->getName());
        $this->assertSame($storage, $event->getTarget());
        $this->assertSame($operation, $event->getOperation());
        $this->assertSame($arguments, $event->getArguments());
        $this->assertSame($returnVal, $event->getReturnValue());
        $this->assertSame($exception, $event->getException());
    }

    public function testSettersAndGetters()
    {
        $event = $this->getMock(OperationEvent::class, null, [], '', false);

        $operation = 'get';
        $arguments = (new OperationArguments($operation))->setKey($key = 'foo');
        $returnVal = 'bar';
        $exception = new Exception();

        $event->setOperation($operation);
        $event->setArguments($arguments);
        $event->setReturnValue($returnVal);
        $event->setException($exception);

        $this->assertSame($operation, $event->getOperation());
        $this->assertSame($arguments, $event->getArguments());
        $this->assertSame($returnVal, $event->getReturnValue());
        $this->assertSame($exception, $event->getException());
    }

    public function testReturnValueReference()
    {
        $event = new OperationEvent(
            'beforeOperation',
            $this->getMockForAbstractClass(StorageInterface::class),
            'get',
            (new OperationArguments('get'))->setKey($key = 'foo')
        );

        $returnValueA = 'foo';
        $event->setReturnValue($returnValueA);

        $returnValueB = & $event->getReturnValue();
        $returnValueB = 'bar';

        $this->assertSame($returnValueB, $returnValueA);
    }
}

Add test class for OperationEvent.

Add test class for OperationEvent.


<?php
require_once(dirname(__FILE__).'/../bootstrap.php');

$playlists = entryPeer::retrieveByPKs(array('_KMCSPL1', '_KMCSPL2'));
foreach($playlists as $playlist)
{
	/* @var $playlist entry */

	$criteria = new Criteria();
	$criteria->add(FileSyncPeer::OBJECT_TYPE, FileSyncObjectType::ENTRY);
	$criteria->add(FileSyncPeer::OBJECT_SUB_TYPE, entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
	$criteria->add(FileSyncPeer::OBJECT_ID, $playlist->getId());
	$criteria->add(FileSyncPeer::PARTNER_ID, 0);
	$criteria->add(FileSyncPeer::DC, 0);
	$criteria->add(FileSyncPeer::ORIGINAL, true);
	$criteria->add(FileSyncPeer::STATUS, FileSync::FILE_SYNC_STATUS_READY);

	$criteria->addDescendingOrderByColumn(FileSyncPeer::ID);

	$fileSync = FileSyncPeer::doSelectOne($criteria);
	$playlist->setData($fileSync->getVersion(), true);
	$playlist->save();
}

KalturaLog::debug('Done');

Fix partner zero playlists file syncs

Fix partner zero playlists file syncs


<?php

namespace AllenJB\Notifications;

class TriggerError
{

    /** @noinspection PhpUndefinedFieldInspection PhpUnusedLocalVariableInspection */
    public static function notice(): void
    {
        $v = null;
        $a = $v->nonExistant;
    }

    public static function warning(): void
    {
        $v = null;
        count($v);
    }

    /** @noinspection PhpUndefinedFunctionInspection */
    public static function fatalError(): void
    {
        thisFunctionIsNotDefined();
    }

    /** @noinspection PhpDivisionByZeroInspection PhpExpressionResultUnusedInspection */
    public static function thrownError(): void
    {
        2 % 0;
    }

    /** @noinspection OnlyWritesOnParameterInspection */
    public static function oom(): void
    {
        $a = '';
        while (true) {
            $a .= str_repeat("Hello", 1024 * 1024);
        }
    }

    /**
     * Exhaust the stack with an infinite tail recursion function call.
     * As of writing (PHP 7.3) this causes a SegFault
     */
    public static function stackOverflow(): void
    {
        function callSelf() {
            callSelf();
        }
        callSelf();
    }

    /** @noinspection PhpUnusedLocalVariableInspection */
    public static function timeout(): void
    {
        while (true) {
            $v = password_hash('dummy value', PASSWORD_BCRYPT, ['cost' => 30]);
        }
    }

}

Add a utility class to help with generating different types of errors / warnings when testing


<?php

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

if ($argc != 3) {
    echo getHelp($argv);

    die();
}

$day = $argv[1];
$puzzle = $argv[2];

$day = ucfirst(strtolower($day));
$puzzle = ucfirst(strtolower($puzzle));

$class = "App\\$day\\$puzzle";

$runner = new $class();

$runner();

function getHelp($argv)
{
    var_dump($argv);
}

Make this run from the command line

Make this run from the command line


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\ActiveModels;

/**
 * Mixin for automatically compiling content fields.
 */
class ContentMixin extends ActiveModelMixin {
  /**
   * {@inheritdoc}
   */
  protected $options = array(
    'fields' => array('content'),
    'text' => true,
    'html' => true,
    'format' => true,
  );

  /**
   * {@inheritdoc}
   */
  public function beforeSave(ActiveModelEvent $event) {
    if (!$this->options['html'] or !$this->options['text'])
      return;
    foreach ($this->options['fields'] as $field) {
      $content = $event->record->$field;
      $html = $content; // TODO: compile
      if ($this->options['html']) {
        $htmlField =  $field . 'Html';
        $event->record->$htmlField = $html;
      }
      if ($this->options['text']) {
        $textField = $field . 'Text';
        $event->record->$textField = strip_tags($html);
      }
    }
  }
  }

  /**
   * {@inheritdoc}
   */
  public function afterCreate(ActiveModelEvent $event) {
    if (!$this->options['format'])
      return;
    // TODO: find editor/format
    foreach ($this->options['fields'] as $field) {
      $formatField = $field . 'Format';
      $event->record->$formatField = 'html';
    }
  }
}

Add possible replacement for ContentFilter.


<?php namespace Reshadman\EloquentFaster\Tests;

use Illuminate\Database\Eloquent\Model;
use Reshadman\EloquentFaster\EloquentClassFinder;
use Reshadman\EloquentFaster\FasterModel;

class EloquentClassFinderTest extends \PHPUnit_Framework_TestCase {

    public function test_eloquent_class_is_detected()
    {
        $testClasses = [
            SomeExampleModelClass::class,
            SomeExampleModelClassWithEloquent::class
        ];

        $finder = new EloquentClassFinder();

        $classes = iterator_to_array($finder->find());

        foreach ($testClasses as $testClass) {
            $this->assertContains($testClass, $classes);
        }
    }

}

class SomeExampleModelClass extends FasterModel {

}

class SomeExampleModelClassWithEloquent extends Model {

}

Add test for eloquent class finder.

Add test for eloquent class finder.


<?php

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

namespace Symfony\Bridge\PhpUnit\Tests;

use PHPUnit\Framework\TestCase;

final class ExpectedDeprecationAnnotationTest extends TestCase
{
    /**
     * Do not remove this test in the next major versions.
     *
     * @group legacy
     *
     * @expectedDeprecation foo
     */
    public function testOne()
    {
        @trigger_error('foo', E_USER_DEPRECATED);
    }

    /**
     * Do not remove this test in the next major versions.
     *
     * @group legacy
     *
     * @expectedDeprecation foo
     * @expectedDeprecation bar
     */
    public function testMany()
    {
        @trigger_error('foo', E_USER_DEPRECATED);
        @trigger_error('bar', E_USER_DEPRECATED);
    }
}

[PhpUnitBridge] Add test case for @expectedDeprecation annotation


<?php
/**
 * Make Static
 *
 * Make method static.
 *
 */

namespace Refactoring16\JetBrains;

// 1. Make method split static.
class Splitter
{
	private $delimiter;

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

	public function split($subject)
	{
		return explode($this->delimiter, $subject);
	}
}

// 2. Note that calls to Splitter::split() have updated to static calls
// as well as a new argument with instance have been provided.
$splitter = new Splitter(' ');
$myArray = $splitter->split('This is a test');
$myCsvRecord = $splitter->split('PhpStorm JetBrains');

Add lesson for simple Make Static refactoring


<?php

use Aedart\Scaffold\Contracts\Tasks\ConsoleTaskRunner;
use Mockery as m;

/**
 * Trait TaskRunnerUtils
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
trait TaskRunnerUtils
{

    /**
     * Returns a console task runner mock
     *
     * @return m\MockInterface|ConsoleTaskRunner
     */
    public function makeConsoleTaskRunnerMock()
    {
        return m::mock(ConsoleTaskRunner::class);
    }

}

Add make task runner mock util method

Add make task runner mock util method


<?php

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

namespace Sylius\Component\Order\Repository;

use Sylius\Component\Order\Model\OrderItemInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lchrusciel@gmail.com>
 */
interface OrderItemRepositoryInterface extends RepositoryInterface
{
    /**
     * @param mixed $id
     * @param mixed $cartId
     *
     * @return OrderItemInterface
     */
    public function findOneByIdAndCartId($id, $cartId);
}

[API] Configure cart and related items serialization


<?php

/**
 * Data object containing the SQL and PHP code to migrate the database
 * up to version 1421151831.
 * Generated on 2015-01-13 12:23:51 by vagrant
 */
class PropelMigration_1421151831
{

    public function preUp($manager)
    {
        // add the pre-migration code here
    }

    public function postUp($manager)
    {
        // add the post-migration code here
    }

    public function preDown($manager)
    {
        // add the pre-migration code here
    }

    public function postDown($manager)
    {
        // add the post-migration code here
    }

    /**
     * Get the SQL statements for the Up migration
     *
     * @return array list of the SQL strings to execute for the Up migration
     *               the keys being the datasources
     */
    public function getUpSQL()
    {
        return array (
  'koddi' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;

CREATE TABLE `users`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    `created_at` DATETIME,
    `updated_at` DATETIME,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM;

CREATE TABLE `users_archive`
(
    `id` INTEGER NOT NULL,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    `created_at` DATETIME,
    `updated_at` DATETIME,
    `archived_at` DATETIME,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM;

# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
    }

    /**
     * Get the SQL statements for the Down migration
     *
     * @return array list of the SQL strings to execute for the Down migration
     *               the keys being the datasources
     */
    public function getDownSQL()
    {
        return array (
  'koddi' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS `users`;

DROP TABLE IF EXISTS `users_archive`;

# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
    }

}

Add propel user table migration file

Add propel user table migration file


<?php declare(strict_types=1);

namespace Application\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20190724124736 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('INSERT INTO `inkomens` (`id`, `naam`, `datum_van`, `datum_tot`, `created`, `modified`) VALUES (NULL, \'Geen\', \'2010-01-06\', NULL, NOW(), NOW());');

    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->addSql('DELETE FROM `inkomens` WHERE `naam` = \'Geen\'');
    }
}

Add 'Geen' als inkomen met migratie

Add 'Geen' als inkomen met migratie


<?php

namespace Fhaculty\Graph\Algorithm;

use Fhaculty\Graph\Exception\UnexpectedValueException;

use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Edge\Base as Edge;
use Fhaculty\Graph\Edge\Directed as EdgeDirected;

class TransposeGraph extends Base{
    private $graph;

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

    /**
     * create transpose graph
     *
     * @throws UnexpectedValueException if input graph has undirected edges
     * @return Graph
     * @uses Graph::createGraphCloneEdgeless()
     * @uses Graph::createEdgeClone()
     * @uses Graph::createEdgeCloneInverted()
     */
    public function createGraph(){

        $newgraph = $this->graph->createGraphCloneEdgeless();

        foreach($this->graph->getEdges() as $edge){
            if(!($edge instanceof EdgeDirected)){
                throw new UnexpectedValueException('Edge is undirected');
            }
            $newgraph->createEdgeCloneInverted($edge);
        }
        return $newgraph;
    }
}

Add skeleton for transpose graph G^T

Add skeleton for transpose graph G^T


<?php
namespace ZBateson\MailMimeParser;

use PHPUnit_Framework_TestCase;

/**
 * Description of MailMimeParserTest
 *
 * @group MailMimeParser
 * @group Base
 * @covers ZBateson\MailMimeParser\MailMimeParser
 * @author Zaahid Bateson
 */
class MailMimeParserTest extends PHPUnit_Framework_TestCase
{
    public function testConstructMailMimeParser()
    {
        $mmp = new MailMimeParser();
        $this->assertNotNull($mmp);
    }

    public function testParseFromHandle()
    {
        $mmp = new MailMimeParser();

        $handle = fopen('php://memory', 'rw');
        fwrite($handle, 'This is a test');
        rewind($handle);

        $ret = $mmp->parse($handle);
        $this->assertNotNull($ret);
        $this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
    }

    public function testParseFromSmtpHandle()
    {
        $mmp = new MailMimeParser();

        $handle = fopen('php://memory', 'rw');
        fwrite($handle, "This is a test\r\n..\r\nblah\r\n.\r\n");
        rewind($handle);

        $ret = $mmp->parse($handle, true);
        $this->assertNotNull($ret);
        $this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
    }
}

Add MailMimeParser class unit tests

Add MailMimeParser class unit tests


<?php
namespace pyd\testkit\web\exceptions;

use pyd\testkit\Tests;
use yii\base\InvalidParamException;

/**
 * Create exception page instances.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class ExceptionPageFactory
{
    /**
     * @var array each key is an alias and each value is an exception page class
     * name
     */
    protected static $pageMap = [
        'default' => '\pyd\testkit\web\exceptions\Page',
        'missingParameters' => '\pyd\testkit\web\exceptions\MissingParametersPage',
        'methodNotAllowed' => '\pyd\testkit\web\exceptions\MethodNotAllowedPage',
        'csrfValidation' => '\pyd\testkit\web\exceptions\CsrfValidationPage',
    ];

    public static $parserClass = '\pyd\testkit\web\exceptions\ExceptionPageDefaultParser';

    /**
     *
     * @param string $pageAlias {@see $pageMap}
     * @return \pyd\testkit\web\exceptions\Page or subclass
     */
    public static function create($pageAlias = 'default')
    {
        if (!is_string($pageAlias) || !array_key_exists($pageAlias, self::$pageMap)) {
            throw new InvalidParamException("No exception page alias named '$pageAlias' exists.");
        }
        $pageClass = self::$pageMap[$pageAlias];
        $page = \Yii::createObject($pageClass, [Tests::$manager->getWebDriverManager()->getDriver()]);

        $parser = \Yii::createObject(self::$parserClass, [$page]);

        $page->setParser($parser);
        return $page;
    }
}

Add a factory class to create exception pages.


<?php

# check here
//Notifications which could be shown in the bottom corner of the page, and also dismissed.
//This would require another table with system information which can be marked read? Or something like this. It would be best to have it in the account page.
//Display a header with information? This can be dismissed and stored using local storage? Or maybe using a number to show the most recently read/dismissed notification and would only show higher numbers.

//One of these approaches above could be used.

//Start this tomorrow
if(($_SERVER['REQUEST_METHOD'] == 'POST') && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    $notification = new Notifications();
    if($_POST['action'] === 'check') {
        $last = $_POST['last'];
        $notification->checkForNewNotifications($last);
    } else if($_POST['action'] === 'get') {
        $last = $_POST['last'];
        $notification->getNewNotifications($last);
    }
}

class Notifications {

    public $db = null;
    function __construct() {
        require_once 'db-connect.inc.php';
        $this->db = Database::ConnectDb();
    }

    function checkForNewNotifications($last) {
		$stmt = $this->db->prepare('SELECT NotificationId FROM note_announcements ORDER BY NotificationId DESC LIMIT 1');
		$stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if($stmt->rowCount() > 0) {
            $result = $result[0]['NotificationId'];

            $send = array('notificationId' => $result);
            echo json_encode($send);
        } else {
            echo json_encode('none_found');
        }

        return;
    }

    function getNewNotifications($last) {
        echo json_encode('placeholder');
    }
}

?>

Add backend for checking and getting the lastest notification


<?php

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

class AddExclusiveToArtistTracks extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('artist_tracks', function (Blueprint $table) {
            $table->boolean('exclusive')->after('length')->default(0);
        });
    }

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

Add exclusive flag to artist tracks

Add exclusive flag to artist tracks


<?php
namespace Squid\MySql\Impl\Connectors\Object\Identity;

use lib\DataSet;
use lib\DummyObject;
use PHPUnit\Framework\TestCase;
use Squid\MySql\Impl\Connectors\Internal\Object\AbstractORMConnector;
use Squid\MySql\Impl\Connectors\Object\IdentityConnector;

class TIdentityDecoratorTest extends TestCase
{
	private static function subject(): TIdentityDecoratorTestHelper
	{
		$subject = new TIdentityDecoratorTestHelper();

		$subject->setObjectMap(DummyObject::class);
		$subject->setTable('a');
		$subject->setConnector(DataSet::connector());

		return $subject;
	}

	private function assertMethodCalled(string $name, ...$params): void
	{
		$subject = self::subject();
		$mock = $this->getMockBuilder(IdentityConnector::class)->getMock();
		$subject->object = $mock;

		$mock->expects(self::once())->method($name)->with(...$params)->willReturn(123);

		self::assertEquals(123, $subject->$name(...$params));
	}

	public function test_getIdentityConnector_SameObjectReturned()
	{
		$subject = self::subject();
		self::assertSame($subject->getIdentityConnectorMethod(), $subject->getIdentityConnectorMethod());
	}

	public function test_sanity()
	{
		$this->assertMethodCalled('delete', [new DummyObject()]);
		$this->assertMethodCalled('update', new DummyObject());
		$this->assertMethodCalled('upsert', [new DummyObject()]);
	}
}

class TIdentityDecoratorTestHelper extends AbstractORMConnector
{
	use TIdentityDecorator { TIdentityDecorator::getIdentityConnector as getIdentityConnectorOrigin; }

	public $object;

	protected function getPrimaryKeys(): array
	{
		return ['a' => 'a'];
	}

	protected function getIdentityConnector()
	{
		if ($this->object)
			return $this->object;

		return $this->getIdentityConnectorOrigin();
	}

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

Add unit tests for TIdentityDecorator

Add unit tests for TIdentityDecorator


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('add or update events in database');
$I->runShellCommand('php artisan memvents:update');
$I->seeInShellOutput('All Done!');

Add test for artisan update command. Need to refactor so it's not hitting the meetup api


<?php
/**
 * Copyright (c) (2017) - Aikar's Minecraft Timings Parser
 *
 *  Written by Aikar <aikar@aikar.co>
 *    + Contributors (See AUTHORS)
 *
 *  http://aikar.co
 *  http://starlis.com
 *
 *  @license MIT
 *
 */

namespace Starlis\Timings;

use Stiphle\Storage\Apc;
use Stiphle\Throttle\LeakyBucket;

class TimingsThrottle extends LeakyBucket {

	/**
	 * Throttle constructor.
	 */
	public function __construct() {
		parent::__construct();
		$this->storage = new Apc();
	}

	public function throttle($key, $limit, $milliseconds) {

		$key = $this->getStorageKey($key, $limit, $milliseconds);
		$wait     = 0;
		$newRatio = $this->getNewRatio($key, $limit, $milliseconds);
		if ($newRatio > $milliseconds) {
			$wait = ceil($newRatio - $milliseconds);
		}
		if ($wait) {
			return $wait;
		}

		/**
		 * Lock, record and release
		 */
		$this->storage->lock($key);
		$newRatio = $this->getNewRatio($key, $limit, $milliseconds);
		$this->setLastRatio($key, $newRatio);
		$this->setLastRequest($key, microtime(1));
		$this->storage->unlock($key);
		return false;
	}
}

Add a custom throttle class

Add a custom throttle class

i dont want Stiphle's behavior of waiting. I want to deny the upload.


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

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

/**
 * Adjust DB migrations:
 *
 * - use Doctrine\Migrations\AbstractMigration instead of Doctrine\DBAL\Migrations\AbstractMigration
 * - adjust method signatures
 */
class Version20201109224100 extends AbstractMigration
{
    /**
     * @return string
     */
    public function getIdentifier()
    {
        return 'Neos.Flow-20201109224100';
    }

    /**
     * @return void
     */
    public function up()
    {
        $this->searchAndReplace('Doctrine\DBAL\Migrations\AbstractMigration', 'Doctrine\Migrations\AbstractMigration', ['php']);
        $this->searchAndReplaceRegex('/public function getDescription\(\)(\s*\{)?$/m', 'public function getDescription(): string $1', ['php']);
        $this->searchAndReplaceRegex('/public function (up|down)\(Schema \$schema\)(\s*\{)?$/m', 'public function $1(Schema \$schema): void $2', ['php']);
    }
}

TASK: Add code migration to adjust DB migrations


<?php

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

namespace Symfony\Bundle\SecurityBundle\Security;

use Symfony\Component\Security\Http\Firewall\ExceptionListener;

/**
 * This is a wrapper around the actual firewall configuration which allows us
 * to lazy load the context for one specific firewall only when we need it.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class FirewallContext
{
    private $listeners;
    private $exceptionListener;
    private $config;

    /**
     * @param \Traversable|array     $listeners
     * @param ExceptionListener|null $exceptionListener
     * @param FirewallConfig|null    $firewallConfig
     */
    public function __construct($listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
    {
        $this->listeners = $listeners;
        $this->exceptionListener = $exceptionListener;
        $this->config = $config;
    }

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

    /**
     * @return \Traversable|array
     */
    public function getListeners()
    {
        return $this->listeners;
    }

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

<?php

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

namespace Symfony\Bundle\SecurityBundle\Security;

use Symfony\Component\Security\Http\Firewall\ExceptionListener;

/**
 * This is a wrapper around the actual firewall configuration which allows us
 * to lazy load the context for one specific firewall only when we need it.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class FirewallContext
{
    private $listeners;
    private $exceptionListener;
    private $config;

    public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
    {
        $this->listeners = $listeners;
        $this->exceptionListener = $exceptionListener;
        $this->config = $config;
    }

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

    public function getListeners(): iterable
    {
        return $this->listeners;
    }

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

Fix merge (phpdoc => typehint)

Fix merge (phpdoc => typehint)


Related products

		<?php
			$count = count($info);
			for($i=0; $i<$count; $i++){
				$id = $info[$i]['id'];
				$name = $info[$i]['name'];
				$price = $info[$i]['price'];
				$price_new = $info[$i]['price_new'];
				$images = rtrim(ltrim($info[$i]['images'],'["'),'"]');
				echo "
";
				echo "";
				echo "
";
				echo "
".$name."
";
				echo "";
				echo "
$".$price."
";
				echo "
";
				echo "
";
				echo "";
				echo "
";
				echo "";
				echo "
";

			}

		?>

Update code Related product & show more images


<?php
/**
 * MIT License
 *
 * Copyright (c) 2016 Ricardo Velhote
 *
 * 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 Tests\AppBundle;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class AuthenticatedWebTestCase
 * @package Tests\AppBundle
 */
class AuthenticatedWebTestCase extends WebTestCase
{
    /**
     * Create a client with a default Authorization header.
     *
     * @param string $username
     * @param string $password
     *
     * @return \Symfony\Bundle\FrameworkBundle\Client
     */
    protected function createAuthenticatedClient($username = '@rvelhote', $password = 'x')
    {
        $client = static::createClient();
        $client->request(
            'POST',
            '/api/v1/login',
            array(
                '_username' => $username,
                '_password' => $password,
            )
        );

        $data = json_decode($client->getResponse()->getContent(), true);

        $client = static::createClient();
        $client->setServerParameter('HTTP_Authorization', sprintf('Bearer %s', $data['token']));

        return $client;
    }
}

ADD: Create a class that will allow us to create an authenticated client with a JWT token


<?php

declare(strict_types=1);

namespace BinSoul\Test\Net\Mqtt\Packet;

use BinSoul\Net\Mqtt\Packet;
use BinSoul\Net\Mqtt\Packet\DisconnectRequestPacket;
use BinSoul\Net\Mqtt\PacketStream;
use PHPUnit\Framework\TestCase;

class DisconnectRequestPacketTest extends TestCase
{
    private function getDefaultData(): string
    {
        return "\xe0\x00";
    }

    public function test_write(): void
    {
        $packet = new DisconnectRequestPacket();
        $stream = new PacketStream();
        $packet->write($stream);

        $this->assertEquals($this->getDefaultData(), $stream->getData());
    }

    public function test_read(): void
    {
        $stream = new PacketStream($this->getDefaultData());
        $packet = new DisconnectRequestPacket();
        $packet->read($stream);

        $this->assertEquals(Packet::TYPE_DISCONNECT, $packet->getPacketType());
    }
}

Test the disconnect request packet

Test the disconnect request packet


<?php
/**
 * Created by PhpStorm.
 * User: ahmetturk
 * Date: 30/06/2017
 * Time: 15:02
 */

namespace Fabs\CouchDB2;

use Fabs\CouchDB2\Model\LuceneSearchQueryModel;

class LuceneSearchQueryBuilder
{
    /**
     * @param string $field
     * @param string $value
     * @param bool $exact
     * @param bool $required
     * @return null|string[]
     */
    public static function build($field, $value, $exact = false, $required = false)
    {
        $clean_query = preg_replace('/[^\sa-zA-Z0-9ğüşıöçĞÜŞİÖÇ]+/', ' ', $value);

        $words = explode(' ', $clean_query);
        $count = count($words);
        for ($i = 0; $i < $count; $i++)
        {
            if (strlen(trim($words[$i])) === 0)
            {
                unset($words[$i]);
                continue;
            }

            $words[$i] = $field . ':' . $words[$i];

            if (!$exact)
            {
                $words[$i] = $words[$i] . '*';
            }

            if ($required)
            {
                $words[$i] = '+' . $words[$i];
            }
        }

        if (count($words) === 0)
        {
            return null;
        }

        return implode(' ', $words);
    }

    /**
     * @param LuceneSearchQueryModel $lucene_query_model
     * @return null|string
     */
    public static function buildFromModel($lucene_query_model)
    {
        return self::build($lucene_query_model->field,
            $lucene_query_model->value,
            $lucene_query_model->is_exact,
            $lucene_query_model->is_required);
    }
}

ADD Lucene Search Query Builder

ADD Lucene Search Query Builder


<?
include '../scat.php';
include '../lib/txn.php';

$txn_id= (int)$_REQUEST['txn'];

$txn= txn_load($db, $txn_id);

if (!$txn)
  die_jsonp('No such transaction.');

/* Plain integer values */
foreach(array('number', 'no_rewards') as $key) {
  if (isset($_REQUEST[$key])) {
    $value= (int)$_REQUEST[$key];
    // $key is one of our hardcoded values
    $q= "UPDATE txn SET $key = $value WHERE id = $txn_id";
    $r= $db->query($q)
      or die_query($db, $q);
  }
}

$txn= txn_load($db, $txn_id);

echo jsonp(array('txn' => $txn));

<?
include '../scat.php';
include '../lib/txn.php';

$txn_id= (int)$_REQUEST['txn'];

$txn= txn_load($db, $txn_id);

if (!$txn)
  die_jsonp('No such transaction.');

/* Plain integer values */
foreach(array('number', 'no_rewards') as $key) {
  if (isset($_REQUEST[$key])) {
    $value= (int)$_REQUEST[$key];
    // $key is one of our hardcoded values
    $q= "UPDATE txn SET $key = $value WHERE id = $txn_id";
    $r= $db->query($q)
      or die_query($db, $q);
  }
}

if (isset($_REQUEST['no_rewards'])) {
  $txn= new Transaction($db, $txn_id);
  if ((int)$_REQUEST['no_rewards']) {
    $txn->clearLoyalty();
  } else {
    $txn->rewardLoyalty();
  }
}

$txn= txn_load($db, $txn_id);

echo jsonp(array('txn' => $txn));

Reset loyalty when toggling whether txn earns any


<?php
namespace Dellaert\KULEducationAPIBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Dellaert\KULEducationAPIBundle\Utility\APIUtility;

class GenerateCSV extends Command
{
	protected function configure()
	{
		$this
			->setName('kulapi:generate-csv')
			->setDescription('Generate a CSV output of all the courses.')
			->addOption(
				'fid',
				null,
				InputOption::VALUE_REQUIRED,
				'Which faculty do you want to generate a CSV for.'
			)
			->addOption(
				'lid',
				null,
				InputOption::VALUE_REQUIRED,
				'Which level do you want to generate a CSV for.'
			)
			->addOption(
				'locale',
				null,
				InputOption::VALUE_REQUIRED,
				'What locale? nl|en'
			)
		;
	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		// Handling options
		$fid = $input->getOption('fid');
		$lid = $input->getOption('lid');
		$locale = $input->getOption('locale');

		// Headers
		$output->writeln('"Vaknummer";"Vak";"Hoofddocent";"Studie";"Fase";"Verplicht";"Semester"');

		$studies = APIUtility::getLiveStudiesByIdTitle($this->container,$locale,$fid,$lid);
		foreach($studies => $study) {
			$output->writeln('"vn";"v";"d";"'.$study['title'].'";"f";"m";"s"');
		}
	}
}

Add Command to generate CSV of the list

Add Command to generate CSV of the list


<?php
namespace pyd\testkit;

/**
 * Store and provide generic failure messages for assertion methods.
 *
 * <code>
 * // AssertionMessage::get() will return the message set by the hasFocus()
 * // method
 * $this->assertTrue($form->username->hasFocus(), AssertionMessage::get());
 * </code>
 *
 * @author pyd <pierre.yves.delettre@gmail.com>
 */
class AssertionMessage
{
    /**
     * @var string message container
     */
    protected static $msg;

    /**
     * Store a message. Any existing content will be overwritten.
     *
     * @param string $msg
     */
    public static function set($msg)
    {
        self::$msg = "\n$msg";
    }

    /**
     * Return the currently stored message and remove it.
     *
     * @return string
     */
    public static function get()
    {
        $msg = self::$msg;
        if (null === $msg) {
            return "No assertion message available.";
        }
        self::$msg = null;
        return $msg;
    }

    /**
     * Add a message. Any existing content will be preserved.
     *
     * @param string $msg
     * @param boolean $newLine add a new line "\n" before the added message
     */
    public static function add($msg, $newLine = false)
    {
        $msg = $newLine ? "\n$msg" : " $msg";
        self::$msg .= $msg;
    }

    /**
     * Clear message.
     */
    public static function clear()
    {
        self::$msg = '';
    }
}

Create helper for assertion messages.

Create helper for assertion messages.


<?php
	#
	# $Id: vuln_latest.php,v 1.1.2.1 2006-09-16 23:17:42 dan Exp $
	#
	# Copyright (c) 1998-2006 DVL Software Limited
	#

// base class for user tasks
class vuln_latest {

	var $id;
	var $category;
	var $port;
	var $dater;
	var $vid;

	var $dbh;
	var $LocalResult;

	function Vuln_Latest($dbh) {
		$this->dbh	= $dbh;
	}

	function _PopulateValues($myrow) {
		$this->category = $myrow['category'];
		$this->port     = $myrow['port'];
		$this->date     = $myrow['date'];
		$this->vid      = $myrow['vid'];
	}

	function FetchInitialise($PortID) {
		# fetch all rows in ports_updating with id = $PortID

		$Debug = 0;

		$sql = "
SELECT distinct PA.category, PA.name as port, coalesce(V.date_modified, V.date_entry, V.date_discovery), V.vid
  FROM commit_log_ports_vuxml CLPV, vuxml V, ports_all PA
 WHERE CLPV.vuxml_id = V.id
   AND CLPV.port_id  = PA.id
 ORDER BY coalesce(V.date_modified, V.date_entry, V.date_discovery) desc, category, name
 LIMIT 15;";
		if ($Debug) echo "
$sql
";

		$this->LocalResult = pg_exec($this->dbh, $sql);
		if ($this->LocalResult) {
			$numrows = pg_numrows($this->LocalResult);
			if ($numrows == 1) {
				$myrow = pg_fetch_array ($this->LocalResult);
			}
		} else {
			echo 'pg_exec failed:
' . $sql . '
 : ' . pg_errormessage();
		}

		return $numrows;
	}

	function FetchNth($N) {
		#
		# call FetchInitialiseTo first.
		# then call this function N times, where N is the number
		# returned by FetchInitialiseTo
		#

		$myrow = pg_fetch_array($this->LocalResult, $N);
		$this->_PopulateValues($myrow);
	}

}

Add class for getting latest vuln.

Add class for getting latest vuln.

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3794 46e82423-29d8-e211-989e-002590a4cdd4


<?php

/*
 * Copyright (C) 2013 Kolibre
 *
 * This file is part of Kolibre-KADOS.
 * Kolibre-KADOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * at your option) any later version.
 *
 * Kolibre-KADOS 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Kolibre-KADOS. If not, see <http://www.gnu.org/licenses/>.
 */

$includePath = dirname(realpath(__FILE__)) . '/../../../include/adapter';
set_include_path(get_include_path() . PATH_SEPARATOR . $includePath);

require_once('DemoAdapter.class.php');

class DemoAdapterTest extends PHPUnit_Framework_TestCase
{
    protected static $database;
    protected static $adapter;

    public static function setUpBeforeClass()
    {
        self::$database = realpath(dirname(__FILE__)) . '/demo.db';
        if (file_exists(self::$database)) unlink(self::$database);

        $dump = realpath(dirname(__FILE__)) . '/../../../data/db/demo.sqlite.dump';
        $output = array();
        $command = "sqlite3 " . self::$database . " < $dump";
        exec($command, $output);
        self::$adapter = new DemoAdapter(self::$database);
    }

    public static function tearDownAfterClass()
    {
        if (file_exists(self::$database)) unlink(self::$database);
    }

    public function testAuthenticate()
    {
        $this->assertFalse(self::$adapter->authenticate('kolibre', 'erbilok'));
        $this->assertTrue(self::$adapter->authenticate('kolibre', 'kolibre'));
    }
}

?>

Add PHPUnit test for demo adapter

Add PHPUnit test for demo adapter


<?php

/**
 * This file contains an abstract definition for a JSON helper class.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Abstract definition for a Json wrapper
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
interface JsonInterface
{

    /**
     * Decode a JSON string into an array.
     *
     * @param String $json The JSON string
     *
     * @return array Decoded Array
     */
    public static function decode($json);

    /**
     * Return a json encoded error.
     *
     * @param String $error Error to output
     * @param mixed  $info  Additional information about the error
    *                       (optional)
     *
     * @return String $return json encoded error
     */
    public static function error($error, $info = "");

    /**
     * Return a json encoded internal server error.
     *
     * This also leaves a note about it in the error log.
     *
     * @param String $info Error information
     *
     * @return String $return json encoded error
     */
    public static function server_error($info);

    /**
     * Return a json encoded invalid input error.
     *
     * This also leaves a note about it in the error log.
     *
     * @param String $info Error information
     *
     * @return String $return json encoded error
     */
    public static function invalid_input($info);

    /**
     * Return a json encoded (partial) result (not everything worked fine).
     *
     * @param mixed $info Additional information about the error (optional)
     * @param array $data The return data
     *
     * @return String $return json encoded return value
     */
    public static function partial_result($info, $data);

    /**
     * Return a json encoded (full) result (everything worked fine).
     *
     * @param array $data The return data
     *
     * @return String $return json encoded return value
     */
    public static function result($data);

}

?>

Add Json Interface to system

system: Add Json Interface to system

  Make application json class implement it.


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

namespace Zend\Stdlib\Hydrator\Filter;

use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;

class NumberOfParameterFilter implements FilterInterface
{
    /**
     * The number of parameters beeing accepted
     * @var int
     */
    protected $numberOfParameters = null;

    /**
     * @param int $numberOfParameters Number of accepted parameters
     */
    public function __construct($numberOfParameters = 0)
    {
        $this->numberOfParameters = (int) $numberOfParameters;
    }

    /**
     * @param string $property the name of the property
     * @return bool
     * @throws InvalidArgumentException
     */
    public function filter($property)
    {
        try {
            $reflectionMethod = new ReflectionMethod($property);
        } catch (ReflectionException $exception) {
            throw new InvalidArgumentException(
                "Method $property doesn't exist"
            );
        }

        if ($reflectionMethod->getNumberOfParameters() !== $this->numberOfParameters) {
            return false;
        }

        return true;
    }
}

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

namespace Zend\Stdlib\Hydrator\Filter;

use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;

class NumberOfParameterFilter implements FilterInterface
{
    /**
     * The number of parameters beeing accepted
     * @var int
     */
    protected $numberOfParameters = null;

    /**
     * @param int $numberOfParameters Number of accepted parameters
     */
    public function __construct($numberOfParameters = 0)
    {
        $this->numberOfParameters = (int) $numberOfParameters;
    }

    /**
     * @param string $property the name of the property
     * @return bool
     * @throws InvalidArgumentException
     */
    public function filter($property)
    {
        try {
            $reflectionMethod = new ReflectionMethod($property);
        } catch (ReflectionException $exception) {
            throw new InvalidArgumentException(
                "Method $property doesn't exist"
            );
        }

        return $reflectionMethod->getNumberOfParameters() === $this->numberOfParameters;
    }
}

Return boolean instead of if statement.

Return boolean instead of if statement.


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

use app\components\db\Migration;

class m171028_033342_bbass_splatnet extends Migration
{
    public function safeUp()
    {
        $this->update(
            'map2',
            ['splatnet' => 11],
            ['key' => 'bbass']
        );
    }

    public function safeDown()
    {
        $this->update(
            'map2',
            ['splatnet' => null],
            ['key' => 'bbass']
        );
    }
}

Set SplatNet ID for bbass

Set SplatNet ID for bbass

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


<?php
class db_dcs_device extends CI_Model{
	function get_all(){
		$q = $this->db->get('dcs_device');
		return $q->result();
	}

	function insert($data){
		$this->db->insert('dcs_device', $data);
	}
}

Add new model to handle DCS Device

Add new model to handle DCS Device


<?php

class CM_Paging_Log_AbstractTest extends CMTest_TestCase {

	public function testAddGet() {
		$paging = $this->getMockBuilder('CM_Paging_Log_Abstract')->setMethods(array('getType'))
				->disableOriginalConstructor()->getMockForAbstractClass();
		$paging->expects($this->any())->method('getType')->will($this->returnValue(14));
		/** @var CM_Paging_Log_Abstract $paging */
		$paging->__construct();

		$add = CMTest_TH::getProtectedMethod('CM_Paging_Log_Abstract', '_add');
		$add->invoke($paging, 'foo');
		$add->invoke($paging, 'bar', array('meta1' => 12));

		$items = $paging->getItems();
		$this->assertSame(2, count($items));

		$this->assertSame('bar', $items[0]['msg']);
		$this->assertSame(array('meta1' => 12), $items[0]['metaInfo']);

		$this->assertSame('foo', $items[1]['msg']);
		$this->assertSame(null, $items[1]['metaInfo']);
	}
}

Add test for adding and getting log items


<?php

use Fhaculty\Graph\Algorithm\ConnectedComponents as AlgorithmConnected;
use Fhaculty\Graph\Graph;

class ConnectedComponentsTest extends TestCase
{
    public function testNullGraph()
    {
        $graph = new Graph();

        $alg = new AlgorithmConnected($graph);

        $this->assertEquals(0, $alg->getNumberOfComponents());
        $this->assertFalse($alg->isSingle());
        $this->assertCount(0, $alg->createGraphsComponents());
    }

    public function testGraphSingleTrivial()
    {
        $graph = new Graph();
        $graph->createVertex(1);

        $alg = new AlgorithmConnected($graph);

        $this->assertEquals(1, $alg->getNumberOfComponents());
        $this->assertTrue($alg->isSingle());

        $graphs = $alg->createGraphsComponents();

        $this->assertCount(1, $graphs);
        $this->assertGraphEquals($graph, reset($graphs));
    }

    public function testGraphEdgeDirections()
    {
        // 1 -- 2 -> 3 <- 4
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));
        $graph->getVertex(2)->createEdgeTo($graph->createVertex(3));
        $graph->createVertex(4)->createEdgeTo($graph->getVertex(3));

        $alg = new AlgorithmConnected($graph);

        $this->assertEquals(1, $alg->getNumberOfComponents());
        $this->assertTrue($alg->isSingle());

        $graphs = $alg->createGraphsComponents();

        $this->assertCount(1, $graphs);
        $this->assertGraphEquals($graph, reset($graphs));
        $this->assertGraphEquals($graph, $alg->createGraphComponentVertex($graph->getVertex(1)));
    }

    public function testComponents()
    {
        // 1 -- 2, 3 -> 4, 5
        $graph = new Graph();
        $v1 = $graph->createVertex(1);
        $v2 = $graph->createVertex(2);
        $v3 = $graph->createVertex(3);
        $v4 = $graph->createVertex(4);
        $v5 = $graph->createVertex(5);
        $e1 = $v1->createEdge($v2);
        $e2 = $v3->createEdgeTo($v4);

        $alg = new AlgorithmConnected($graph);

        $this->assertEquals(3, $alg->getNumberOfComponents());
        $this->assertFalse($alg->isSingle());

        $graphs = $alg->createGraphsComponents();
        $this->assertCount(3, $graphs);

        $ge = new Graph();
        $ge->createVertex(1)->createEdge($ge->createVertex(2));
        $this->assertGraphEquals($ge, $alg->createGraphComponentVertex($v2));

        $ge = new Graph();
        $ge->createVertex(5);
        $this->assertEquals($ge, $alg->createGraphComponentVertex($v5));
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvalidVertexPassedToAlgorithm()
    {
        $graph = new Graph();

        $graph2 = new Graph();
        $v2 = $graph2->createVertex(12);

        $alg = new AlgorithmConnected($graph);
        $alg->createGraphComponentVertex($v2);
    }
}

Add tests for connected components (100% coverage)


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Enum\WeekDay;
use Zimbra\Mail\Struct\ByDayRule;
use Zimbra\Mail\Struct\WkDay;

/**
 * Testcase class for ByDayRule.
 */
class ByDayRuleTest extends ZimbraMailTestCase
{
    public function testByDayRule()
    {
        $ordwk1 = mt_rand(1, 53);
        $ordwk2 = mt_rand(-53, -1);

        $wkday1 = new WkDay(WeekDay::SU(), $ordwk1);
        $wkday2 = new WkDay(WeekDay::MO(), $ordwk2);

        $byday = new ByDayRule([$wkday1]);
        $this->assertSame([$wkday1], $byday->getDays()->all());
        $byday->addDay($wkday2);
        $this->assertSame([$wkday1, $wkday2], $byday->getDays()->all());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<byday>'
                .'<wkday day="' . WeekDay::SU() . '" ordwk="' . $ordwk1 . '" />'
                .'<wkday day="' . WeekDay::MO() . '" ordwk="' . $ordwk2 . '" />'
            .'</byday>';
        $this->assertXmlStringEqualsXmlString($xml, (string) $byday);

        $array = array(
            'byday' => array(
                'wkday' => array(
                    array(
                        'day' => WeekDay::SU()->value(),
                        'ordwk' => $ordwk1,
                    ),
                    array(
                        'day' => WeekDay::MO()->value(),
                        'ordwk' => $ordwk2,
                    ),
                )
            ),
        );
        $this->assertEquals($array, $byday->toArray());
    }
}

Add test case for ByDayRule.

Add test case for ByDayRule.


<?php

namespace Omise\Payment\Gateway\Http\Client;

class Authorize extends AbstractOmiseClient
{
    /**
     * @param  array $body
     *
     * @return array
     */
    public function request(Array $body)
    {
        return \OmiseCharge::create([
            'amount'   => 10000,
            'currency' => "thb",
            'card'     => "tokn_test_5609gc5d58d32nr4e1g",
            'capture'  => false
        ], $this->publicKey, $this->secretKey);
    }
}

Add a class to create the charge with authorize only

Add a class to create the charge with authorize only. The public key and
secret key will be used from the initialize of parent class. This class
is still fixed the parameters from the client side.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;

class CandidacyStep7Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('total_days', 'text', array(
        				'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank()
        				)))
        		->add('start_candidacy', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add candidacy step 7 form type

Add candidacy step 7 form type


<?php

namespace Risan\OAuth1\Signature;

use Psr\Http\Message\UriInterface;

interface BaseStringBuilderInterface
{
    /**
     * Build the signature base string.
     *
     * @param string $httpMethod
     * @param \Psr\Http\Message\UriInterface|string $uri
     * @param array $parameters
     * @link https://tools.ietf.org/html/rfc5849#section-3.4.1
     * @return string
     */
    public function build($httpMethod, $uri, array $parameters = []);

    /**
     * Build the HTTP method component for base string.
     *
     * @param  string $httpMethod
     * @return string
     */
    public function buildMethodComponent($httpMethod);

    /**
     * Build the URI component for base string.
     *
     * @param  \Psr\Http\Message\UriInterface|string $uri
     * @link https://tools.ietf.org/html/rfc5849#section-3.4.1.2
     * @return string
     */
    public function buildUriComponent($uri);

    /**
     * Build the parameters component for base string.
     *
     * @param  array  $parameters
     * @link https://tools.ietf.org/html/rfc5849#section-3.4.1.3
     * @return string
     */
    public function buildParametersComponent(array $parameters);

    /**
     * Parse the given uri to PSR URIInterface.
     *
     * @param  \Psr\Http\Message\UriInterface|string $uri
     * @return Psr\Http\Message\UriInterface
     * @throws \InvalidArgumentException
     */
    public function parseToPsrUri($uri);
}

:sparkles: Add new interface for building signature base string.


<?php

declare(strict_types=1);

namespace GraphQL\Tests;

use GraphQL\Executor\Promise\Adapter\SyncPromiseAdapter;
use GraphQL\GraphQL;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use PHPUnit\Framework\TestCase;
use function sprintf;

class GraphQLTest extends TestCase
{
    public function testPromiseToExecute() : void
    {
        $promiseAdapter = new SyncPromiseAdapter();
        $schema         = new Schema(
            [
                'query' => new ObjectType(
                    [
                        'name' => 'Query',
                        'fields' => [
                            'sayHi' => [
                                'type' => Type::nonNull(Type::string()),
                                'args' => [
                                    'name' => [
                                        'type' => Type::nonNull(Type::string()),
                                    ],
                                ],
                                'resolve' => static function ($value, $args) use ($promiseAdapter) {
                                    return $promiseAdapter->createFulfilled(sprintf('Hi %s!', $args['name']));
                                },
                            ],
                        ],
                    ]
                ),
            ]
        );

        $promise = GraphQL::promiseToExecute($promiseAdapter, $schema, '{ sayHi(name: "John") }');
        $result  = $promiseAdapter->wait($promise);
        $this->assertSame(['data' => ['sayHi' => 'Hi John!']], $result->toArray());
    }
}

Add a test to cover promises

Add a test to cover promises


<?php

namespace SilMock\Google\Service;

use Exception;
use SilMock\DataStore\Sqlite\SqliteUtils;
use Sil\Psr3Adapters\Psr3EchoLogger;

class DbClass
{
    /** @var string|null - The path (with file name) to the SQLite database. */
    public ?string $dbFile;

    /** @var string - The 'type' field to use in the database. */
    protected string $dataType;

    /** @var string - The 'class' field to use in the database */
    protected string $dataClass;

    protected Psr3EchoLogger $logger;

    public function __construct(?string $dbFile, string $dataType, string $dataClass)
    {
        $this->dbFile = $dbFile;
        $this->dataType = $dataType;
        $this->dataClass = $dataClass;
        $this->logger = new Psr3EchoLogger();
        if (empty($dbFile)) {
            $exception = new Exception();
            $exceptions = explode("\n", $exception->getTraceAsString());
            $previousLocationMessage = $exceptions[1];
            $this->logger->warning(
                sprintf(
                    "Empty dbFile provided:\n%s",
                    $previousLocationMessage
                )
            );
        }
    }

    protected function getSqliteUtils(): SqliteUtils
    {
        return new SqliteUtils($this->dbFile);
    }

    protected function getRecords(): array
    {
        $sqliteUtils = $this->getSqliteUtils();
        return $sqliteUtils->getData($this->dataType, $this->dataClass);
    }

    protected function deleteRecordById(int $recordId)
    {
        $sqliteUtils = $this->getSqliteUtils();
        $sqliteUtils->deleteRecordById($recordId);
    }

    protected function addRecord(string $data)
    {
        $sqliteUtils = $this->getSqliteUtils();
        $sqliteUtils->recordData(
            $this->dataType,
            $this->dataClass,
            $data
        );
    }
}

Add a database base class

Add a database base class


<?php

use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;

class FixQbJeId extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('payment', [ 'signed' => false ]);
      $table
        ->changeColumn('qb_je_id', 'string', [ 'limit' => 512, 'default' => '' ])
        ->save();

      $table= $this->table('txn', [ 'signed' => false ]);
      $table
        ->changeColumn('qb_je_id', 'string', [ 'limit' => 512, 'default' => '' ])
        ->save();
    }
}

Fix defaults of new fields

Fix defaults of new fields


<?php
/**
 * Base controller class for WizinSimpleCmsBundle
 */
namespace Wizin\Bundle\SimpleCmsBundle\Controller;

use Wizin\Bundle\BaseBundle\Controller\Controller as BaseController;

/**
 * Class Controller
 * @package Wizin\Bundle\SimpleCmsBundle\Controller
 * @author Makoto Hashiguchi <gusagi@gmail.com>
 */
class Controller extends BaseController
{
    /**
     * @return \Wizin\Bundle\SimpleCmsBundle\Repository\ContentRepository
     */
    protected function getContentRepository()
    {
        return $this->getEntityManager()->getRepository('WizinSimpleCmsBundle:Content');
    }

    /**
     * @return \Wizin\Bundle\SimpleCmsBundle\Service\Template
     */
    protected function getTemplateService()
    {
        return $this->get('wizin_simple_cms.template');
    }
}

Create base controller class for WizinSimpleCmsBundle


<?php

namespace TZK\Taiga\Services;

use TZK\Taiga\RestClient;
use TZK\Taiga\Service;

class IssueCustomAttributeValues extends Service
{
    public function __construct(RestClient $taiga)
    {
        parent::__construct($taiga, 'issues/custom-attributes-values');
    }

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

    public function edit($id, $data)
    {
        return $this->put($id, [], $data);
    }

    public function editPartially($id, $data)
    {
        return $this->patch($id, [], $data);
    }
}

Add custom attribute value endpoint

Add custom attribute value endpoint


<?php

// Check if we're at least on PHP 5.3.3. We do this check here, because as soon as
// we require any other files, we'll get a fatal error, because the parser chokes
// on the backslashes in Namespaces.
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
    require_once dirname(__FILE__) . '/app/legacy.php';
    exit;
}

// PHP -S (built-in webserver) doesn't handle static assets without a `return false`
// For more information, see: http://silex.sensiolabs.org/doc/web_servers.html#php-5-4
if ('cli-server' === php_sapi_name()) {
    $filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);

    // If it is a file, just return false.
    if (is_file($filename)) {
        return false;
    }
}
define('BOLT_PROJECT_ROOT_DIR', __DIR__);

require_once __DIR__ . '/app/bootstrap.php';
$app->run();

<?php

$app = require_once __DIR__ . '/app/load.php';

$app->run();

Modify front controller to call primary loader


<?php
# error reporting
# ini_set('display_errors',1);
# error_reporting(E_ALL|E_STRICT);

require_once('lib/simpletest/autorun.php');
require_once('core/php/cashmusic.php');

class BasicTests extends UnitTestCase {

    function testCASHData(){
        $data = new CASHData();
    }

    function assertFileExists($filename, $message = '%s') {
        $this->assertTrue(
                file_exists($filename),
                sprintf($message, 'File [$filename] existence check'));
    }
}
?>

Add stub test for CASHData

Add stub test for CASHData


<?php

// Page qui reçoit les requêtes de l'agent

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

if($_SERVER['REQUEST_METHOD'] == "POST"){
	echo "Hello armadito !";
}

?>

Add first server side page for interfacing with Armadito HTTP Client


<?php

namespace Dompdf\Tests\Css;

use Dompdf\Dompdf;
use Dompdf\Css\Style;
use Dompdf\Css\Stylesheet;
use Dompdf\Tests\TestCase;

class StyleTest extends TestCase
{

    public function testLengthInPt()
    {
        $dompdf = new Dompdf();
        $sheet = new Stylesheet($dompdf);
        $s = new Style($sheet);

        // PX
        $length = $s->length_in_pt('100px');
        $this->assertEquals(75, $length);

        // also check caps
        $length = $s->length_in_pt('100PX');
        $this->assertEquals(75, $length);

        // PT
        $length = $s->length_in_pt('100pt');
        $this->assertEquals(100, $length);

        // %
        $length = $s->length_in_pt('100%');
        $this->assertEquals(12, $length);
    }

}

Add test to check length_in_pt returns as expected


<?php
// 2.0.0 pr-12 to 2.0.0 ? updater
try {
    $db_engine = Config::get('mysql/engine');
} catch (Exception $e) {
    // unable to retrieve from config
    echo $e->getMessage() . '
';
}
if (!$db_engine || ($db_engine != 'MyISAM' && $db_engine != 'InnoDB'))
    $db_engine = 'InnoDB';

try {
    $db_charset = Config::get('mysql/charset');
} catch (Exception $e) {
    // unable to retrieve from config
    echo $e->getMessage() . '
';
}
if (!$db_charset || ($db_charset != 'utf8mb4' && $db_charset != 'latin1'))
    $db_charset = 'latin1';

// Update version number
/*$version_number_id = $queries->getWhere('settings', array('name', '=', 'nameless_version'));

if (count($version_number_id)) {
    $version_number_id = $version_number_id[0]->id;
    $queries->update('settings', $version_number_id, array(
        'value' => '2.0.0'
    ));
} else {
    $queries->create('settings', array(
        'name' => 'nameless_version',
        'value' => '2.0.0'
    ));
}*/

$version_update_id = $queries->getWhere('settings', array('name', '=', 'version_update'));
$version_update_id = $version_update_id[0]->id;

$queries->update('settings', $version_update_id, array(
    'value' => 'false'
));

Create nameless_version setting if it doesn't already exist


<?php

namespace ActiveCollab\DatabaseStructure\Test\CompositeFields;

use ActiveCollab\DatabaseStructure\Field\Composite\CreatedByField;
use ActiveCollab\DatabaseStructure\Test\TestCase;

/**
 * @package ActiveCollab\DatabaseStructure\Test\CompositeFields
 */
class CreatedByFieldTest extends TestCase
{
    /**
     * Test default name
     */
    public function testDefaultName()
    {
        $this->assertEquals('created_by_id', (new CreatedByField('User'))->getName());
    }
}

Add test for created by field

Add test for created by field


<?php

class CM_Http_Response_EmailTrackingTest extends CMTest_TestCase {

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

    public function testProcess() {
        $user = CMTest_TH::createUser();
        $mail = new CM_Mail_Welcome($user);

        $site = CM_Site_Abstract::factory();
        $headers = array('host' => $site->getHost());
        $render = new CM_Frontend_Render(new CM_Frontend_Environment($site));
        $request = new CM_Http_Request_Get($render->getUrlEmailTracking($mail), $headers);
        $response = new CM_Http_Response_EmailTracking($request);

        $response->process();

        $actionList = new CM_Paging_Action_User($user, CM_Action_Email::getTypeStatic(), CM_Action_Abstract::getVerbByVerbName(CM_Action_Abstract::VIEW));
        $this->assertSame(1, $actionList->getCount());
    }
}

Add test for emailtracking response

Add test for emailtracking response


<?php

namespace Scheb\TwoFactorBundle\Tests\Security\Authentication\Exception;

use Scheb\TwoFactorBundle\Security\Authentication\Exception\InvalidTwoFactorCodeException;
use Scheb\TwoFactorBundle\Tests\TestCase;

class InvalidTwoFactorCodeExceptionTest extends TestCase
{
    private const CUSTOM_MESSAGE_KEY = 'custom_message_key';

    /**
     * @test
     */
    public function unserialize_customMessageKey_isUnserialized()
    {
        $exception = new InvalidTwoFactorCodeException();
        $exception->setMessageKey(self::CUSTOM_MESSAGE_KEY);

        $unserialized = unserialize(serialize($exception));

        $this->assertEquals(self::CUSTOM_MESSAGE_KEY, $unserialized->getMessageKey());
    }
}

Add test case for InvalidTwoFactorCodeException serialization


<?php

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

class MakeCiteAsTextColumn extends Migration
{
    public function up()
    {
        Schema::table('issues', function (Blueprint $table) {
            $table->text('cite_as')->nullable()->change();
        });

        Schema::table('issue_articles', function (Blueprint $table) {
            $table->text('cite_as')->nullable()->change();
        });
    }

    public function down()
    {
        Schema::table('issues', function (Blueprint $table) {
            $table->string('cite_as')->nullable()->change();
        });

        Schema::table('issue_articles', function (Blueprint $table) {
            $table->string('cite_as')->nullable()->change();
        });
    }
}

Make `cite_as` text columns to support longer lengths


<?php

namespace Tests\Feature\Frontend;

use Tests\BrowserKitTestCase;
use App\Models\Access\User\User;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use App\Events\Frontend\Auth\UserConfirmed;
use Illuminate\Support\Facades\Notification;
use App\Notifications\Frontend\Auth\UserNeedsConfirmation;

/**
 * Class LoggedOutRouteTest.
 */
class LoggedOutRouteTest extends BrowserKitTestCase
{
    /**
     * User Logged Out Frontend.
     */

    /** @test */
    public function test_homePage()
    {
        $this->visit('/')->assertResponseOk();
    }

    /** @test */
    public function test_macroPage()
    {
        $this->visit('/macros')->see('Macro Examples');
    }

    /** @test */
    public function testLoginPage()
    {
        $this->visit('/login')->see('Login');
    }

    /** @test */
    public function testRegisterPage()
    {
        $this->visit('/register')->see('Register');
    }

    /** @test */
    public function testForgotPasswordPage()
    {
        $this->visit('password/reset')->see('Reset Password');
    }

    /** @test */
    public function testDashboardPageLoggedOut()
    {
        $this->visit('/dashboard')->seePageIs('/login');
    }

    /** @test */
    public function testAccountPageLoggedOut()
    {
        $this->visit('/account')->seePageIs('/login');
    }

    /**
     * Create an unconfirmed user and assure the user gets
     * confirmed when hitting the confirmation route.
     */
    /** @test */
    public function confirm_account_route()
    {
        Event::fake();

        // Create default user to test with
        $unconfirmed = factory(User::class)->states('unconfirmed')->create();
        $unconfirmed->attachRole(3); //User

        $this->visit('/account/confirm/'.$unconfirmed->confirmation_code)
             ->seePageIs('/login')
             ->see('Your account has been successfully confirmed!')
             ->seeInDatabase(config('access.users_table'), ['email' => $unconfirmed->email, 'confirmed' => 1]);

        Event::assertDispatched(UserConfirmed::class);
    }

    /**
     * Assure the user gets resent a confirmation email
     * after hitting the resend confirmation route.
     */
    /** @test */
    public function resend_confirm_account_route()
    {
        Notification::fake();

        $this->visit('/account/confirm/resend/'.$this->user->id)
             ->seePageIs('/login')
             ->see('A new confirmation e-mail has been sent to the address on file.');

        Notification::assertSentTo(
            [$this->user],
            UserNeedsConfirmation::class
        );
    }

    /** @test */
    public function test_404Page()
    {
        $response = $this->call('GET', '7g48hwbfw9eufj');
        $this->assertEquals(404, $response->getStatusCode());
        $this->assertContains('Page Not Found', $response->getContent());
    }
}

Test cases for frontend loggedout routes


<?php
namespace Pragma\Helpers;

class TaskLock {
	public static function check_lock($path, $lock_name){
		if( ! file_exists($path) ){;
			$oldumask = umask(0);
			mkdir($path, 0775, true);
			umask($oldumask);
		}
		$file = $path . (substr($path, -1) == '/' ? $lock_name : '/'.$lock_name);

		if(file_exists($file)){
			$pid = file_get_contents($file);
			$pids = explode(PHP_EOL, `ps -e | awk '{print $1}'`);
			if(in_array($pid, $pids)){
				echo "\n Task `$lock_name` is still in progress... \n\n";@ob_flush();
				exit();
			}else{
				echo "\n Task `$lock_name` did not complete successfully. Task restart ! \n\n";@ob_flush();
				unlink($file);
			}
		}
		file_put_contents($file, getmypid());
	}

	public static function flush($path, $lock_name){
		$file = $path . (substr($path, -1) == '/' ? $lock_name : '/'.$lock_name);
		if(file_exists($file)){
			unlink($file);
		}
	}
}

Add task locker for cli exec

Add task locker for cli exec


<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

class Search_Formatter_ValueFormatter_Datetime implements Search_Formatter_ValueFormatter_Interface
{
	function render($name, $value, array $entry)
	{
		global $prefs, $tikilib;
		return $tikilib->date_format($tikilib->get_short_datetime_format(), $value);
	}
}

Add datetime formatter to search

[NEW] Add datetime formatter to search

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@36876 b456876b-0849-0410-b77d-98878d47e9d5


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

/**
 * Simple authentication API
 */
class Controller_Api_V1_Auth extends Controller_Api_Standard
{

	public function action_index ()
	{
		// Get request parameters
		$email = $this->request->post('email');
		$password = $this->request->post('password');

		// Build request data
		$data = array(
			'email' => $email,
			'password' => $password
		);

		// Get the account service
		$account_service = Service::factory('Account');

		// Get the api service
		$api_service = Service::factory('Api');

		try
		{
			// Try to authenticate the user
			$account = $account_service->authenticate($data);

			// Return appropriate HTTP code
			$this->response($api_service->build_response(
				'Authentication succeed',
				'success',
				array(
					'token' => $account->token
				)
			), 201);
		}
		catch (Service_Exception_AuthError $e)
		{
			$this->response($api_service->build_response(
				$e->getMessage(),
				'failure'
			), 401);
		}
		catch (Exception $e)
		{
			var_dump($e);
			$this->response($api_service->build_response(
				'Bad authentication request',
				'failure'
			), 400);
		}
	}

}

Add a authentication endpoint into the API


<?php

namespace Lyon1\Bundle\PoobleBundle\Controller;

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

/**
 * @Route("/api/1.0")
 */
class Api10Controller extends Controller
{
    /**
     * @Route("/surveys")
     */
    public function surveysAction()
    {
        $em = $this->getDoctrine()->getManager();
        $surveys = $em->getRepository('PoobleBundle:Survey')->findAll();

        $ret = array();
        foreach($surveys as $survey) {
            $ret[] = array(
                'id'   => $survey->getId(),
                'name' => $survey->getName()
            );
        }

        return new Response(
            json_encode($ret),
            200,
            array('Content-Type' => 'application/json')
        );
    }
}

Add a demo api controller

Add a demo api controller


<?php

use App\Utils\RawMigration;

class RemoveProjects extends RawMigration
{
    /**
     * @inheritdoc
     * @return string
     */
    public function getRawSqlMigration()
    {
        return <<<SQL
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

ALTER TABLE `workspaces`
DROP FOREIGN KEY `workspaces_fk_user`,
DROP FOREIGN KEY `workspaces_fk_project`;

ALTER TABLE `workspaces`
DROP COLUMN `project_id`,
ADD INDEX `workspaces_fk_user` (`user_id` ASC)  COMMENT '',
DROP INDEX `workspaces_fk_project` ,
DROP INDEX `workspaces_fk_user` ;

DROP TABLE IF EXISTS `projects` ;

ALTER TABLE `workspaces`
ADD CONSTRAINT `workspaces_fk_user`
  FOREIGN KEY (`user_id`)
  REFERENCES `users` (`id`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
SQL;

    }
}

Create migration to remove Projects table and project_id column from workspaces table


<?php
/*
Plugin Name: OHS Rest API Plugin
Description: Enables the OHS API
Author: Derek Dorr
Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

register_activation_hook( __FILE__, 'ohsapi_activate' );

function ohsapi_activate() {
	flush_rewrite_rules();
}

add_action( 'rest_api_init', 'ohsapi_register_api_hooks' );

function ohsapi_register_api_hooks() {
	$namespace = 'ohs/v1';

	/**
	 * Menu API
	 */

	register_rest_route( $namespace, '/menu/', array(
		'methods'  => 'GET',
		'callback' => 'ohsapi_get_menu',
	) );

	/**
	 * Events API
	 */

	register_rest_route( $namespace, '/events/', array(
		'methods'  => 'GET',
		'callback' => 'ohsapi_get_events',
	) );

	/**
	 * Add Fields to Posts API
	 */

	register_rest_field( 'post', 'media', array(
		'get_callback' => 'posts_register_media',
		'update_callback' => null,
		'schema' => null
	) );

	/**
	 * Add Fields to Pages API
	 */

	register_rest_field( 'post', 'media', array(
		'get_callback' => 'posts_register_media',
		'update_callback' => null,
		'schema' => null
	) );

}

function ohsapi_get_menu() {

	$menu = wp_get_nav_menu_items(21);

	return $menu;
}

function ohsapi_get_events() {
	$events = new WP_Query(array('post_type' => 'event'));

	return $events;
}

function posts_register_media($object, $field_name, $request) {
	$featuredImageId = get_post_thumbnail_id($object['id']);

	$media = null;

	if ($featuredImageId) {
		$fullSizeFeatured = wp_get_attachment_image_src( $featuredImageId, 'full', false);
		$thumbnailFeatured = wp_get_attachment_image_src( $featuredImageId, 'thumbnail', false);

		$media = array(
			'id' => $featuredImageId,
			'url' => $fullSizeFeatured[0],
			'width' => $fullSizeFeatured[1],
			'height' => $fullSizeFeatured[2],
			'thumbnail' => array(
				'url' => $thumbnailFeatured[0],
				'width' => $thumbnailFeatured[1],
				'height' => $thumbnailFeatured[2]
			)
		);
	}

	return $media;
}

Add File: First Draft Plugin File

Add File: First Draft Plugin File


<?php

/*
 * Include the composer autoload file.
 */

include('../vendor/autoload.php');

/*
 * Load in the configuration information.
 * Make sure to replace the keys with your own.
 */

$configuration = new \Ziftr\ApiClient\Configuration();

$configuration->load_from_array(array(
  'host' => 'sandbox.fpa.bz',
  'port' => 443,
  'private_key' => '...',
  'publishable_key' => '...'
));

/*
 * Create a new order request.
 */

$order = new \Ziftr\ApiClient\Request('/orders/', $configuration, false);

try {

  /*
   * POST the request with the order data.
   * See the documentation for possible fields.
   */

  $order = $order->post(
    array(
      'order' => array(
        'currency_code' => 'USD',
        'is_shipping_required' => true
      )
    )
  );

  print_r($order->getResponse());

  /*
   * Create a new request object for the items endpoint.
   * This method is preffered to creating a URL directly.
   */

  $itemsReq = $order->linkRequest('items');

  /*
   * Add an order item.
   */

  $itemsReq->post(array(
    'order_item' => array(
      'name' => 'Test Item',
      'price' => 100,
      'quantity' => 1,
      'currency_code' => 'USD'
    )
  ));

  print_r($itemsReq->getResponse());

} catch( Exception $e ) {
}

Add an example of creating an order

Add an example of creating an order


<?php
class Kwc_Basic_Table_Trl_Events extends Kwc_Chained_Trl_Events
{
    public function getListeners()
    {
        $ret = parent::getListeners();
        $childModel = Kwc_Abstract::getSetting($this->_class, 'childModel');
        $ret[] = array(
            'class' => $childModel,
            'event' => 'Kwf_Component_Event_Row_Updated',
            'callback' => 'onOwnRowEvent'
        );
        $ret[] = array(
            'class' => $childModel,
            'event' => 'Kwf_Component_Event_Row_Deleted',
            'callback' => 'onOwnRowEvent'
        );
        $ret[] = array(
            'class' => $childModel,
            'event' => 'Kwf_Component_Event_Row_Inserted',
            'callback' => 'onOwnRowEvent'
        );
        return $ret;
    }

    public function onOwnRowEvent(Kwf_Component_Event_Row_Abstract $event)
    {
        $component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId(
            $event->row->component_id, array('ignoreVisible'=>true)
        );
        $this->fireEvent(new Kwf_Component_Event_Component_ContentChanged(
            $this->_class, $component
        ));
    }

    public function onMasterContentChanged(Kwf_Component_Event_Component_ContentChanged $event)
    {
        $components = Kwc_Chained_Abstract_Component::getAllChainedByMaster($event->component, 'Trl');
        foreach ($components as $component) {
            $this->fireEvent(new Kwf_Component_Event_Component_ContentChanged(
                $component->componentClass, $component
            ));
        }
    }
}

Add events.php for table trl

Add events.php for table trl

Now cache deleted on master-change and component-change


<?php

namespace Cerbero\QueryFilters;

/**
 * Dummy class to test query filters.
 *
 * @author    Andrea Marco Sartori
 */
class TestFilters extends QueryFilters
{
    /**
     * List of called filters, for testing purposes.
     *
     * @author  Andrea Marco Sartori
     * @var     array
     */
    public $filters = [];

    /**
     * Dummy filter requiring a value.
     *
     * @author    Andrea Marco Sartori
     * @param    mixed    $value
     * @return    void
     */
    public function foo($value)
    {
        $this->filters['foo'] = $value;
    }

    /**
     * Dummy filter requiring a falsy value.
     *
     * @author    Andrea Marco Sartori
     * @param    integer    $value
     * @return    void
     */
    public function bar($value)
    {
        $this->filters['bar'] = $value;
    }

    /**
     * Dummy filter requiring no values.
     *
     * @author    Andrea Marco Sartori
     * @return    void
     */
    public function baz()
    {
        $this->filters['baz'] = '';
    }

    /**
     * Dummy filter to test query strings with dashes and underscores.
     *
     * @author    Andrea Marco Sartori
     * @return    void
     */
    public function fooBarBaz()
    {
        $this->filters['foo-bar_baz'] = '';
    }
}

Create dummy class to test query filters


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use App\Models\Attributes\Vehicle\VehicleMake;

/**
 * This is the make extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class MakeExtractorTest extends AbstractVehicleExtractorTest
{
    public function testExtractMake()
    {
        $text = [
            'peugeot'    => 'Peugeot',
            'alfa-romeo' => 'Alfa Romeo',
            'alfa romeo' => 'Alfa Romeo',
        ];

        foreach ($text as $input => $expected) {
            $makeId = $this->extractor->make($input);

            $this->assertNotNull($makeId, "Input: $input");
            $this->assertSame($expected, VehicleMake::find($makeId)->name);
        }
    }
}

Add the make extractor test

Add the make extractor test


<?php
class kMetadataObjectDeletedHandler implements kObjectDeletedEventConsumer
{
	/**
	 * @param BaseObject $object
	 */
	public function objectDeleted(BaseObject $object)
	{
		if($object instanceof entry)
			$this->deleteMetadataObjects(Metadata::TYPE_ENTRY, $object->getId());
	}

	protected function deleteMetadataObjects($objectType, $objectId)
	{
		$c = new Criteria();
		$c->add(MetadataPeer::OBJECT_TYPE, $objectType);
		$c->add(MetadataPeer::OBJECT_ID, $objectId);
		$c->add(MetadataPeer::STATUS, KalturaMetadataStatus::DELETED, Criteria::NOT_EQUAL);

		$update = new Criteria();
		$update->add(MetadataPeer::STATUS, KalturaMetadataStatus::DELETED);

		$con = Propel::getConnection(MetadataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		$count = BasePeer::doUpdate($c, $update, $con);

		$peer = null;
		MetadataPeer::setUseCriteriaFilter(false);
		$metadatas = MetadataPeer::doSelect($c);
		foreach($metadatas as $metadata)
		{
			kEventsManager::raiseEvent(new kObjectDeletedEvent($metadata));

			if(!$peer)
				$peer = kMetadataManager::getObjectPeer($metadata->getObjectType());

			$peer->saveToSphinx($metadata->getObjectId(), array());
		}
	}
}

Delete metadata objects for deleted entries

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@50661 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


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

use Curl\MultiCurl;

$start_time = microtime(true);

$multi_curl = new MultiCurl();
$multi_curl->setRateLimit('2/10s');

$multi_curl->beforeSend(function ($instance) use ($start_time) {
    echo
        sprintf('%.6f', round(microtime(true) - $start_time, 6)) . ' - ' .
        'request ' . $instance->id . ' start' . "\n";
});

$multi_curl->success(function ($instance) use ($start_time) {
    echo
        sprintf('%.6f', round(microtime(true) - $start_time, 6)) . ' - ' .
        'request ' . $instance->id . ' successful (' . $instance->url . ')' . "\n";
});
$multi_curl->error(function ($instance) use ($start_time) {
    echo
        sprintf('%.6f', round(microtime(true) - $start_time, 6)) . ' - ' .
        'request ' . $instance->id . ' unsuccessful (' . $instance->url . ')' . "\n";
});

$multi_curl->addGet('https://httpbin.org/ip');
$multi_curl->addGet('https://httpbin.org/status/503');

$multi_curl->addGet('https://httpbin.org/ip');
$multi_curl->addGet('https://httpbin.org/status/503');

$multi_curl->addGet('https://httpbin.org/ip');

$multi_curl->start();

// $ php multi_curl_get_with_rate_limit.php
// 0.021839 - request 0 start
// 0.021894 - request 1 start
// 0.661308 - request 0 successful (https://httpbin.org/ip)
// 0.661968 - request 1 unsuccessful (https://httpbin.org/status/503)
// 10.024627 - request 2 start
// 10.024694 - request 3 start
// 10.114304 - request 2 successful (https://httpbin.org/ip)
// 10.117299 - request 3 unsuccessful (https://httpbin.org/status/503)
// 20.029945 - request 4 start
// 20.112836 - request 4 successful (https://httpbin.org/ip)

Add example for using rate limiter via MultiCurl::setRateLimit()


<?php
/**
 * This file is part of the Laravel Auditing package.
 *
 * @author     Antério Vieira <anteriovieira@gmail.com>
 * @author     Quetzy Garcia  <quetzyg@altek.org>
 * @author     Raphael França <raphaelfrancabsb@gmail.com>
 * @copyright  2015-2017
 *
 * For the full copyright and license information,
 * please view the LICENSE.md file that was distributed
 * with this source code.
 */

namespace OwenIt\Auditing\Drivers;

use Illuminate\Support\Facades\Config;
use OwenIt\Auditing\Contracts\Auditable;
use OwenIt\Auditing\Contracts\AuditDriver;

class Database implements AuditDriver
{
    /**
     * {@inheritdoc}
     */
    public function audit(Auditable $model)
    {
        $class = Config::get('audit.implementation', \OwenIt\Auditing\Models\Audit::class);

        return $class::create($model->toAudit());
    }

    /**
     * {@inheritdoc}
     */
    public function prune(Auditable $model)
    {
        if (($threshold = $model->getAuditThreshold()) > 0) {
            $total = $model->audits()->count();

            $forRemoval = ($total - $threshold);

            if ($forRemoval > 0) {
                $model->audits()
                    ->orderBy('created_at', 'asc')
                    ->limit($forRemoval)
                    ->delete();

                return true;
            }
        }

        return false;
    }
}

Fix invalid whitespace on empty line

Fix invalid whitespace on empty line


<?php

class StatusesTableSeeder extends Seeder {

	public function run()
	{
		Status::create([
			'title' => 'Open'
		]);
		Status::create([
			'title' => 'In Progress'
		]);
		Status::create([
			'title' => 'On Hold'
		]);
		Status::create([
			'title' => 'Closed'
		]);
	}

}

Add table seeder for statuses

Add table seeder for statuses


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
/**
 * 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_Db
 */

namespace Zend\I18n\Translator;

use Zend\ServiceManager\FactoryInterface;

/**
 * Translator.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class TranslatorServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        return Translator::factory($config['translator']);
    }
}

Add a service manager factory for the translator


<?php

env('web_dir', '.');

set('reset_script_content', '
<?php

if (function_exists("opcache_reset")) {
    opcache_reset();
}
@unlink(__FILE__);
echo "success";
');

function getResetScriptFileName() {
    $factory = new \RandomLib\Factory;
    $generator = $factory->getMediumStrengthGenerator();
    $scriptIdentifier = $generator->generateString(32, \RandomLib\Generator::CHAR_ALNUM);
    // store the $scriptIdentifier
    env('opcache:reset:scriptIdentifier', $scriptIdentifier);

    $scriptFilename = 'surf-opcache-reset-' . $scriptIdentifier . '.php';
    return $scriptFilename;
}

task('opcache:reset:create_script', function() {
    run("file_put_contents({{web_dir}}/" . getResetScriptFileName() . ",". str_replace('"', "\"", get('reset_script_content')) . ")");
})->desc('create opcache reset script');

task('local:opcache:reset:create_script', function() {
    runLocally("file_put_contents({{web_dir}}/" . getResetScriptFileName() . ",". str_replace('"', "\"", get('reset_script_content')) . ")");
})->desc('create opcache reset script locally');

task('opcache:reset:execute', function() {
    run("curl -sS {{public_url}}/surf-opcache-reset-{{opcache:reset:scriptIdentifier}}.php");
})->desc('execute opcache reset script');

Add opcode cache recipe with tasks

Add opcode cache recipe with tasks

* opcache:reset:create_script
* local:opcache:reset:create_script
* opcache:reset:execute


<?php

require_once 'SwatDB/SwatDBClassMap.php';
require_once 'SwatDB/SwatDBRecordsetWrapper.php';
require_once 'Site/dataobjects/SiteApiCredential.php';

/**
 * A recordset wrapper class for SiteApiCredential objects
 *
 * @package   Site
 * @copyright 2013 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @see       SiteApiCredential
 */
class SiteApiCredentialWrapper extends SwatDBRecordsetWrapper
{
	// {{{ protected function init()

	protected function init()
	{
		parent::init();

		$this->row_wrapper_class = SwatDBClassMap::get('SiteApiCredential');
		$this->index_field = 'id';
	}

	// }}}
}

?>

Add a wrapper class for API Credentials

Add a wrapper class for API Credentials

svn commit r81454


<?php
/*
 * @copyright Copyright (c) 2021 Julius Härtl <jus@bitgrid.net>
 *
 * @author Julius Härtl <jus@bitgrid.net>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * 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/>.
 *
 */

declare(strict_types=1);

namespace OCA\Deck\Search\Query;

use PHPUnit\Framework\TestCase;

class AQueryParameterTest extends TestCase {
	public function dataValue() {
		return [
			['foo', 'foo'],
			['spätial character', 'spätial character'],
			['"spätial character"', 'spätial character'],
			['"spätial "character"', 'spätial "character'],
			['"spätial 🐘"', 'spätial 🐘'],
			['\'spätial character\'', '\'spätial character\''],
		];
	}

	/** @dataProvider dataValue */
	public function testValue($input, $expectedValue) {
		$parameter = new StringQueryParameter('test', 0, $input);
		$this->assertEquals($expectedValue, $parameter->getValue());
	}
}

Add test case for special characters

Add test case for special characters

Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>


<?php

namespace Lchski\Migrations;

use Lchski\Contracts\Migration;

class CreateConnectionMigration extends BaseMigration implements Migration
{
	/**
	 * Create a dummy connection.
	 */
	public function up()
	{
		$this->dbHelper->createConnection(array('from' => "(select from V where name = 'DummyVertex')", 'to' => "(select from V where name = 'DummyVertex')"), array('description' => 'Yoyo!'));
	}

	/**
	 * Delete the connection.
	 */
	public function down()
	{
		$this->dbHelper->deleteNodes(array('from' => "(select from V where name = 'DummyVertex')", 'to' => "(select from V where name = 'DummyVertex')"));
	}
}

Create migration to test Edge creation

Create migration to test Edge creation


<?php

namespace tests\codeception\unit\models;

use yii\codeception\TestCase;
use Carbon\Carbon;
use app\models\Counter;

class CounterTest extends TestCase
{
    protected function setUp()
    {
        parent::setUp();
    }

    function testBest() {
        $counter = Counter::findOne(1);
        $best = $counter->getBest();
        $this->assertEquals(8, $best['count']);

        $start = (new Carbon())->subMonth(1)->startOfMonth()->addDays(18);
        $end = (new Carbon())->subMonth(1)->startOfMonth()->addDays(26);
        $this->assertEquals($start->toDateString(), $best['startDate']);
        $this->assertEquals($end->toDateString(), $best['endDate']);

        $counter = Counter::findOne(2);
        $best = $counter->getBest();
        $this->assertEquals(11, $best['count']);

        $start = (new Carbon())->subMonth(1)->startOfMonth();
        $end = (new Carbon())->subMonth(1)->startOfMonth()->addDays(11);
        $this->assertEquals($start->toDateString(), $best['startDate']);
        $this->assertEquals($end->toDateString(), $best['endDate']);
    }
}

Add unit test for models/Counter::getBest() method.


<?php

use Socks\Factory;

class PairTest extends TestCase
{
    private $loop;
    private $factory;

    public function setUp()
    {
        $this->loop = React\EventLoop\Factory::create();

        $dnsResolverFactory = new React\Dns\Resolver\Factory();
        $dns = $dnsResolverFactory->createCached('8.8.8.8', $this->loop);

        $this->factory = new Factory($this->loop, $dns);
    }

    public function testClientHttpRequest()
    {
        $socket = $this->createSocketServer();
        $port = $socket->getPort();
        $this->assertNotEquals(0, $port);

        $server = $this->factory->createServer($socket);

        $server->on('connection', function () use ($socket) {
            // close server socket once first connection has been established
            $socket->shutdown();
        });

        $client = $this->factory->createClient('127.0.0.1', $port);

        $http = $client->createHttpClient();

        $request = $http->request('GET', 'https://www.google.com/', array('user-agent'=>'none'));
        $request->on('response', function (React\HttpClient\Response $response) {
            // response received, do not care for the rest of the response body
            $response->close();
        });
        $request->end();

//         $loop = $this->loop;
//         $that = $this;
//         $this->loop->addTimer(1.0, function() use ($that, $loop) {
//             $that->fail('timeout timer');
//             $loop->stop();
//         });

        $this->loop->run();
    }

    private function createSocketServer()
    {
        $socket = new React\Socket\Server($this->loop);
        $socket->listen(0);

        return $socket;
    }
}

Add Client and Server interaction test

Add Client and Server interaction test