<?php

use Carbon\Carbon;
use Northstar\Models\User;

class AuthenticationEventsTest extends TestCase
{
    /** @test */
    public function testSuccessfulLoginEvent()
    {
        /** @var \Northstar\Models\User $user */
        $user = factory(User::class)->create(['last_authenticated_at' => Carbon::yesterday()]);

        // Save a reference to "now" so we can compare it.
        Carbon::setTestNow($now = Carbon::now());

        // Trigger the login event!
        event(new \Illuminate\Auth\Events\Login($user, true));

        // The user's `last_authenticated_at` timestamp should be updated.
        $this->seeInDatabase('users', [
            '_id' => $user->id,
            'last_authenticated_at' => $now,
        ]);
    }
}

Add unit test for auth event.

Add unit test for auth event.


<?php
/**
 * Box packing (3D bin packing, knapsack problem)
 * @package BoxPacker
 * @author Doug Wright
 */
  namespace DVDoug\BoxPacker;

  /**
   * List of items to be packed, ordered by volume
   * @author Doug Wright
   * @package BoxPacker
   */
  class ItemList extends \SplMaxHeap {

    /**
     * Compare elements in order to place them correctly in the heap while sifting up.
     * @see \SplMaxHeap::compare()
     */
    public function compare(Item $aItemA, Item $aItemB) {
      $volumeA = $aItemA->getLength() * $aItemA->getWidth() * $aItemA->getDepth();
      $volumeB = $aItemB->getLength() * $aItemB->getWidth() * $aItemB->getDepth();

      return $volumeA - $volumeB;
    }

  }

Use a SPLMaxHeap to efficiently sort items by volume


<?php

namespace Concrete\Core\User\Group\AutomatedGroup;
use Concrete\Core\User\User;
use Concrete\Core\User\Group\GroupAutomationController;

class DefaultAutomation extends GroupAutomationController {

    /**
     * Return true to automatically enter the current ux into the group
     */
    public function check(User $ux) {
        return true;
    }

}

Create a default Automation Group

Create a default Automation Group


<?php

namespace Desk\Test\System;

use Desk\Test\Helper\SystemTestCase;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\QueryAggregator\CommaAggregator;
use Guzzle\Plugin\Oauth\OauthPlugin;

/**
 * @coversNothing
 * @group system
 */
class OauthPluginSystemTest extends SystemTestCase
{
    const TIMESTAMP = '1327274290';
    const NONCE = 'e7aa11195ca58349bec8b5ebe351d3497eb9e603';

    protected $config = array(
        'consumer_key'    => 'foo',
        'consumer_secret' => 'bar',
        'token'           => 'count',
        'token_secret'    => 'dracula'
    );

    protected function getRequest()
    {
        return RequestFactory::getInstance()->create('POST', 'http://www.test.com/path?a=b&c=d', null, array(
            'e' => 'f'
        ));
    }

    public function testMultiDimensionalArrayWithNonDefaultQueryAggregator()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $aggregator = new CommaAggregator();
        $query = $request->getQuery()->setAggregator($aggregator)
            ->set('g', array('h', 'i', 'j'))
            ->set('k', array('l'))
            ->set('m', array('n', 'o'));
        $this->assertContains('a%3Db%26c%3Dd%26e%3Df%26g%3Dh%2Ci%2Cj%26k%3Dl%26m%3Dn%2Co', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE));
    }
}

Add test for Guzzle Oauth bug patch

Add test for Guzzle Oauth bug patch


<?php

class UserRatingsTest extends RateableTestCase
{

    public function testUserAverageRating()
    {
        Rating::unguard();

        $post1 = Post::find(1);
        $post2 = Post::find(2);
        $user1 = User::find(1);

        Rating::create(['id' => 5, 'rating' => 1, 'rateable_id' => $post1->id, 'rateable_type' => 'Post', 'user_id' => $user1->id]);
        Rating::create(['id' => 6, 'rating' => 1, 'rateable_id' => $post2->id, 'rateable_type' => 'Post', 'user_id' => $user1->id]);

        Rating::reguard();

        $this->assertEquals(3, (int)Post::find(1)->userAverageRating);
        $this->assertEquals("3.0", Post::find(1)->userAverageRating());

        $this->assertEquals(1, (int)Post::find(2)->userAverageRating);
        $this->assertEquals('1.0', Post::find(2)->userAverageRating());
    }

    public function testUserSumRating()
    {
        Rating::unguard();

        $post1 = Post::find(1);
        $post2 = Post::find(2);
        $user1 = User::find(1);

        Rating::create(['id' => 5, 'rating' => 1, 'rateable_id' => $post1->id, 'rateable_type' => 'Post', 'user_id' => $user1->id]);
        Rating::create(['id' => 6, 'rating' => 1, 'rateable_id' => $post2->id, 'rateable_type' => 'Post', 'user_id' => $user1->id]);

        Rating::reguard();

        $this->assertEquals(6, Post::find(1)->userSumRating);
        $this->assertEquals(6, Post::find(1)->userSumRating());

        $this->assertEquals(2, Post::find(2)->userSumRating);
        $this->assertEquals(2, Post::find(2)->userSumRating());
    }

}

Add user average & sum tests.

Add user average & sum tests.


<?php

namespace Emarref\Jwt\Verification;

use Emarref\Jwt\Claim;
use Emarref\Jwt\Encoding;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter;
use Emarref\Jwt\Token;

class IssuerVerifier implements VerifierInterface
{
    /**
     * @var string
     */
    private $issuer;

    /**
     * @param string $issuer
     */
    public function __construct($issuer = null)
    {
        if (null !== $issuer && !is_string($issuer)) {
            throw new \InvalidArgumentException('Cannot verify invalid issuer value.');
        }

        $this->issuer = $issuer;
    }

    /**
     * @param Token $token
     * @throws VerificationException
     */
    public function verify(Token $token)
    {
        /** @var Claim\Issuer $issuerClaim */
        $issuerClaim = $token->getPayload()->findClaimByName(Claim\Issuer::NAME);

        if (null === $issuerClaim) {
            return;
        }

        $issuer = $issuerClaim->getValue();

        if ($this->issuer !== $issuer) {
            throw new VerificationException('Issuer is invalid.');
        }
    }
}

<?php

namespace Emarref\Jwt\Verification;

use Emarref\Jwt\Claim;
use Emarref\Jwt\Encoding;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter;
use Emarref\Jwt\Token;

class IssuerVerifier implements VerifierInterface
{
    /**
     * @var string
     */
    private $issuer;

    /**
     * @param string $issuer
     */
    public function __construct($issuer = null)
    {
        if (null !== $issuer && !is_string($issuer)) {
            throw new \InvalidArgumentException('Cannot verify invalid issuer value.');
        }

        $this->issuer = $issuer;
    }

    /**
     * @param Token $token
     * @throws VerificationException
     */
    public function verify(Token $token)
    {
        /** @var Claim\Issuer $issuerClaim */
        $issuerClaim = $token->getPayload()->findClaimByName(Claim\Issuer::NAME);

        $issuer = (null === $issuerClaim) ? null : $issuerClaim->getValue();

        if ($this->issuer !== $issuer) {
            throw new VerificationException('Issuer is invalid.');
        }
    }
}

Validate issuer even if none in payload

Validate issuer even if none in payload


#!/usr/bin/php
<?php

const DB_PATH = "/home/grawity/lib/cgi-data/rwho.db";

// read user input

$input = fgets(STDIN);
if (!strlen($input)) {
	die("Error.\n");
}
$input = rtrim($input);

// strip off /W

if ($input == "/W" or substr($input, 0, 3) == "/W ") {
	$query = substr($input, 3);
	$detail = true;
} else {
	$query = $input;
	$detail = false;
}

$q_user = null;
$q_host = null;

if (strlen($query)) {
	if (preg_match('|^(.*)@(.+)$|', $query, $m)) {
		$q_user = $m[1];
		$q_host = $m[2];
	} else {
		$q_user = $query;
	}
}

$db = new SQLite3(DB_PATH, SQLITE3_OPEN_READONLY);

$sql = "SELECT * FROM utmp";

$cond = array();
if (strlen($q_user))
	$cond[] = "user=:user";
if (strlen($q_host))
	$cond[] = "host=:host";
if (count($cond))
	$sql = $sql." WHERE ".implode(" AND ", $cond);

$st = $db->prepare($sql);
$st->bindValue(":user", $q_user);
$st->bindValue(":host", $q_host);

$fmt = "%-12s %-12s %-6s %s\n";
printf($fmt, "USER", "HOST", "LINE", "FROM");

$res = $st->execute();
$data = array();
while ($row = $res->fetchArray(SQLITE3_ASSOC))
	$data[] = $row;

usort($data, function($a, $b) {
	$s = strcmp($a["user"], $b["user"]);
	if (!$s) $s = strcmp($a["host"], $b["host"]);
	if (!$s) $s = strcmp($a["line"], $b["line"]);
	return $s;
	});

$last = array("user" => null);
foreach ($data as $row) {
	printf($fmt,
		($row["user"] != $last["user"] ? $row["user"] : ""),
		$row["host"], $row["line"], $row["rhost"]);
	$last = $row;
}

Add tcp/79 to rwhodb gateway

Add tcp/79 to rwhodb gateway


<?php

namespace Oro\Bundle\SegmentBundle\Tests\Functional\Query;

use Oro\Bundle\SegmentBundle\Model\RestrictionSegmentProxy;
use Oro\Bundle\SegmentBundle\Query\SegmentQueryConverter;
use Oro\Bundle\SegmentBundle\Tests\Functional\DataFixtures\LoadSegmentData;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

class SegmentQueryConverterTest extends WebTestCase
{
    /** @var SegmentQueryConverter */
    private $segmentQueryConverter;

    protected function setUp()
    {
        $this->initClient();
        $this->loadFixtures([LoadSegmentData::class]);
        $this->segmentQueryConverter = $this->getContainer()->get('oro_segment.query_converter.segment');
    }

    public function testConvert()
    {
        $segment = $this->getReference(LoadSegmentData::SEGMENT_STATIC);
        $em = $this->getContainer()->get('oro_entity.doctrine_helper')->getEntityManager($segment->getEntity());
        $qb = $this->segmentQueryConverter->convert(new RestrictionSegmentProxy($segment, $em));
        $tableAlias = current($qb->getDQLPart('from'))->getAlias();
        $classname = $segment->getEntity();
        $expectedDqlPart = "SELECT $tableAlias.id, $tableAlias.id FROM $classname $tableAlias";
        $this->assertEquals($expectedDqlPart, $qb->getDQL());
    }

    public function testConvertWithFilter()
    {
        $segment = $this->getReference(LoadSegmentData::SEGMENT_DYNAMIC_WITH_FILTER);
        $em = $this->getContainer()->get('oro_entity.doctrine_helper')->getEntityManager($segment->getEntity());
        $qb = $this->segmentQueryConverter->convert(new RestrictionSegmentProxy($segment, $em));
        $tableAlias = current($qb->getDQLPart('from'))->getAlias();
        $expectedDqlPart = "WHERE LOWER($tableAlias.name) LIKE LOWER(:";
        $this->assertContains($expectedDqlPart, $qb->getDQL());
    }

    public function testConvertWithOrder()
    {
        $segment = $this->getReference(LoadSegmentData::SEGMENT_STATIC_WITH_FILTER_AND_SORTING);
        $em = $this->getContainer()->get('oro_entity.doctrine_helper')->getEntityManager($segment->getEntity());
        $qb = $this->segmentQueryConverter->convert(new RestrictionSegmentProxy($segment, $em));
        $tableAlias = current($qb->getDQLPart('from'))->getAlias();
        $expectedDqlPart = "ORDER BY $tableAlias.name DESC";
        $this->assertContains($expectedDqlPart, $qb->getDQL());
    }
}

BB-8979: Add test for SegmentQueryConverter
 - added test


<?php

/**
 * Created by PhpStorm.
 * User: elbachirnouni
 * Date: 06/09/2016
 * Time: 23:09
 */
interface NOrderableParentRecordInterface {

	/**
	 * Return false if this element is a root page
	 *
	 * @return bool
	 */
	function getIsChild();

	/**
	 * @param int    $except pid of the element to exclude
	 *
	 * @param string $select
	 *
	 * @return array
	 */
	static function parentPages( $except = null, $select = '*' );

	/**
	 * Returns the last element order
	 * Null if no page exists
	 *
	 * @return int|null
	 */
	static function getLastOrder();

	/**
	 * Re-order the elements to change the order of the given element to the new order
	 *
	 * @param int|TActiveRecord $pid
	 * @param int               $newOrder
	 *
	 * @return bool
	 * @throws NPageException
	 * @throws TActiveRecordException
	 */
	static function reOrderPage( $pid, $newOrder );

	/**
	 * @return TActiveRecord
	 */
	static function finderWithParent();

	/**
	 * @return TActiveRecord
	 */
	static function finderWithChilds();

	/**
	 * @return bool
	 */
	function getHasChilds();

	/**
	 * Return true if this element has the lower order
	 *
	 * @return bool
	 */
	function getIsFirstInOrder();

	/**
	 * Return true if this element has the greater order
	 *
	 * @return bool
	 */
	function getIsLastInOrder();

	/**
	 * Re-order all elements.
	 *
	 * Rules :
	 * - Sub elements will follow there parent on order.
	 * - Next parent element gets the last element last child order + 1.
	 *
	 * @param bool $useTx if false this method will not run into a DB transaction
	 *
	 * @throws NPageException
	 */
	static function reOrderAllElems( $useTx = true );
}

Add an interface for models having sub-model


<?php

namespace Illuminate\Foundation\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Illuminate\Contracts\Foundation\Application;

class DetectEnvironment
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if (! $app->configurationIsCached()) {
            try {
                (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
            } catch (InvalidPathException $e) {
                //
            }
        }
    }
}

<?php

namespace Illuminate\Foundation\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Illuminate\Contracts\Foundation\Application;

class DetectEnvironment
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if (! $app->configurationIsCached()) {
            $this->detectCustomEnvFile($app);

            try {
                (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
            } catch (InvalidPathException $e) {
                //
            }
        }
    }

    /**
     * Detect if a custom env file matching the APP_ENV exists.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    protected function detectCustomEnvFile($app)
    {
        $fileName = $app->environmentFile().'.'.env('APP_ENV');

        if (file_exists($app->environmentPath().'/'.$fileName)) {
            $app->loadEnvironmentFrom($fileName);
        }
    }
}

Load custom environment file if available


<?php

namespace AdobeConnectClient\Tests\Commands;

use AdobeConnectClient\Commands\Logout;

class LogoutTest extends TestCommandBase
{
    /**
     * return string
     */
    public function testExecute()
    {
        $command = new Logout();
        $command->setClient($this->client);

        $this->assertTrue($command->execute());

        return $this->client->getSession();
    }

    /**
     * @depends testExecute
     *
     * @param string $session
     */
    public function testLogoutSession($session)
    {
        $this->assertEquals('', $session);
    }
}

Create tests for Logout command

Create tests for Logout command


<?php
namespace Platformsh\Cli\Command\Project\Variable;

use Platformsh\Cli\Command\CommandBase;
use Platformsh\Cli\Console\AdaptiveTableCell;
use Platformsh\Cli\Util\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ProjectVariableGetCommand extends CommandBase
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('project:variable:get')
            ->setAliases(['project-variables', 'pvget'])
            ->addArgument('name', InputArgument::OPTIONAL, 'The name of the variable')
            ->addOption('pipe', null, InputOption::VALUE_NONE, 'Output the full variable value only (a "name" must be specified)')
            ->setDescription('View variable(s) for a project');
        Table::addFormatOption($this->getDefinition());
        $this->addProjectOption();
        $this->addExample('View the variable "example"', 'example');
        $this->setHiddenAliases(['project:variable:list']);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->validateInput($input);

        if ($name = $input->getArgument('name')) {
            $variable = $this->getSelectedProject()
                             ->getVariable($name);
            if (!$variable) {
                $this->stdErr->writeln("Variable not found: <error>$name</error>");

                return 1;
            }

            if ($input->getOption('pipe')) {
                $output->writeln($variable->value);
            }
            else {
                $output->writeln(sprintf('<info>%s</info>: %s', $variable->name, $variable->value));
            }

            return 0;
        }

        $results = $this->getSelectedProject()
                        ->getVariables();
        if (!$results) {
            $this->stdErr->writeln('No variables found');

            return 1;
        }

        if ($input->getOption('pipe')) {
            throw new \InvalidArgumentException('Specify a variable name to use --pipe');
        }

        $table = new Table($input, $output);

        $header = ['ID', 'Value', 'JSON', 'Build time', 'Runtime'];
        $rows = [];
        foreach ($results as $variable) {
            $rows[] = [
                new AdaptiveTableCell($variable->id, ['wrap' => false]),
                $variable->value,
                $variable->is_json ? 'Yes' : 'No',
                $variable->visible_build ? 'Yes' : 'No',
                $variable->visible_runtime ? 'Yes' : 'No',
            ];
        }

        $table->render($rows, $header);

        return 0;
    }

}

Add a Project Variable Get command.

Add a Project Variable Get command.


<?php
/**
 * This class should represent the whole text
 *
 * @author newloki
 */
namespace \Language\Text;
use \Language\Languages\LanguagesAbstract
    \Language\Word;

class Text
{
    /** @var string $_text */
    protected $_text;

    /** @var \Language\Languages\LanguagesAbstract $_language */
    protected $_language;

    /** @var array $_words */
    protected $_words = array();

    /**
     * Create an text object based on text as string and his corresponding
     * language
     *
     * @param  $_text
     * @param \Language\Languages\LanguagesAbstract $_language
     */
    public function __construct($_text, LanguagesAbstract $_language)
    {
        $this->_text = (string) $_text;
        $this->_language = $_language;
    }

    /**
     * Get an array of words for this text, if there are no words present,
     * this method call method to generate words from text
     *
     * @return array of \Language\Word\Word
     */
    public function getWords()
    {
        if(empty($this->_words)) {
            $this->_splitText();
        }

        return $this->_words;
    }

    /**
     * Set an word for this text, and give him a language (this give the
     * ability to use foreign words in text)
     *
     * @param  $_word
     * @param LanguagesAbstract|null $_language
     * @return void
     */
    public function setWord($_word, LanguagesAbstract $_language = null)
    {
        if (empty($_language)) {
            $_language = $this->_language;
        }

        $this->_words[$_word] = new Word($_word, $_language);
    }

    /**
     * Split this text into words and create a word object for each of them,
     * if there is nothing stored, else increase counter for this word
     *
     * @return void
     */
    protected function _splitText()
    {
        $words = str_word_count($this->_text, 1);
        foreach ($words as $word) {
            if (!array_key_exists($word, $this->_words)) {
                $this->_words[$word] = new Word($word, $this->_language);
            } else {
                /** @var $_word Word */
                $_word = $this->_words[$word];
                $_word->increaseCounter();
            }
        }
    }

    /**
     * Getter for language
     *
     * @return \Language\Languages\LanguagesAbstract|LanguagesAbstract
     */
    public function getLanguage()
    {
        return $this->_language;
    }
}

Add getter for language to text class

Add getter for language to text class


<?php

class BulkQueryTest extends \Codeception\TestCase\Test
{

    use \Codeception\Specify;

    const BULK_SIZE = 5;

    /**
     * @var \UnitTester
     */
    protected $tester;

    /**
     * @var \Nord\Lumen\Elasticsearch\Queries\Bulk\BulkQuery
     */
    private $query;

    /**
     * @inheritdoc
     */
    public function _before()
    {
        $this->query = new \Nord\Lumen\Elasticsearch\Queries\Bulk\BulkQuery(self::BULK_SIZE);
    }

    public function testActionHandling()
    {
        $this->specify('testing item handling', function () {
            verify($this->query->isReady())->false();

            for ($i = 0; $i < self::BULK_SIZE; $i++) {
                $this->query->addAction(new \Nord\Lumen\Elasticsearch\Queries\Bulk\BulkAction());
            }

            verify($this->query->hasItems())->true();
            verify($this->query->isReady())->true();

            $this->query->reset();
            verify($this->query->hasItems())->false();
        });

    }

    public function testSerialization()
    {
        $this->specify('checking serialization', function () {
            $index = [
                '_index' => 'foo',
                '_type'  => 'bar',
                '_id'    => 'baz',
            ];

            $body = [
                'foo' => 'bar',
            ];

            // Add two actions (same item twice)
            $action = new \Nord\Lumen\Elasticsearch\Queries\Bulk\BulkAction();
            $action->setAction(\Nord\Lumen\Elasticsearch\Queries\Bulk\BulkAction::ACTION_INDEX, $index)
                   ->setBody($body);

            $this->query->addAction($action)->addAction($action);

            verify($this->query->toArray())->equals([
                'body' => [
                    [
                        'index' => $index,
                        $body,
                    ],

                    [
                        'index' => $index,
                        $body,
                    ],

                ],
            ]);
        });
    }

}

Add unit tests for the bulk query and bulk action


Add Kosovo phone number specifications

Add Kosovo phone number specifications

http://en.wikipedia.org/wiki/Telephone_numbers_in_Kosovo


<?php

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

class CreateArticleAggregatedViewsWithIdTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('article_aggregated_views', 'article_aggregated_views_WITHOUT_ID');

        Schema::create('article_aggregated_views', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('article_id')->unsigned();
            $table->string('user_id')->nullable();
            $table->string('browser_id')->nullable();
            $table->date('date');
            $table->integer('pageviews')->default(0);
            $table->integer('timespent')->default(0);

            $table->unique(['article_id', 'user_id', 'browser_id', 'date'], 'unique_index');
            $table->index('user_id');
            $table->index('browser_id');
            $table->foreign('article_id', 'fk_article_id')->references('id')->on('articles');
        });

        DB::statement('INSERT INTO article_aggregated_views (article_id, user_id, browser_id, date, pageviews, timespent)
SELECT article_id, if(user_id = "", null, user_id) as user_id, browser_id, date, pageviews, timespent
FROM article_aggregated_views_WITHOUT_ID');

        Schema::dropIfExists('article_aggregated_views_WITHOUT_ID');
    }

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

Add primary ID and make user_id and browser_id columns nullable in article_aggregated_views table


<?php

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

$header = <<<EOF
This file is part of the Shade project.

(c) A51 doo <info@activecollab.com>. All rights reserved.
EOF;

return (new PhpCsFixer\Config('psr2'))
    ->setRules([
        'header_comment' => [
            'header' => $header,
            'location' => 'after_open',
        ],
        'function_typehint_space' => true,
        'method_argument_space' => true,
        'no_trailing_whitespace' => true,
        'no_whitespace_before_comma_in_array' => true,
        'whitespace_after_comma_in_array' => true,
        'no_multiline_whitespace_around_double_arrow' => true,
        'hash_to_slash_comment' => true,
        'include' => true,
        'trailing_comma_in_multiline_array' => true,
        'no_leading_namespace_whitespace' => true,
        'no_blank_lines_after_phpdoc' => true,
        'phpdoc_scalar' => true,
        'phpdoc_summary' => true,
        'self_accessor' => true,
        'no_trailing_comma_in_singleline_array' => true,
        'single_blank_line_before_namespace' => true,
        'space_after_semicolon' => true,
        'no_singleline_whitespace_before_semicolons' => true,
        'cast_spaces' => true,
        'standardize_not_equals' => true,
        'ternary_operator_spaces' => true,
        'trim_array_spaces' => true,
        'no_unused_imports' => true,
        'no_whitespace_in_blank_line' => true,
        'ordered_imports' => true,
        'array_syntax' => ['syntax' => 'short'],
        'phpdoc_align' => true,
        'return_type_declaration' => true,
        'single_quote' => true,
        'phpdoc_separation' => false,
        'phpdoc_no_package' => false,
        'no_mixed_echo_print' => false,
        'concat_space' => false,
        'simplified_null_return' => false,
        'single_blank_line_at_eof' => true,
    ])->setFinder((new PhpCsFixer\Finder())->in([
        __DIR__ . '/src',
        __DIR__ . '/test',
    ])
);

Add PHP code style fixer

Add PHP code style fixer


<?php

namespace Marein\Nchan\HttpAdapter;

use Marein\Nchan\Exception\NchanException;
use PHPUnit\Framework\TestCase;

class HttpStreamWrapperResponseTest extends TestCase
{
    /**
     * @test
     */
    public function itShouldBeCreatedWithItsValues(): void
    {
        $expectedStatusCode = 200;
        $expectedBody = 'my body';

        $response = new HttpStreamWrapperResponse($expectedStatusCode, $expectedBody);

        $this->assertEquals($expectedStatusCode, $response->statusCode());
        $this->assertEquals($expectedBody, $response->body());
    }

    /**
     * @test
     */
    public function itShouldBeCreatedFromStreamWrapperResponse(): void
    {
        $expectedStatusCode = 200;
        $expectedBody = 'my body';

        $response = HttpStreamWrapperResponse::fromResponse([
            'HTTP\1.1 200 OK'
        ], $expectedBody);

        $this->assertEquals($expectedStatusCode, $response->statusCode());
        $this->assertEquals($expectedBody, $response->body());
    }

    /**
     * @test
     * @dataProvider incorrectResponseHeadersProvider
     */
    public function itShouldThrowAnExceptionWhenIncorrectResponseHeadersArePassed(array $headers): void
    {
        $this->expectException(NchanException::class);

        HttpStreamWrapperResponse::fromResponse($headers, '');
    }

    /**
     * Returns various incorrect response headers.
     *
     * @return array
     */
    public function incorrectResponseHeadersProvider(): array
    {
        return [
            [['wrong response header']],
            [['HTT 200 OK']],
            [['HTTP/1.1 OK']],
            [['HTTP/1.1 -123']],
            [['']],
            [[]]
        ];
    }
}

Add unit test for HttpStreamWrapperResponse


#!/usr/bin/env php
<?php

/**
 * Generate C structs from a JSON file of chemical elements
 *
 * To run with the default data:
 *      ./generate-structs.php
 *
 * To run with some other JSON file:
 *      ./generate-structs.php /path/to/some/other/file
 *
 * The C code is printed to stdout.
 */

$filename = __DIR__ . "/elements.json";

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

try {
    echo array_to_structs(file_to_array($filename));
} catch (Exception $e) {
    die($e->getMessage() . "\n");
}

function file_to_array($filename) {
    if (!file_exists($filename)) {
        throw new Exception("File not found.");
    }
    return json_decode(file_get_contents($filename), false);
}

function array_to_structs(array $elements) {
    $buffer = "const Element elements[] = {\n";

    $buffer .= implode(", \n", array_map(function ($element) {
        return "\t{" . implode(", ", array(
            sprintf(".atomic = %d", $element->atomic),
            sprintf('.symbol = "%s"', $element->symbol),
            sprintf('.name = "%s"', $element->name)
        )) . "}";
    }, $elements));

    $buffer .= "\n};\n\n";
    $buffer .= sprintf("const uint8_t num_elements = %d;\n", count($elements));
    return $buffer;
}

Add script to generate the C structs containing the app's elements data.


<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Services\NoteService;
use App\Jobs\SyndicateToTwitter;
use App\Jobs\SyndicateToFacebook;
use Illuminate\Support\Facades\Queue;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class NoteServiceTest extends TestCase
{
    use DatabaseTransactions;

    public function test_syndicate_to_twitter_job_is_sent()
    {
        Queue::fake();

        $noteService = new NoteService();
        $note = $noteService->createNote([
            'content' => 'Hello Fred',
            'in-reply-to' => 'https://fredbloggs.com/note/abc',
            'syndicate' => ['twitter'],
        ]);

        Queue::assertPushed(SyndicateToTwitter::class);
    }

    public function test_syndicate_to_facebook_job_is_sent()
    {
        Queue::fake();

        $noteService = new NoteService();
        $note = $noteService->createNote([
            'content' => 'Hello Fred',
            'in-reply-to' => 'https://fredbloggs.com/note/abc',
            'syndicate' => ['facebook'],
        ]);

        Queue::assertPushed(SyndicateToFacebook::class);
    }

    public function test_syndicate_to_target_jobs_are_sent()
    {
        Queue::fake();

        $noteService = new NoteService();
        $note = $noteService->createNote([
            'content' => 'Hello Fred',
            'in-reply-to' => 'https://fredbloggs.com/note/abc',
            'syndicate' => ['twitter', 'facebook'],
        ]);

        Queue::assertPushed(SyndicateToTwitter::class);
        Queue::assertPushed(SyndicateToFacebook::class);
    }
}

Add some tests for syndication jobs

Add some tests for syndication jobs


<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

use Biblys\Data\Book;

class testBook extends PHPUnit_Framework_TestCase
{
    private $book;

    /**
     * Test setting an EAN
     */
    public function testSetEan()
    {
        $book = new Book();
        $ean = '9791091146135';

        $book->setEan($ean);

        $this->assertEquals($ean, $book->getEan(), "setEan should set an EAN");
    }

    /**
     * Test setting an invalid EAN
     * @expectedException Exception
     */
    public function testSetInvalidEan()
    {
        $book = new Book();
        $ean = '00777289';

        $book->setEan($ean);
    }

    /**
     * Test setting a title
     */
    public function testSetTitle()
    {
        $book = new Book();
        $title = 'Chants du cauchemar et de la nuit';

        $book->setTitle($title);

        $this->assertEquals($title, $book->getTitle(), "setTitle should set a title");
    }
}

Add tests for Book class

Add tests for Book class


<?php

namespace ForkCMS\Bundle\InstallerBundle\Requirement;

final class RequirementCategory
{
    /** @var string */
    private $name;

    /** @var Requirement[] */
    private $requirements;

    /**
     * @param string $name
     * @param Requirement[] $requirements
     */
    public function __construct($name, Requirement ...$requirements)
    {
        $this->name = $name;
        $this->requirements = $requirements;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return Requirement[]
     */
    public function getRequirements(): array
    {
        return $this->requirements;
    }

    /**
     * @return Requirement[]
     */
    public function getWarnings(): array
    {
        return array_filter(
            $this->requirements,
            function (Requirement $requirement) {
                return $requirement->getStatus()->isWarning();
            }
        );
    }

    /**
     * @return Requirement[]
     */
    public function getErrors(): array
    {
        return array_filter(
            $this->requirements,
            function (Requirement $requirement) {
                return $requirement->getStatus()->isError();
            }
        );
    }

    /**
     * @return bool
     */
    public function hasWarnings(): bool
    {
        return count($this->getWarnings()) > 0;
    }

    /**
     * @return bool
     */
    public function hasErrors(): bool
    {
        return count($this->getErrors()) > 0;
    }
}

Add a category to group requirements for fork


<?php
namespace Afonso\Soapi\Tests;

use PHPUnit_Framework_TestCase;

class SoapiTest extends PHPUnit_Framework_TestCase
{
    public function testSoapi()
    {
        /*
         * Temporary placeholder test to avoid
         * Travis builds to fail.
         */
    }
}

Add dummy test to avoid Travis builds to fail.

(Real tests should come pretty soon though.)


<?php
namespace Nayjest\ViewComponents\Test\Components;

use Nayjest\ViewComponents\Components\Container;
use Nayjest\ViewComponents\Components\Text;
use Nayjest\ViewComponents\Components\Repeater;
use PHPUnit_Framework_TestCase;

class RepeaterTest extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        $repeater = new Repeater(
            [
                ['value' => 1],
                ['value' => 2],
                ['value' => 3],
            ],
            [new Text]
        );
        self::assertEquals('123', $repeater->render());
    }

    public function testWithMultipleComponents()
    {
        $repeater = new Repeater(
            [
                ['value' => 1],
                ['value' => 2],
            ],
            [new Text, new Text]
        );
        self::assertEquals('1122', $repeater->render());
    }
    public function testWithContainer()
    {
        $repeater = new Repeater(
            [
                ['value' => 1],
                ['value' => 2],
            ],
            [
                new Container([
                    new Text('[')
                ]),
                new Text,
                new Container([
                    new Text(']')
                ])
            ]
        );
        self::assertEquals('[1][2]', $repeater->render());
    }
}

Test for Repeater component implemented

Test for Repeater component implemented


<?php

	function checkLogin($userID, $pass_hash, $linkID)
	{
		$userclause = mysql_real_escape_string("$userID");
		$passclause = mysql_real_escape_string("$pass_hash");
		$query = "SELECT * FROM users WHERE user_ID='$userID' AND password='$passclause'";
		$resultID = mysql_query($query, $linkID) or die("Data not found.");
		//$row = mysql_fetch_assoc($resultID);
		if(mysql_num_rows($resultID)>0){
			return true;
		}else{
			return false;
		}
	}
?>

Check Login code actually added this time around.


<?php

namespace DDPro\Admin\Config;

/**
 * Interface ModelServiceInterface
 *
 * This interface is used when a model config wants to provide a custom form with a custom
 * load / save handler for a model.
 *
 * The functions contained here include:
 *
 * * getBladeViewIndex -- provide a custom index page.
 * * getBladeViewForm -- provide a custom form.
 * * getFormData -- provide data for the form.
 * * saveFormData -- provide a custom save handler for the form.
 *
 * @package DDPro\Admin\Config
 */
interface ModelServiceInterface
{
    /**
     * Returns the name of the blade view used as the model "index" page.
     *
     * @return string
     */
    public function getBladeViewIndex();

    /**
     * Returns the name of the blade view used as the model create/edit form.
     *
     * @return string
     */
    public function getBladeViewForm();

    /**
     * Get the data to be displayed in the model edit form when editing an existing object.
     *
     * @param integer $id
     * @return array
     */
    public function getFormData($id=null);

    /**
     * Save handler
     *
     * May throw some kind of exception of the data save fails.
     *
     * @param integer $id
     * @param array $data
     * @return boolean
     */
    public function saveFormData($id=null, $data);
}

Add an interface to define custom form and load/save handlers


<?php

namespace PhpFlo\Component;

use PhpFlo\Component;
use PhpFlo\Port;

/**
 * Component for creating a simple queu of messages.
 *
 * All incomming messages are kept in memory. As soon as the queu reaches the
 * pre-configured size of 100 messages, the current list of messages is send.
 *
 * You can reconfigure the queu size of the component by sending a message to
 * the `size` input port of this component. If the incomming data is not a
 * positive integer, an error message will be send to the `err` out port of this
 * component.
 *
 * @author Marijn Huizendveld <marijn@pink-tie.com>
 */
class Queu extends Component
{
    /**
     * @var integer
     */
    private $size;

    /**
     * @var array<mixed>
     */
    private $messages;

    public function __construct()
    {
        $this->size = 100;
        $this->messages = array();

        $this->inPorts['in'] = new Port();
        $this->inPorts['size'] = new Port();

        $this->outPorts['err'] = new Port();
        $this->outPorts['messages'] = new Port();

        $this->inPorts['in']->on('data', array($this, 'onAppendQueu'));
        $this->inPorts['in']->on('detach', array($this, 'onStreamEnded'));

        $this->inPorts['size']->on('data', array($this, 'onResize'));
    }

    /**
     * @param mixed $data
     */
    public function onAppendQueu($data)
    {
        $this->messages[] = $data;

        $this->sendQueu();
    }

    public function onStreamEnded()
    {
        $this->flushQueu();
    }

    /**
     * @param mixed $data
     */
    public function onResize($data)
    {
        if (!is_int($data) || 0 > $data) {
            $dumped = var_dump($data);

            $this->outPorts['err']->send("Invalid queu size: '{$dumped}'. Queu resize operation expects a positive integer value.");
        }

        $this->size = $data;

        $this->sendQueu();
    }

    private function sendQueu()
    {
        if ($this->size =< count($this->messages)) {
            $this->flushQueu();
        }
    }

    private function flushQueu()
    {
        $this->outPorts['messages']->send($this->messages);
        $this->outPorts['messages']->disconnect();

        $this->messages = array();
    }
}

Add component for queuing messages.

Add component for queuing messages.

All incomming messages are kept in memory. As soon as the queu reaches the
pre-configured size of 100 messages, the current list of messages is send.

You can reconfigure the queu size of the component by sending a message to
the `size` input port of this component. If the incomming data is not a
positive integer, an error message will be send to the `err` out port of this
component.


<?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\Taxonomy\Model;

use Doctrine\Common\Collections\Collection;

/**
 * Taxons aware interface.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface TaxonsAwareInterface
{
    /**
     * Get all taxons.
     *
     * @param string $taxonomy
     *
     * @return Collection|TaxonInterface[]
     */
    public function getTaxons($taxonomy = null);

    /**
     * Set the taxons.
     *
     * @param Collection $collection
     */
    public function setTaxons(Collection $collection);

    /**
     * Has a taxon?
     *
     * @param TaxonInterface $taxon
     *
     * @return Boolean
     */
    public function hasTaxon(TaxonInterface $taxon);

    /**
     * Add taxon.
     *
     * @param TaxonInterface $taxon
     */
    public function addTaxon(TaxonInterface $taxon);

    /**
     * Remove taxon.
     *
     * @param TaxonInterface $taxon
     */
    public function removeTaxon(TaxonInterface $taxon);
}

Allow to get taxons from specific taxonomy


<?php

namespace UWaterlooAPI\Utils;

class ArrayUtil
{
    public static function getVal(array $array, ...$keys)
    {
        foreach ($keys as $key) {
            $array = $array[$key];
        }

        return $array;
    }

    /**
     * Filters elements from an array of associative arrays that don't contain a certain key/value pair.
     *
     * @param array $array The array of associative arrays to filter.
     * @param mixed $prop The key to filter by.
     * @param mixed $expectedVal The expected value which given key maps to.
     * @return array The filtered array.
     */
    public static function filterByProperty(array $array, $prop, $expectedVal)
    {
        // todo handle exceptions
        return array_filter($array, function ($val, $key) use ($prop, $expectedVal) {
            return $val[$prop] === $expectedVal;
        }, ARRAY_FILTER_USE_BOTH);
    }
}

Move array helper methods to a utility class.


<?php

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

class AddColumnsToCategorizePosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('type')->after('northstar_id')->default('photo')->comment('Describes the type of post submitted e.g. photo, call, voter-reg');
            $table->string('action_bucket')->after('type')->comment('Describes the bucket the action is tied to. A campaign could ask for multiple types of actions throught the life of the campaign.');
            $table->text('details')->after('remote_addr')->comment('A JSON field to store extra details about a post.');
        });
    }

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

Add a migration to add new columns to the posts table


Create the base test class

Create the base test class


<?php

namespace Sockets;

// modelled closely after React\EventLoop\StreamSelectLoop
class SelectPoller
{
    private $loop;
    private $pollInterval = 0.01;
    private $tid = null;
    private $readSockets = array();
    private $readListeners = array();
    private $writeSockets = array();
    private $writeListeners = array();

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

    public function resume()
    {
        if ($this->tid === null && ($this->read || $this->write)) {
            $this->tid = $this->loop->addPeriodicTimer($this->pollInterval, array($this, 'poll'));
        }
    }

    public function pause()
    {
        if ($this->tid !== null) {
            $this->loop->cancelTimer($this->tid);
            $this->tid = null;
        }
    }

    public function poll()
    {
        $read = $this->readSockets ? $this->readSockets : null;
        $write = $this->writeSockets ? $this->writeSockets : null;
        $ret = socket_select($read, $write, $x = null, 0);
        if ($ret) {
            foreach ($read as $socket) {
                $id = (int)$socket;
                if (isset($this->readListeners[$id])) {
                    call_user_func($this->readListeners[$id], $socket, $this);
                }
            }
            foreach ($write as $socket) {
                $id = (int)$socket;
                if (isset($this->writeListeners[$id])) {
                    call_user_func($this->writeListeners[$id], $socket, $this);
                }
            }
        } else if ($ret === false) {
            throw new Exception('Socket operation "socket_select()" failed: ' . socket_strerror(socket_last_error()));
        }
    }

    public function addReadSocket($socket, $listener)
    {
        $id = (int)$socket;
        if (!isset($this->readSockets[$id])) {
            $this->readSockets[$id] = $socket;
            $this->readListeners[$id] = $listener;
        }
    }

    public function addWriteSocket($socket, $listener)
    {
        $id = (int)$socket;
        if (!isset($this->writeSockets[$id])) {
            $this->writeSockets[$id] = $socket;
            $this->writeListeners[$id] = $listener;
        }
    }

    public function removeReadSocket($socket)
    {
        $id = (int)$socket;
        unset($this->readSockets[$id], $this->readListeners[$id]);
    }

    public function removeWriteSocket($socket)
    {
        $id = (int)$socket;
        unset($this->writeSockets[$id], $this->writeListeners[$id]);
    }

    public function removeSocket($socket)
    {
        $this->removeReadSocket($socket);
        $this->removeWriteSocket($socket);
    }
}

Add skeleton for combined poller

Add skeleton for combined poller


<?php

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

class ChangeDataTypeToLongtext extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$this->dropColumn();

		Schema::table('sprint_snapshots', function($t)
		{
			$t->longText('data');
		});
	}

	private function dropColumn()
	{
		Schema::table('sprint_snapshots', function($t)
		{
			$t->dropColumn('data');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		$this->dropColumn();

		Schema::table('sprint_snapshots', function($t)
		{
			$t->dropColumn('data');
		});
	}

}

Change data field for sprint snapshots to longText.


<?php
namespace Loct\Pinger\Provider;

use \Loct\Pinger\Notifier\MailgunNotifier;
use \Mailgun\Mailgun;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;

class NotifierProvider implements ServiceProviderInterface
{

    public function register(Container $pimple)
    {
        $pimple['notifier'] = function ($pimple) {
            $config = $pimple['config'];

            $apiKey = $config->get('pinger.notifications.mailgun.api_key');
            $domain = $config->get('pinger.notifications.mailgun.domain');
            $recipients = $config->get('pinger.notifications.mailgun.recipients');

            $mailgun = new Mailgun($apiKey);
            return new MailgunNotifier($mailgun, $domain, $recipients);
        };
    }

}

Isolate notifier in dedicated provider

Isolate notifier in dedicated provider


<?php

namespace Kibo\Phast\HTTP;

class ResponseTest extends \PHPUnit_Framework_TestCase {

    public function testETagGeneration() {
        $res = new Response();

        $empty = $res->getHeaders()['ETag'];
        $this->assertRegExp('/^[a-f0-9]{32}$/', $empty);
        $this->assertEquals($empty, $res->getHeaders()['ETag']);

        $res->setHeader('Hello', 'World');
        $withHeader = $res->getHeaders()['ETag'];
        $this->assertRegExp('/^[a-f0-9]{32}$/', $withHeader);
        $this->assertNotEquals($empty, $withHeader);

        $res->setContent('Hey!');
        $withContent = $res->getHeaders()['ETag'];
        $this->assertRegExp('/^[a-f0-9]{32}$/', $withContent);
        $this->assertNotEquals($withHeader, $withContent);
    }

}

Add a test for ETag generation

Add a test for ETag generation


<?php

namespace CommerceGuys\Platform\Cli\Tests;

use CommerceGuys\Platform\Cli\Helper\ShellHelper;

class ShellHelperTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Test ShellHelper::execute().
     */
    public function testExecute()
    {
        $shellHelper = new ShellHelper();

        // Find a command that will work on all platforms.
        $workingCommand = strpos(PHP_OS, 'WIN') !== false ? 'help' : 'pwd';

        // With $mustRun disabled.
        $this->assertNotEmpty($shellHelper->execute(array($workingCommand)));
        $this->assertFalse($shellHelper->execute(array('which', 'nonexistent')));

        // With $mustRun enabled.
        $this->assertNotEmpty($shellHelper->execute(array($workingCommand), null, true));
        $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException');
        $shellHelper->execute(array('which', 'nonexistent'), null, true);
    }

}

<?php

namespace CommerceGuys\Platform\Cli\Tests;

use CommerceGuys\Platform\Cli\Helper\ShellHelper;

class ShellHelperTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Test ShellHelper::execute().
     */
    public function testExecute()
    {
        $shellHelper = new ShellHelper();

        // Find a command that will work on all platforms.
        $workingCommand = strpos(PHP_OS, 'WIN') !== false ? 'help' : 'pwd';

        // With $mustRun disabled.
        $this->assertNotEmpty($shellHelper->execute(array($workingCommand)));
        $this->assertFalse($shellHelper->execute(array('which', 'nonexistent')));

        // With $mustRun enabled.
        $this->assertNotEmpty($shellHelper->execute(array($workingCommand), null, true));
        $this->setExpectedException('Exception');
        $shellHelper->execute(array('which', 'nonexistent'), null, true);
    }

}

Update tests now that ShellHelper throws a generic exception.


<?php

/**
 * Post upgrade, update filesizes for assets uploaded prior to FileSize capture
 *
 * @author marcus
 */
class UpdateFileSizeTask extends BuildTask
{
    public function run($request)
    {
        $number = $request->getVar('number');

        if (!$number) {
            $number = 50;
        }

        if (!$request->getVar('run')) {
            exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)");
        }

        $files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number);

        echo "Processing " . $number . " files
\n"; flush();

        foreach ($files as $file) {
            echo "Downloading $file->ClassName #{$file->ID} " . $file->Title . " ... "; flush();
            $file->ensureLocalFile();
            if ($file->localFileExists()) {
                $file->FileSize = filesize($file->getFullPath());
                echo "filesize {$file->FileSize} ... "; flush();
                if ($file instanceof CdnImage) {
                    $dim = $file->getDimensions();
                    echo "dimensions $dim ... "; flush();
                }
                unlink($file->getFullPath());
            } else {
                echo " cannot download $file->Title - $file->CDNFile
\n";
            }
            echo "
\n";
        }
    }

}

FIX Added task for updating FileSize and Dimensions


<?php

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

class CreateMediaBlocks extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('media_blocks', function(Blueprint $table) {
			$table->increments('id');

			$table->integer('media_id')->unsigned()->index();
			$table->integer('block_id')->unsigned()->index();

			$table->string('block_associated_field');

			$table->foreign('media_id', 'media_blocks_media_id_fk')
				->references('id')->on('media')->onDelete('cascade');

			$table->foreign('block_id', 'media_blocks_block_id_fk')
				->references('id')->on('blocks')->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('media_blocks', function(Blueprint $table) {
			$table->dropForeign('media_blocks_media_id_fk');
			$table->dropForeign('media_blocks_block_id_fk');
		});

		Schema::drop('media_blocks');
	}
}

Add media_blocks pivot table to efficiently attach media to fields (in blocks).


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for dropFirst Mimic library function.
 *
 * @since 0.1.0
 */
class FirstIndexOfFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		$boolean = array(0, 1, false, true);
		$integer = array('1', 1);
		$float = array('1.2', 1, 1.2);
		$collection = array(0, 1, false, true, 1.0, 'something', 'else', '1');
		return array(
			array(1, false, true, $boolean),
			array(0, false, false, $boolean),
			array(3, true, true, $boolean),
			array(0, true, false, $boolean),
			array(1, 1, true, $integer),
			array(0, 1, false, $integer),
			array(2, 1.2, true, $float),
			array(0, 1.2, false, $float),
			array(7, '1', true, $collection),
			array(1, '1', false, $collection),
			array(6, 'else', true, $collection),
			array(5, 'something', true, $collection),
		);
	}

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

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\firstIndexOf
	 */
	public function testResultsCallback($expected, $value, $strict, $collection) {
		$self = $this;
		$callback = function($element, $index, $array) use ($self, $collection) {
			$self->assertSame($collection, $array, 'callback collection is different from given');
			$self->assertEquals($collection[$index], $element, 'element does not match element with index at given collection');
			return $index === 1;
		};
		$this->assertEquals(1, F\firstIndexOf($collection, $callback));
	}
}

Add first index of test suite.

Add first index of test suite.


<?php

namespace Tests\Bulb;

use Yeelight\Bulb\Exceptions\BulbCommandException;
use Yeelight\Bulb\Response;

class ResponseTest extends \PHPUnit_Framework_TestCase
{
    public function test_success_Response()
    {
        $response = new Response(
            [
                'id' => 1,
                'result' => ['foo']
            ]
        );

        $this->assertTrue($response->isSuccess());
        $this->assertEquals(1, $response->getDeviceId());
        $this->assertEquals(['foo'], $response->getResult());
    }

    public function test_error_Response()
    {
        $response = new Response(
            [
                'id' => 1,
                'error' => [
                    'code' => 500,
                    'message' => 'error'
                ]
            ]
        );

        $this->assertFalse($response->isSuccess());
        $this->assertEquals(1, $response->getDeviceId());
        $this->assertEmpty($response->getResult());
        $this->assertInstanceOf(BulbCommandException::class, $response->getException());
    }
}

Add unit tests for Response

Add unit tests for Response


<?php

$type2attr = [
    'article' => [
        'required' => ['author', 'title', 'journal', 'year'],
        'optional' => ['volume', 'number', 'pages', 'month', 'note']
    ],
    'book' => [
        'required' => ['author', 'title', 'publisher', 'year'],
        'optional' => ['volumn', 'series', 'address', 'edition', 'month', 'note']
    ],
    'booklet' => [
        'required' => ['title'],
        'optional' => ['author', 'howpublished', 'address', 'month', 'year', 'note']
    ],
    'conference' => [
        'required' => ['author', 'title', 'booktitle', 'year'],
        'optional' => ['editor', 'volume', 'series', 'pages', 'address', 'month', 'organization', 'publisher', 'note']
    ],
    'inbook' => [
        'required' => ['author', 'title', 'pages', 'publisher', 'year'],
        'optional' => ['volume', 'series', 'type', 'address', 'edition', 'month', 'note']
    ],
    'incollection' => [
        'required' => ['author', 'title', 'booktitle', 'publisher', 'year'],
        'optional' => [ 'editor', 'volume', 'series', 'type', 'chapter', 'pages', 'address', 'edition', 'month', 'note']
    ],
    'inproceedings' => [
        'required' => ['author', 'title', 'booktitle', 'year'],
        'optional' => ['editor', 'volume', 'series', 'pages', 'address', 'month', 'organization', 'publisher', 'note']
    ],
    'manual' => [
        'required' => ['title'],
        'optional' => ['author', 'organization', 'address', 'editor', 'month', 'year', 'note']
    ],
    'mastersthesis' => [
        'required' => ['author', 'title', 'school', 'year'],
        'optional' => ['type', 'address', 'month', 'note']
    ],
    'misc' => [
        'required' => [],
        'optional' => ['author', 'title', 'howpublished', 'month', 'year', 'note']
    ],
    'phdthesis' => [
        'required' => ['author', 'title', 'school', 'year'],
        'optional' => ['type', 'address', 'month', 'note']
    ],
    'proceedings' => [
        'required' => ['title', 'year'],
        'optional' => ['editor', 'volume', 'series', 'address', 'month', 'publisher', 'organization', 'note']
    ],
    'techreport' => [
        'required' => ['author', 'title', 'institution', 'year'],
        'optional' => ['type', 'number', 'address', 'month', 'note']
    ],
    'unpublished' => [
        'required' => ['author', 'title', 'note'],
        'optional' => ['month', 'year']
    ]
];

Implement a rough database query function


<?php

class Stripe_SubscriptionTest extends Stripe_TestCase
{

  public function testCreateUpdateCancel()
  {
    $planID = 'gold-' . self::randomString();
    self::retrieveOrCreatePlan($planID);

    $customer = self::createTestCustomer();

    $sub = $customer->subscriptions->create(array('plan' => $planID));

    $this->assertSame($sub->status, 'active');
    $this->assertSame($sub->plan->id, $planID);

    $sub->quantity = 2;
    $sub->save();

    $sub = $customer->subscriptions->retrieve($sub->id);
    $this->assertSame($sub->status, 'active');
    $this->assertSame($sub->plan->id, $planID);
    $this->assertSame($sub->quantity, 2);

    $sub->cancel(array('at_period_end' => true));

    $sub = $customer->subscriptions->retrieve($sub->id);
    $this->assertSame($sub->status, 'active');
    // @codingStandardsIgnoreStart
    $this->assertTrue($sub->cancel_at_period_end);
    // @codingStandardsIgnoreEnd
  }

  public function testDeleteDiscount()
  {
    $planID = 'gold-' . self::randomString();
    self::retrieveOrCreatePlan($planID);

    $couponID = '25off-' . self::randomString();
    self::retrieveOrCreateCoupon($couponID);

    $customer = self::createTestCustomer();

    $sub = $customer->subscriptions->create(
        array(
            'plan' => $planID,
            'coupon' => $couponID
        )
    );

    $this->assertSame($sub->status, 'active');
    $this->assertSame($sub->plan->id, $planID);
    $this->assertSame($sub->discount->coupon->id, $couponID);

    $sub->deleteDiscount();
    $sub = $customer->subscriptions->retrieve($sub->id);
    $this->assertNull($sub->discount);
  }
}

Add phpunit test for Stripe_Subscription


<?php
namespace Mrimann\CoMo\Domain\Repository;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "Mrimann.CoMo".          *
 *                                                                        *
 *                                                                        */

use TYPO3\Flow\Annotations as Flow;

/**
 * A repository for Repositories
 *
 * @Flow\Scope("singleton")
 */
class RepositoryRepository extends \TYPO3\Flow\Persistence\Repository {

	// add customized methods here

}
?>

[FEATURE] Add a repository class for Git-Repositories


<?php

use \Bruno\AdobeConnectClient\API;
use \Bruno\AdobeConnectClient\RequestHandler;

// If want change the cURL Options
$requestHandler = new RequestHandler(
    'https://user.adobeconnect.com',
    [
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0
    ]
);

$api = new API($requestHandler);

Add an example using the new RequestHandler


<?php

namespace Becklyn\AssetsBundle\tests\File;

use Becklyn\AssetsBundle\Entry\EntryNamespaces;
use Becklyn\AssetsBundle\File\FileLoader;
use Becklyn\AssetsBundle\Processor\ProcessorRegistry;
use PHPUnit\Framework\TestCase;

class FileLoaderTest extends TestCase
{
    /**
     * @var FileLoader
     */
    private $loader;

    /**
     * @var string
     */
    private $fixtures = __DIR__ . "/../fixtures";

    protected function setUp ()
    {
        $entryNamespaces = new EntryNamespaces($this->fixtures, [
            "bundles" => "public/bundles"
        ]);

        $processorRegistry = $this->getMockBuilder(ProcessorRegistry::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->loader = new FileLoader($entryNamespaces, $processorRegistry);
    }

    public function dataProviderValid ()
    {
        return [
            ["@bundles/test/css/app.css", "{$this->fixtures}/public/bundles/test/css/app.css"],
            ["@bundles/test/js/test.js", "{$this->fixtures}/public/bundles/test/js/test.js"],
        ];
    }

    /**
     * @dataProvider dataProviderValid
     *
     * @param string $assetPath
     * @param string $expectedFile
     * @throws \Becklyn\AssetsBundle\Exception\AssetsException
     */
    public function testValid (string $assetPath, string $expectedFile)
    {
        self::assertStringEqualsFile($expectedFile, $this->loader->loadFile($assetPath));
    }

    public function dataProviderInvalid ()
    {
        return [
            ["@invalid/test.js"],
            ["@bundles/test/js/doesnt_exist.js"],
            ["@Invalid/test.js"],
        ];
    }

    /**
     * @dataProvider dataProviderInvalid
     * @param string $assetPath
     *
     * @expectedException \Becklyn\AssetsBundle\Exception\AssetsException
     */
    public function testInvalid (string $assetPath)
    {
        $this->loader->loadFile($assetPath);
    }
}

Add tests for file loader

Add tests for file loader


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

function dumpWriteResults(MongoDB\WriteResult $result) {
    printf("Inserted %d documents, upserted %d, updated %d and deleted %d\n",
        $result->getInsertedCount(), $result->getUpsertedCount(),
        $result->getModifiedCount(), $result->getDeletedCount()
    );

    if ($result->getUpsertedCount()) {
        foreach ($result->getUpsertedIds() as $index => $id) {
            printf("upsertedId[%d]: %s", $index, $id);
        }
    }
}
function dumpCollection($collection) {
    printf("\n---\nDumping all documents in: %s.%s\n",
        $collection->getDatabaseName(),
        $collection->getCollectionName()
    );
    $n = 0;
    foreach($collection->find() as $document) {
        var_dump($document);
        $n++;
    }
    printf("Found %d documents\n", $n);
}

$manager = new MongoDB\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "crud.bulkWrite");
$result = $collection->bulkWrite([
    [
        "insertOne" => [
            [
                "name" => "Hannes Magnusson",
                "company" => "10gen",
            ]
        ],
    ],
    [
        "insertOne" => [
            [
                "name" => "Jeremy Mikola",
                "company" => "10gen",
            ]
        ],
    ],
    [
        "updateMany" => [
            ["company" => "10gen"],
            ['$set' => ["company" => "MongoDB"]],
        ],
    ],
    [
        "updateOne" => [
            ["name" => "Hannes Magnusson"],
            ['$set' => ["viking" => true]],
        ],
    ],
]);

dumpWriteResults($result);
dumpCollection($collection);

$result = $collection->bulkWrite([
    [
        "deleteOne" => [
            ["company" => "MongoDB"],
        ],
    ],
    [
        "updateOne" => [
            ["name" => "Hannes Magnusson"],
            ['$set' => ["nationality" => "Icelandic"]],
            ["upsert" => true],
        ],
    ],
    [
        "deleteMany" => [
            ["nationality" => [ '$ne' => "Icelandic"]],
        ],
    ],
]);

echo "\n\n";
dumpWriteResults($result);
dumpCollection($collection);

$result = $collection->bulkWrite([
    [
        "deleteMany" => [
            [],
        ],
    ],
]);

echo "\n\n";
dumpWriteResults($result);
dumpCollection($collection);

Add example referenced from Collection::bulkWrite()


<?php
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');

if ( ! isset($_POST["value"]) ) {

	/* One or more required inputs aren't set. */
	exit("");

} else {

	/* Bootstrap EDMS and only load database */
	require_once '../../init.php';

	/* Store values */
	$id = $_POST["value"];

	/* Get access to database */
	global $edmsdb;

	try
	{
		/* Prepare select statement */
	    if ( $id === "all" ) :

	    	// Query for all parts
	    	$query = $edmsdb->prepare('SELECT part_name, part_number, stock_amt, cost_inv, cost_retail FROM parts');

	    else :

	    	// Query for a specific part
			$query = $edmsdb->prepare('SELECT part_name, part_number, stock_amt, cost_inv, cost_retail FROM parts WHERE id = :id');

			// Bind parameters and set data types
			$query->bindParam(":id", $id ,PDO::PARAM_INT );

		endif;

		/* Execute query and check if successful */
		if ( $query->execute() ) {

			$partsInfo = array();

			foreach ( $query->fetchAll() as $parts ) {
				$partsInfo["part_name"] = $parts["part_name"];
				$partsInfo["part_number"] = $parts["part_number"];
				$partsInfo["stock_amt"] = $parts["stock_amt"];
				$partsInfo["cost_inv"] = $parts["cost_inv"];
				$partsInfo["cost_retail"] = $parts["cost_retail"];
			}
			/**
			 * Lookup was successful
			 *
			 * Send JSON result back to page
			 */
			$result = array(
				"success" => "true",
				"parts" => $partsInfo
			);

			echo json_encode($result);

			return true;
		}

	}
	catch (PDOException $e)
	{
		echo json_encode(
			array(
				"success" => "false",
				"message" => "There was an error selecting data. Contact system administrator."
			) );

		return false;
	}
}
?>

Add Search Part AJAX feature

Add Search Part AJAX feature


<?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\Generic\District;

/**
 * This is the district extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class DistrictExtractorTest extends AbstractPropertyExtractorTest
{
    public function testExtractDistrictName()
    {
        $text = [
            'freguesia de Amora, Concelho de Seixal, Distrito de Setúbal' => 'Setúbal',
        ];

        foreach ($text as $input => $expected) {
            $districtId = $this->extractor->district($input, null);

            $this->assertNotNull($districtId);
            $this->assertSame($expected, District::find($districtId)->name);
        }
    }
}

Add the district extractor test

Add the district extractor test


<?php

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

/*
 * Compare lookup in a list (O(n)) vs lookup in a set (O(1))
 */

use mre\PHPench\BenchmarkInterface;

abstract class AbstractBenchmark implements  BenchmarkInterface
{
    protected $testList;
    protected $testSet;

    function setUp($arrSize)
    {
        // In PHP lists and sets are both implemented as arrays
        $this->testList = [];
        $this->testSet = [];

        for ($i=1; $i<$arrSize; $i++)
        {
            $randKey = rand(0, 1000*$arrSize);

            // Set element in the list
            $this->testList[] = $randKey;

            // Set element in the set
            $this->testSet[$randKey] = True;
        }
    }
}

class BenchmarkListLookup extends AbstractBenchmark
{
    public function execute() {
        $randKey = rand(1000, 10000);
        foreach($this->testList as $id)
        {
            if ($randKey == $id)
            {
                // Key in array
                return true;
            }
        }
        // Key not in array
        return false;
    }
}

class BenchmarkSetLookup extends AbstractBenchmark
{
    public function execute() {
        $randKey = rand(1000, 10000);
        return isset($this->testSet[$randKey]);
    }
}

// Create a new benchmark instance
$phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator);

// Use GnuPlot for output
$oOutput = new \mre\PHPench\Output\GnuPlotOutput('test2.png', 1024, 768);

// Alternatively, print the values to the terminal
//$oOutput = new \mre\PHPench\Output\CliOutput();

$oOutput->setTitle('Compare set and list lookup in PHP');
$phpench->setOutput($oOutput);

// Add your test to the instance
$phpench->addBenchmark(new BenchmarkSetLookup, 'set');
$phpench->addBenchmark(new BenchmarkListLookup, 'list');

// Run the benchmark and plot the results in realtime.
// With the second parameter you can specify
// the start, end and step for each call
$phpench->setInput(range(1,pow(2,16), 1024));
$phpench->setRepetitions(4);
$phpench->run();

Add example: list vs set lookup

Add example: list vs set lookup


<?php

namespace JPB\WP\Dev;

use function wp_list_filter;

trait FactoryTrait {

	protected $_cached = [];

	/**
	 * Retrieve an object from a cached slot within the factory.
	 *
	 * Methods in the factory class that create objects will use some property as a unique identifier that is the key
	 * within the storage array. By default, that key is what's used for the lookup. Optionally, methods may provide a
	 * property within objects themselves that will be used for the lookup. If provided, rather than look the object up
	 * by its primary key, this method will use wp_list_pluck() to find all objects with the specified property matching
	 * the lookup value, then return the first result.
	 *
	 * @param string $slot   The internal cache slot in which to look
	 * @param mixed  $lookup The value to look up by
	 * @param bool   $key    Optional key under which to look for the value
	 *
	 * @return mixed|null
	 */
	protected function retrieveObject( $slot, $lookup, $key = false ) {
		if ( ! isset( $this->_cached[ $slot ] ) ) {
			$this->_cached[ $slot ] = [];

			return null;
		}
		if ( $key === false ) {
			return isset( $this->_cached[ $slot ][ $lookup ] ) ? $this->_cached[ $slot ][ $lookup ] : null;
		}
		$objects = wp_list_filter( $this->_cached[ $slot ], [ $key => $lookup ] );

		return $objects ? reset( $objects ) : null;
	}

	/**
	 * Store an object in an internal cache slot
	 *
	 * Returns the stored object for simpler return statements.
	 *
	 * This method can be used to bust the cache of an object, so consider only using this method in conjunction with
	 * retrieveObject to make sure you don't accidentally overwrite an existing object without meaning to.
	 *
	 * @param string $slot   The cache slot in which to store the object
	 * @param mixed  $key    The key for the object
	 * @param mixed  $object The object to store
	 *
	 * @return mixed
	 */
	protected function storeObject( $slot, $key, $object ) {
		if ( ! isset( $this->_cached[ $slot ] ) ) {
			$this->_cached[ $slot ] = [];
		}
		$this->_cached[ $slot ][ $key ] = $object;

		return $object;
	}

}

Add a factory trait for tracking cached objects


<?php

namespace Dan\Shopify;

/**
 * Interface ShopifyApiInterface
 */
interface HasShopifyClientInterface
{
    /** @return string */
    public function getShop();

    /** @return string */
    public function getToken();
}

Add interface for another client to retrieve a valid client.


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

/**
 * Constraint for ensuring a header does not contain a value.
 *
 * @internal
 */
class HeaderNotContains extends HeaderEquals
{

    /**
     * Checks assertion
     *
     * @param mixed $other Expected content
     * @return bool
     */
    public function matches($other)
    {
        return parent::matches($other) === false;
    }

    /**
     * Assertion message
     *
     * @return string
     */
    public function toString()
    {
        return sprintf("is not in header '%s'", $this->headerName);
    }
}

Add constraint class for header not contains


<?php

return [
    'aries' => 'Áries',
    'taurus' => 'Touro',
    'gemini' => 'Gêmeos',
    'cancer' => 'Câncer',
    'leo' => 'Leão',
    'virgo' => 'Virgem',
    'libra' => 'Libra',
    'scorpio' => 'Escorpião',
    'sagittarius' => 'Sargitário',
    'capricorn' => 'Capricórnio',
    'aquarius' => 'Aquário',
    'pisces' => 'Peixes'
];

Revert "Revert "Including language Portuguese Brazil""

This reverts commit 5ce0123660faa559f67d62d259561620a067078a.


<?php

namespace HCLabs\Bills\Controller;

use HCLabs\Bills\Command\Bus\CommandBusInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class AccountController
{
    /** @var CommandBusInterface */
    private $commandBus;

    /** @var UrlGeneratorInterface */
    private $urlGenerator;

    /** @var FormFactoryInterface */
    private $formFactory;

    /** @var \Twig_Environment */
    private $templating;

    public function __construct(
        \Twig_Environment $templating,
        UrlGeneratorInterface $urlGenerator,
        CommandBusInterface $commandBus,
        FormFactoryInterface $formFactory
    ) {
        $this->templating = $templating;
        $this->urlGenerator = $urlGenerator;
        $this->commandBus = $commandBus;
        $this->formFactory = $formFactory;
    }

    /**
     * @return Response
     */
    public function openAction()
    {
        return $this->getFormResponse($this->createAccountForm());
    }

    /**
     * @param Request $request
     * @return RedirectResponse|Response
     */
    public function processAccountCreationAction(Request $request)
    {
        $form = $this->createAccountForm();
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->commandBus->execute($form->getData());

            return new RedirectResponse(
                $this->urlGenerator->generate('hclabs_bills.dashboard_controller.index')
            );
        }

        return $this->getFormResponse($form);
    }

    /**
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createAccountForm()
    {
        return $this->formFactory->create(
            'hclabs_bills_open_account_type',
            null,
            ['action' => $this->urlGenerator->generate('hclabs_bills.account_controller.process')]
        );
    }

    /**
     * @param  FormInterface $form
     * @return Response
     */
    private function getFormResponse(FormInterface $form)
    {
        return new Response(
            $this->templating->render(
                '@HCLabsBills/Account/open.html.twig',
                ['form' => $form->createView()]
            )
        );
    }
}

[Controller] Create controller for account with methods to open and process an account


<?php
namespace Bolt\Tests\Composer\Action;

use Bolt\Tests\BoltUnitTest;

abstract class ActionUnitTest extends BoltUnitTest
{
    public function setUp()
    {
        $app = $this->getApp();
        $action = $app['extend.action']['json'];
        $action->updateJson();
    }

    protected function getApp()
    {
        $bolt = parent::getApp();
        $bolt['extend.action.options']['basedir'] = $bolt['resources']->getPath('extensions');
        $bolt['extend.action.options']['composerjson'] = $bolt['resources']->getPath('extensions') . '/composer.json';
        return $bolt;
    }
}

[Tests] Add a base class for Bolt\Composer\Action tests


<?

// callback controller
class Bitpay_Bitcoins_IndexController extends Mage_Core_Controller_Front_Action {

	// bitpay's IPN lands here
	public function indexAction() {
		require 'lib/bitpay/bp_lib.php';

		$apiKey = Mage::getStoreConfig('payment/Bitcoins/api_key');
		$invoice = bpVerifyNotification($apiKey);

		if (is_string($invoice))
			Mage::log("bitpay callback error: $invoice");
		else {
			// get the order
			if (isset($invoice['posData']['quoteId'])) {
				$quoteId = $invoice['posData']['quoteId'];
				$order = Mage::getModel('sales/order')->load($quoteId, 'quote_id');
			}
			else {
				$orderId = $invoice['posData']['orderId'];
				$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
			}

			// save the ipn so that we can find it when the user clicks "Place Order"
			Mage::getModel('Bitcoins/ipn')->Record($invoice);

			// update the order if it exists already
			if ($order->getId())
				switch($invoice['status']) {
				case 'confirmed':
				case 'complete':
					foreach($order->getInvoiceCollection() as $i)
						$i->pay()
							->save();
					$order->setState($order::STATE_PROCESSING, true)
						->save();
					break;
				}
		}
	}

}

?>

<?

// callback controller
class Bitpay_Bitcoins_IndexController extends Mage_Core_Controller_Front_Action {

	// bitpay's IPN lands here
	public function indexAction() {
		require 'lib/bitpay/bp_lib.php';

		$apiKey = Mage::getStoreConfig('payment/Bitcoins/api_key');
		$invoice = bpVerifyNotification($apiKey);

		if (is_string($invoice))
			Mage::log("bitpay callback error: $invoice");
		else {
			// get the order
			if (isset($invoice['posData']['quoteId'])) {
				$quoteId = $invoice['posData']['quoteId'];
				$order = Mage::getModel('sales/order')->load($quoteId, 'quote_id');
			}
			else {
				$orderId = $invoice['posData']['orderId'];
				$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
			}

			// save the ipn so that we can find it when the user clicks "Place Order"
			Mage::getModel('Bitcoins/ipn')->Record($invoice);

			// update the order if it exists already
			if ($order->getId())
				switch($invoice['status']) {
				case 'confirmed':
				case 'complete':
					foreach($order->getInvoiceCollection() as $i)
						$i->pay()
							->save();
					$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)
						->save();
					break;
				}
		}
	}

}

?>

Use class name instead of object to reference constant (compile error fix on some versions of php)


<?php

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

class AddTitleAndDescriptionColumnsToSnippetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('snippets', function (Blueprint $table) {
          $table->string('title');
          $table->string('description');
        });
    }

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

Add title and description columns to snippets table migration


<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130425145821_add_AccountPlan extends BaseMigration
{
    public function up(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "CREATE TABLE AccountPlan (
                id INT AUTO_INCREMENT NOT NULL,
                name VARCHAR(255) NOT NULL,
                isVisible TINYINT(1) NOT NULL,
                UNIQUE INDEX UNIQ_F6643B305E237E06 (name),
                PRIMARY KEY(id))
                DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB",
            "ALTER TABLE AccountPlanConstraint ADD constraint_id INT",
            "ALTER TABLE AccountPlanConstraint ADD CONSTRAINT FK_E18FF0B7E3087FFC FOREIGN KEY (constraint_id) REFERENCES AccountPlan (id)",
            "CREATE INDEX IDX_E18FF0B7E3087FFC ON AccountPlanConstraint (constraint_id)"
        );

        $this->statements['sqlite'] = array(
            "CREATE TABLE AccountPlan (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                name VARCHAR(255) NOT NULL,
                isVisible TINYINT(1) NOT NULL)",
            "CREATE UNIQUE INDEX UNIQ_F6643B305E237E06 ON AccountPlan (name)",
            "ALTER TABLE AccountPlanConstraint ADD constraint_id INT",
            // Creating of foreign key constraint removed for sqlite as it is not supported
            "CREATE INDEX IDX_E18FF0B7E3087FFC ON AccountPlanConstraint (constraint_id)"
        );

        parent::up($schema);
    }

    public function down(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "ALTER TABLE AccountPlanConstraint DROP FOREIGN KEY FK_E18FF0B7E3087FFC",
            "DROP TABLE AccountPlan",
            "DROP INDEX IDX_E18FF0B7E3087FFC ON AccountPlanConstraint",
            "ALTER TABLE AccountPlanConstraint DROP constraint_id"
        );

        $this->statements['sqlite'] = array(
            "ALTER TABLE AccountPlanConstraint DROP FOREIGN KEY FK_E18FF0B7E3087FFC",
            "DROP TABLE AccountPlan",
            "DROP INDEX IDX_E18FF0B7E3087FFC ON AccountPlanConstraint",
            "ALTER TABLE AccountPlanConstraint DROP constraint_id"
        );

        parent::down($schema);
    }
}

Add migration for AccountPlan entity

Add migration for AccountPlan entity


<?php
/**
 * JsMinifyTest.php
 * @author Dylan Ferris
 * @link https://github.com/acerix
 */

namespace rmrevin\yii\minify\tests\unit\view;

use rmrevin\yii\minify\components\JS;
use rmrevin\yii\minify\tests\unit\TestCase;

/**
 * Class JSTest
 * @package rmrevin\yii\minify\tests\unit\view
 */
class JSTest extends TestCase
{

    public function testRemoveJsComments()
    {

        $str = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(/\//g,'');//do not remove the regex //
HTTP+'//www.googleadservices.com/pagead/conversion'
";

        $this->assertEquals(
            "

this1
this2
this3
this4
this5 http://removecomment.com
id = id.replace(/\//g,'');
HTTP+'//www.googleadservices.com/pagead/conversion'
",
            JS::removeJsComments($str)
        );

    }
}

Add unit test for JS::removeJsComments()


<?php

namespace Backend\Modules\Blog\Tests\Action;

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

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

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

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

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

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

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

Test that you need to be logged in to see the tags index action


<?php
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * Hprose/Swoole/Client.php                               *
 *                                                        *
 * hprose swoole client library for php 5.3+              *
 *                                                        *
 * LastModified: Apr 17, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

namespace Hprose\Swoole {
    class Client {
        private $real_client = null;
        private function initUrl($url) {
            if ($url) {
                $p = parse_url($url);
                if ($p) {
                    switch (strtolower($p['scheme'])) {
                        case 'tcp':
                        case 'tcp4':
                        case 'tcp6':
                        case 'unix':
                            $this->real_client = new \Hprose\Swoole\Socket\Client($url);
                            break;
                        case 'http':
                        case 'https':
                            $this->real_client = new \Hprose\Http\Client($url);
                            break;
                        default:
                            throw new \Exception("Only support http, https, tcp, tcp4, tcp6 or unix scheme");
                            break;
                    }
                }
                else {
                    throw new \Exception("Can't parse this url: " . $url);
                }
            }
        }
        public function __construct($url = '') {
            $this->initUrl($url);
        }
        public function useService($url = '', $namespace = '') {
            $this->initUrl($url);
            if ($this->real_client) {
                return $this->real_client->useService('', $namespace);
            }
            return null;
        }
        public function invoke($name, &$args = array(), $byref = false, $mode = ResultMode::Normal, $simple = null, $callback = null) {
            if ($this->real_client) {
                return $this->real_client->invoke($name, $args, $byref, $mode, $simple, $callback);
            }
            return null;
        }
        public function __call($name, $args) {
            return call_user_func_array(array($this->real_client, $name), $args);
        }
        public function __set($name, $value) {
            $this->real_client->$name = $value;
        }
        public function __get($name) {
            return $this->real_client->$name;
        }
        public function __isset($name) {
            return isset($this->real_client->$name);
        }
        public function __unset($name) {
            unset($this->real_client->$name);
        }
    }
}

Refactor hprose server and client based on swoole


<?php
/**
 * List dataset(s)
 * Written by Ryan Yonzon <hello@ryanyonzon.com>
 */

set_include_path("vendor/google/apiclient/src/" . PATH_SEPARATOR . get_include_path());

require_once 'Google/Client.php';
require_once 'Google/Service/Bigquery.php';

// configuration stuff
$config = require_once 'config/Credentials.php';

$project_id = 'PROJECT-ID-HERE';

// create Google Client
$client = new Google_Client();
$client->setApplicationName("BigQuery CLI");

$key = file_get_contents('key/' . $config->key_filename);

$client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
    $config->service_account_name,
    array(
        'https://www.googleapis.com/auth/bigquery'
        ),
        $key
    )
);
$client->setClientId($config->client_id);

// create BigQuery service
$service = new Google_Service_Bigquery($client);

// list dataset(s)
$options = array();
$response = $service->datasets->listDatasets($project_id, $options);

print_r($response);

Add list dataset (sample) script.

Add list dataset (sample) script.


<?php

namespace SimplyTestable\WebClientBundle\Tests\Controller\View\Test\Results\ByTaskType\IndexAction;

use SimplyTestable\WebClientBundle\Tests\Controller\Base\RoutingTest as BaseRoutingTest;

class RoutingTest extends BaseRoutingTest {

    protected function getRouteParameters() {
        return array(
            'website' => 'http://example.com',
            'test_id' => 1,
            'task_type' => 'html+validation'
        );
    }

}

Add results by task type controller routing test


<?php

require_once('../src/ColoCrossing.php');

$colocrossing_client = new ColoCrossing_Client();
$colocrossing_client->setAPIToken('YOUR_API_TOKEN');

?>

List Devices Like Name

<?php

$options = array(
	'sort' => 'id'
);

$name = 'COLO-01'; //Enter your device name here
$devices = $colocrossing_client->devices->findLikeName($name, $options);

foreach ($devices as $key => $device)
{
	echo '
Device #' . $device->getId() . ' - ' . $device->getName() . '
';
}

?>

Add Example of Filtering Devices By Name


<?php
/**
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package GitServiceMove
 */
namespace GitServiceMove;

use Symfony\Component\Console\Application as SymfonyApplication;

/**
 * This object is the root of all process, it embed the standard launch behaviour
 * @package GitServiceMove
 */
class Application extends SymfonyApplication
{
    public function __construct()
    {
        parent::__construct(
            Version::NAME,
            Version::REVISION
        );
    }
}

Create the default application layer

Create the default application layer


<?php

class SqlQuerySelectDataConstraintGroupTest extends MidgardTest
{
    protected $select = null;
    protected $mgd = null;

    public function setUp()
    {
        $this->mgd = midgard_connection::get_instance();

        if ($this->select === null) {
            $this->select = new MidgardSqlQuerySelectData(midgard_connection::get_instance());
        }
    }

    public function tearDown()
    {
        unset($this->select);
    }

    public function testInheritance()
    {
        $cg = new MidgardQueryConstraintGroup("AND");
        $this->assertInstanceOf("MidgardQueryConstraintSimple", $cg);
    }

    public function testQueryConstraintGroup()
    {
        $storage = new MidgardQueryStorage("midgard_snippet");
        $columnA = new MidgardSqlQueryColumn(
            new MidgardQueryProperty("name", $storage),
            "tbl1",
            "a"
        );

        $columnB = new MidgardSqlQueryColumn(
            new MidgardQueryProperty("code", $storage),
            "tbl1",
            "b"
        );

        $this->select->add_column($columnA);
        $this->select->add_column($columnB);

        $cg = new MidgardQueryConstraintGroup("AND");

        $cg->add_constraint(
            new MidgardSqlQueryConstraint(
                $columnA,
                "<>",
                new MidgardQueryValue("")
            )
        );

        $cg->add_constraint(
            new MidgardSqlQueryConstraint(
                $columnB,
                "<>",
                new MidgardQueryValue("")
            )
        );

        $this->select->set_constraint($cg);
        $this->select->execute();
    }
}

?>

Test if QueryConstraintGroup is valid

Test if QueryConstraintGroup is valid


<?php
use yii\db\Migration;
use nterms\mailqueue\MailQueue;
class m170221_090302_add_sent_time_index extends Migration
{
    public function up()
    {
        $this->createIndex('IX_sent_time', Yii::$app->get(MailQueue::NAME)->table, 'sent_time');
    }
    public function down()
    {
        $this->dropIndex('IX_sent_time', Yii::$app->get(MailQueue::NAME)->table);
    }
}

Add index on column sent_time

Add index on column sent_time

Adding an index on columns sent_time speeds up the deletion of sent rows


<?php

namespace SendGrid;

class FilesExistTest extends \PHPUnit_Framework_TestCase
{
    private $requiredFiles;

    protected function setUp()
    {
        $this->requiredFiles = [
            ['./Docker', './docker/Docker'],
            ['./docker-compose.yml', './docker/docker-compose.yml'],
            './.codeclimate.yml',
            './.env_sample',
            './.github/ISSUE_TEMPLATE',
            './.github/PULL_REQUEST_TEMPLATE',
            './.gitignore',
            './.travis.yml',
            './CHANGELOG.md',
            './CODE_OF_CONDUCT.md',
            './CONTRIBUTING.md',
            './LICENSE.md',
            './README.md',
            './TROUBLESHOOTING.md',
            './USAGE.md',
            './USE_CASES.md',
        ];
    }

    public function testFilesArePresentInRepo()
    {
        foreach ($this->requiredFiles as $filePath) {
            if (is_array($filePath)) {
                $exists = array_filter(
                    $filePath,
                    function ($file) {
                        return file_exists($file);
                    }
                );
                $files = join('" and "', $filePath);
                $this->assertNotEmpty($exists, "File \"{$files}\" does not exist in repo!");
            } else {
                $this->assertFileExists($filePath, "File \"{$filePath}\" does not exist in repo!");
            }
        }
    }
}

Add unittest to check that specific files exist in repo


#!/usr/local/bin/php -f

<?php

echo "Starting the pfSense shell system";

echo ".";
require("globals.inc");
$g['booting'] = true;
require("functions.inc");
echo ".";
require("config.inc");
echo ".";
$g['booting'] = false;

$fp = fopen('php://stdin', 'r');

echo ".\n\n";

$shell_active = true;

echo "Example commands:\n\n";
echo "    print_r($config);\n";
echo "    \$config['interfaces']['lan']['ipaddr'] = \"192.168.1.1\";\n";
echo "    write_config();\n";

while($shell_active == true) {
        echo "\n\npfSense shell> ";
        $command = chop(fgets($fp));
        if($command == "exit") {
                $shell_active = false;
                echo "\n";
                break;
		}
        eval($command);
}

Add a pfSense interactive php shell for developers.


<?php
declare(strict_types=1);

namespace Fc2blog\Tests\App\Controller\Admin\Entries;

use Fc2blog\Model\EntriesModel;
use Fc2blog\Tests\Helper\ClientTrait;
use Fc2blog\Web\Controller\Admin\EntriesController;
use PHPUnit\Framework\TestCase;

class CreateTest extends TestCase
{
  use ClientTrait;

  public function testForm(): void
  {
    $this->mergeAdminSession();

    // Ja表記を確認
    $c = $this->reqGet("/admin/entries/create");
    $this->assertInstanceOf(EntriesController::class, $c);
    $this->assertEquals("create", $c->getResolvedMethod());
    $this->assertStringContainsString("新しく記事を書く", $c->getOutput());
//    var_dump($this->clientTraitSession);
//    var_dump($this->clientTraitCookie);
  }

  public function testPost(): void
  {
    $this->mergeAdminSession();

    $em = new EntriesModel();
    $entries = $em->forTestGetAll('testblog2');
    $entries_count = count($entries);

    $this->reqGet("/admin/entries/create");
    $sig = $this->clientTraitSession['sig'];

    // Ja表記を確認
    $r = $this->reqPostWithExit("/admin/entries/create", [
      "sig" => $sig,
      "entry" => [ // 最低限の投稿
        "title" => "test",
        "body" => "body",
        "extend" => "",
        "posted_at" => "",
        "open_status" => "1",
        "password" => "",
        "auto_linefeed" => "1",
        "comment_accepted" => "1",
      ]
    ]);

    $this->assertEquals("/admin/entries/index", $r->redirectUrl);

    $entries = $em->forTestGetAll('testblog2');
    $this->assertCount($entries_count + 1, $entries);
//    var_dump($entries[count($entries)-1]);
    $latest_entry = $entries[count($entries) - 1];
    $this->assertEquals('test', $latest_entry['title']);
    $this->assertEquals('body', $latest_entry['body']);
  }

  // TODO 様々なパラメタをつかったテストの追加
}

Add test: /admin/entries/create, Post new entry.