<?php

class FilesParseTest extends \PHPUnit_Framework_TestCase
{

    public function testFilesParse()
    {
        foreach ($this->getPhpFiles(DIR_BASE_CORE . "/src") as $file) {
            $this->loadFile(array_shift($file));
        }
    }

    private function getPhpFiles($path)
    {
        $directory = new RecursiveDirectoryIterator($path);
        $iterator = new RecursiveIteratorIterator($directory);
        return new RegexIterator($iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);
    }

    private function loadFile($path)
    {
        ob_start();
        require_once $path;
        ob_end_clean();
    }

}

Add a test that ensures all /src files parse

Former-commit-id: 0792beb820dd9e464b153963d8ac5040a3fa7ccd
Former-commit-id: 0df92273484d72c9fd5c379e3a2bb4cc9a193bcf


<?php
/*------------------------------------------------------------------------------

   Project  : CachingProxy
   Filename : tests/overrideRealpathFunction.php
   Autor    : (c) Sebastian Krüger <krueger@secra.de>
   Date     : 19.03.2014

   For the full copyright and license information, please view the LICENSE
   file that was distributed with this source code.

   Description: overrride the realpath() function in namespace to do some tests

  ----------------------------------------------------------------------------*/

namespace secra\CachingProxy;

/**
 * Override realpath() in current namespace for testing
 *
 * @param string $path     the file path
 *
 * @return string
 */
function realpath($path)
{
    return $path;
}

Add test function with correct name

Add test function with correct name


<?php

/**
 *  Drupal 7 snippet :
 *  Form API - Hide a label
 */

/**
 *  Implement hook_form_FORM_ID_alter()
 *  → ex: 'comment_form'
 */
function MODULE_OR_THEME_form_comment_form_alter(&$form, &$form_state)
{
    $lang = $form['comment_body']['#language'];
    $form['comment_body'][$lang][0]['#title_display'] = 'invisible';
}

Add Drupal 7 FormAPI snippet : hiding a label


<?php

namespace Doctrine\Tests\OXM\Util;

use Doctrine\OXM\Util\Inflector;

class InflectorTest extends \PHPUnit_Framework_TestCase
{
    public function testXmlize()
    {
        $this->assertEquals('xxx-yyy', Inflector::xmlize('XxxYYY'));
        $this->assertEquals('with-many-many-words', Inflector::xmlize('withManyManyWords'));
    }
}

Add test case on xmlinflector

[Tests] Add test case on xmlinflector


<?php

use Fhaculty\Graph\Algorithm\Eulerian as AlgorithmEulerian;
use Fhaculty\Graph\Graph;

class EulerianTest extends TestCase
{
    public function testGraphEmpty()
    {
        $graph = new Graph();

        $alg = new AlgorithmEulerian($graph);

        $this->assertFalse($alg->hasCycle());
    }

    public function testGraphPairHasNoCycle()
    {
        // 1 -- 2
        $graph = new Graph();
        $v1 = $graph->createVertex(1);
        $v2 = $graph->createVertex(2);
        $v1->createEdge($v2);

        $alg = new AlgorithmEulerian($graph);

        $this->assertFalse($alg->hasCycle());
    }

    public function testGraphTriangleCycleIsNotBipartit()
    {
        // 1 -- 2 -- 3 -- 1
        $graph = new Graph();
        $v1 = $graph->createVertex(1);
        $v2 = $graph->createVertex(2);
        $v3 = $graph->createVertex(3);
        $v1->createEdge($v2);
        $v2->createEdge($v3);
        $v3->createEdge($v1);

        $alg = new AlgorithmEulerian($graph);

        $this->assertTrue($alg->hasCycle());
    }
}

Add tests with 100% coverage for Algorithm\Eulerian


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ContentBundle\Meta\Tag\Provider;

/**
 * Meta tag provider
 */
interface MetaTagProviderInterface
{
    /**
     * @return string
     */
    public function getHeading(): string;

    /**
     * @return string
     */
    public function getMetaTitle(): string;

    /**
     * @return string
     */
    public function getMetaDescription(): string;
}

Add meta tag provider interface.

Add meta tag provider interface.


<?php namespace Aedart\Scaffold\Tasks;

use Aedart\Scaffold\Contracts\Tasks\ConsoleTask;
use Illuminate\Contracts\Config\Repository;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Base Task
 *
 * Abstraction for all console tasks
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Tasks
 */
abstract class BaseTask implements ConsoleTask
{
    /**
     * The input
     *
     * @var InputInterface
     */
    protected $input;

    /**
     * The output
     *
     * @var OutputInterface|\Symfony\Component\Console\Style\SymfonyStyle
     */
    protected $output;

    /**
     * The configuration
     *
     * @var Repository
     */
    protected $config;

    /**
     * Execute this given task
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param Repository $config
     *
     * @return void
     */
    public function execute(InputInterface $input, OutputInterface $output, Repository $config)
    {
        $this->input = $input;
        $this->output = $output;
        $this->config = $config;

        $this->performTask();
    }

    /**
     * Performs the actual task execution
     *
     * @return void
     */
    abstract public function performTask();
}

Add Base abstraction for console tasks

Add Base abstraction for console tasks

Ensures that input, output and configuration is set, before actually
performing the given task execution


<?php

use yii\db\Migration;

class m160528_135628_ceate_user_table extends Migration
{
    public function up()
    {
        $this->createTable('users', [
            'id' => $this->primaryKey(),
            'name' => $this->string(255)->unique(),
            'email' => $this->string(255),
            'password' => $this->string(255)
        ]);

        $this->insert('users', [
            'name' => 'admin',
            'email' => 'admin@mail.org',
            'password' => password_hash('admin', PASSWORD_DEFAULT)
        ]);
    }

    public function down()
    {
        $this->delete('users', ['id' => 1]);
        $this->dropTable('users');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

Add migration: create users table.

Add migration: create users table.


<?php

namespace ZendTest\Module;

use PHPUnit_Framework_TestCase as TestCase,
    Zend\Module\ManagerOptions,
    InvalidArgumentException,
    BadMethodCallException;

class ManagerOptionsTest extends TestCase
{
    public function testCanConfigureWithArrayInConstructor()
    {
        $options = new ManagerOptions(array(
            'cache_dir' => __DIR__,
            'cache_config' => true,
        ));
        $this->assertSame($options->getCacheDir(), __DIR__);
        $this->assertTrue($options->getCacheConfig(), true);
        $this->assertNotNull(strstr($options->getCacheFilePath(), __DIR__));
        $this->assertNotNull(strstr($options->getCacheFilePath(), '.php'));
    }

    public function testCanAccessKeysAsProperties()
    {
        $options = new ManagerOptions(array(
            'cache_dir' => __DIR__,
            'cache_config' => true,
        ));
        $this->assertSame($options->cache_dir, __DIR__);
        $this->assertTrue($options->cache_config, true);
        $options->cache_dir = 'foo';
        $options->cache_config = false;
        $this->assertSame($options->cache_dir, 'foo');
        $this->assertFalse($options->cache_config, false);
        $this->assertTrue(isset($options->cache_config));
        unset($options->cache_config);
        $this->assertFalse(isset($options->cache_config));
    }

    public function testContructorThrowsInvalidArgumentException()
    {
        $this->setExpectedException('InvalidArgumentException');
        $options = new ManagerOptions('foo');
    }

    public function testThrowsBadMethodCallExceptionForBadSetterKey()
    {
        $this->setExpectedException('BadMethodCallException');
        $options = new ManagerOptions;
        $options->bad = true;
    }

    public function testThrowsBadMethodCallExceptionForBadGetterKey()
    {
        $this->setExpectedException('BadMethodCallException');
        $options = new ManagerOptions;
        $bad = $options->bad;
    }
}

Add module manager options test file

Add module manager options test file


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

namespace PH7\Test\Unit\Framework\Ip;

use PH7\Framework\Ip\Ip;

class IpTest extends \PHPUnit_Framework_TestCase
{
    public function testInvalidIpAddress()
    {
        $_SERVER['REMOTE_ADDR'] = '1222222222233';

        // When it's an invald IP, it musts return "127.0.0.1" instead
        $this->assertEquals('127.0.0.1', Ip::get());
    }

    public function testPrivateIpAddress()
    {
        $_SERVER['REMOTE_ADDR'] = '172.16.0.0';

        // When it's private IP, it musts return "127.0.0.1" instead
        $this->assertEquals('127.0.0.1', Ip::get());
    }

    public function testValidIpAddress()
    {
        $_SERVER['REMOTE_ADDR'] = '108.170.3.142';
        $this->assertEquals('108.170.3.142', Ip::get());
    }

    public function testIsPrivate()
    {
        $this->assertTrue(Ip::isPrivate('192.168.0.0'));
    }

    public function testIsNotPrivate()
    {
        $this->assertFalse(Ip::isPrivate('52.53.189.95'));
    }
 }

Add IP class Unit Tests

Add IP class Unit Tests


<?php

namespace Milkmeowo\Framework\Repository\Foundations\Validators;

use Prettus\Validator\LaravelValidator;

class Validator extends LaravelValidator
{

    /**
     * Validation Custom Messages
     *
     * @var array
     */
    protected $messages = [];

    /**
     * Validation Custom Attributes
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * Get Custom error messages for validation
     *
     * @return array
     */
    public function getMessages()
    {
        return $this->messages;
    }

    /**
     * Set Custom error messages for Validation
     * @param array $messages
     *
     * @return $this
     */
    public function setMessages(array $messages)
    {
        $this->messages = $messages;
        return $this;
    }

    /**
     * Get Custom error attributes for validation
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Set Custom error attributes for Validation
     *
     * @param array $attributes
     *
     * @return $this
     */
    public function setAttributes(array $attributes)
    {
        $this->attributes = $attributes;
        return $this;
    }

    /**
     * Pass the data and the rules to the validator
     *
     * @param string $action
     * @return bool
     */
    public function passes($action = null)
    {
        $rules      = $this->getRules($action);
        $messages   = $this->getMessages();
        $attributes = $this->getAttributes();
        $validator  = $this->validator->make($this->data, $rules, $messages, $attributes);
        if( $validator->fails() )
        {
            $this->errors = $validator->messages();
            return false;
        }
        return true;
    }

}

Implement Custom Messages & Attributes

Implement Custom Messages & Attributes


<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * Class with methods to do safe math operations.
 */

abstract class SafeMath {

    /**
     * Returns 100 times the input as int, false on error.
     * Only input's with precision of 2 decimals or less are accepted.
     *
     * @return int cents
     */
    public static function getCentsFromString($value) {
        //Cuts string on points and count parts
        $parts = explode('.', $value);
        $nParts = count($parts);

        //We can't have more than 1 comma
        if ($nParts > 2)
            return false;

        //Check if the precision isn't to high
        if (strlen(end($parts)) > 2)
            return false;

        //Check if each individual part is numeric
        foreach ($parts as $part)
            if (!is_numeric($part))
                return false;

        //Return given value times 100
        if ($nParts == 1)
            return $parts[0] * 100;
        else
            return $parts[0] * 100 + $parts[1];
    }
}

Create class to do safe math operations.


<?php

/*
 * This file is part of the Stash package.
 *
 * (c) Robert Hafner <tedivm@tedivm.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Stash\Test\Driver;

use Stash\Test\Stubs\DriverUnavailableStub;

/**
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 */
class UnavailableDriverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException Stash\Exception\RuntimeException
     */
    public function testUnavailableDriver()
    {
        new DriverUnavailableStub();
    }

}

Test UnavailableDriver exception in AbstractDriver


<?php

require_once '../Mustache.php';

class MustacheCallTest extends PHPUnit_Framework_TestCase {

	public function testCallEatsContext() {
		$foo = new Foo();
		$foo->name = 'Bob';

		$template = '{{# foo }}{{ label }}: {{ name }}{{/ foo }}';
		$data = array('label' => 'name', 'foo' => $foo);
		$m = new Mustache($template, $data);

		$this->assertEquals('name: Bob', $m->render());
	}
}

class Foo {
	public $name;
	public function __call($method, $args) {
		return 'unknown value';
	}
}

Add a test to discourage people from implementing support for __call.

Pull in the test from https://gist.github.com/655784

This should discourage reports like #16, #19 and #55, and #76.


<?php

/**
 * @group conduit
 */
final class ConduitAPI_differential_querydiffs_Method
  extends ConduitAPIMethod {

  public function getMethodDescription() {
    return pht('Query differential diffs which match certain criteria.');
  }

  public function defineParamTypes() {
    return array(
      'ids' => 'optional list<uint>',
      'revisonIDs' => 'optional list<uint>',
    );
  }

  public function defineErrorTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'list<dict>';
  }

  protected function execute(ConduitAPIRequest $request) {
    $ids = $request->getValue('ids', array());
    $revision_ids = $request->getValue('revisionIDs', array());
    $diffs = array();
    $diff_dicts = array();
    if ($ids || $revision_ids) {
      $diffs = id(new DifferentialDiffQuery())
        ->setViewer($request->getUser())
        ->withIDs($ids)
        ->withRevisionIDs($revision_ids)
        ->needChangesets(true)
        ->needArcanistProjects(true)
        ->execute();
    }

    return mpull($diffs, 'getDiffDict', 'getID');
  }
}

<?php

/**
 * @group conduit
 */
final class ConduitAPI_differential_querydiffs_Method
  extends ConduitAPIMethod {

  public function getMethodDescription() {
    return pht('Query differential diffs which match certain criteria.');
  }

  public function defineParamTypes() {
    return array(
      'ids' => 'optional list<uint>',
      'revisionIDs' => 'optional list<uint>',
    );
  }

  public function defineErrorTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'list<dict>';
  }

  protected function execute(ConduitAPIRequest $request) {
    $ids = $request->getValue('ids', array());
    $revision_ids = $request->getValue('revisionIDs', array());

    $diffs = array();
    if ($ids || $revision_ids) {
      $diffs = id(new DifferentialDiffQuery())
        ->setViewer($request->getUser())
        ->withIDs($ids)
        ->withRevisionIDs($revision_ids)
        ->needChangesets(true)
        ->needArcanistProjects(true)
        ->execute();
    }

    return mpull($diffs, 'getDiffDict', 'getID');
  }
}

Fix a typo in `differential.querydiffs`

Fix a typo in `differential.querydiffs`

Summary:
  - "revision" is misspelled.
  - Remove an unused variable.

Test Plan: Used API console to call method.

Reviewers: btrahan, chad

Reviewed By: chad

CC: aran

Differential Revision: https://secure.phabricator.com/D7184


<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace App\Form\User;

use Mandragora\FormFactory;
use PHPUnit_Framework_TestCase as TestCase;

class LoginTest extends TestCase
{
    /** @test */
    function it_can_be_created()
    {
        $this->assertInstanceOf(Login::class, $this->loginForm);
        $this->assertCount(3, $this->loginForm->getElements());
    }

    /** @test */
    function it_sets_the_authentication_error_messages()
    {
        $message = 'this value is required';
        $errorMessages = ['username' => $message, 'password' => $message];

        $this->loginForm->setAuthenticationErrors($errorMessages);

        $username = $this->loginForm->getElement('username');
        $password = $this->loginForm->getElement('password');

        $this->assertEquals([$message], $username->getErrorMessages());
        $this->assertEquals([$message], $password->getErrorMessages());
    }

    /** @before */
    function createForm()
    {
        $this->loginForm = (new FormFactory(true))->create('Login', 'User');
    }

    /** @var Login */
    private $loginForm;
}

Add tests for the login form.

Add tests for the login form.


<?php

namespace Rogue\Console\Commands;

use Illuminate\Console\Command;
use Rogue\Models\Post;

class DeletePosts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rogue:deleteposts
                            {ids* : A space-separated list of post ids to delete}
                            {--force : Whether or not to force delete these posts instead of soft delete (default)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete posts in Rogue by post id with an option to force delete';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ids = $this->argument('ids');

        $posts = Post::whereIn('id', $ids);

        if ($this->option('force')) {
            $posts->forceDelete();
        } else {
            $posts->delete();
        }

        $this->info('Posts Deleted!');
    }
}

Add command to delete posts by id

Add command to delete posts by id


<?php
namespace Intercom\Util;

use Guzzle\Tests\GuzzleTestCase;

class FlatStoreTest extends GuzzleTestCase
{
    /** @var array  */
    private $unkeyed_data = ['Help', 1234];
    /** @var array */
    private $valid_data = ['key1' => 'value1', 'key2' => false, 'key3' => 0.85353];
    /** @var array */
    private $invalid_data = ['key1' => 'Arg1', 'key2' => ['Arg2']];

    public function testConstructFlatStoreNoArgs() {
        $fs = new FlatStore();
        $this->assertInstanceOf('Intercom\Util\Flatstore', $fs);
    }

    public function testEmptyFlatStore() {
        $fs = new FlatStore();
        $this->assertEmpty($fs->getStore());
    }

    public function testConstructFlatStoreWithData() {
        $fs = new FlatStore($this->valid_data);
        $this->assertEquals($this->valid_data, $fs->getStore());
    }

    public function testGetStore() {
        $fs = new FlatStore($this->valid_data);
        $this->assertTrue(is_array($fs->getStore()));
        $this->assertEquals($this->valid_data, $fs->getStore());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructFlatStoreWithInvalidData() {
        $fs = new FlatStore($this->invalid_data);
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructFlatStoreWithUnkeyedData() {
        $fs = new FlatStore($this->unkeyed_data);
    }
}

Add unit tests for FlatStore

Add unit tests for FlatStore


<?php

namespace Room11\Jeeves\Tests\Chat\Plugin;

use Amp\Artax\HttpClient;
use Amp\Artax\Response;
use Amp\Success;
use function Amp\wait;
use PHPUnit\Framework\TestCase;
use Room11\Jeeves\Chat\Client\ChatClient;
use Room11\Jeeves\Plugins\PHPBugs;
use Room11\Jeeves\Storage\KeyValue;

class PHPBugsTest extends TestCase {
    public function testRecentBugsReturnsFalseOnRequestFailure()
    {
        $chatClient = $this->getMockBuilder(ChatClient::class)->getMock();
        $httpClient = $this->getMockBuilder(HttpClient::class)->getMock();
        $pluginData = $this->getMockBuilder(KeyValue::class)->getMock();
        $response = $this->getMockBuilder(Response::class)->getMock();

        $response->method("getStatus")->willReturn(500);
        $httpClient->method("request")->willReturn(new Success($response));

        $plugin = new PHPBugs($chatClient, $httpClient, $pluginData);

        $reflectionMethod = new \ReflectionMethod($plugin, "getRecentBugs");
        $reflectionMethod->setAccessible(true);

        $this->assertFalse(wait($reflectionMethod->invoke($plugin)));
    }
}

Add unit test for PHPBugs

Add unit test for PHPBugs


<?php

namespace Tomahawk\Test;

class MockPdo extends \PDO
{
    public function __construct ()
    {

    }

    public function quote($string, $parameter_type = \PDO::PARAM_STR) {
        return sprintf("%s", $string);
    }

}

Add mock pdo classes to test with testing


<?php

/**
 * This file contains the FluidInterfaceMock.
 *
 * PHP Version 5.4
 *
 * @category   Tests
 * @package    Halo
 * @subpackage Libraries
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 * @copyright  2014, M2Mobi BV, Amsterdam, The Netherlands
 * @license    http://lunr.nl/LICENSE MIT License
 */

namespace Lunr\Halo;

/**
 * This mock class can be used to more efficiently mock fluid interface calls.
 *
 * @category   Tests
 * @package    Halo
 * @subpackage Libraries
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
class FluidInterfaceMock
{

    /**
     * Array of mocked return values
     * @var array
     */
    protected $return;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->return = [];
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        unset($this->return);
    }

    /**
     * Handle fluid interface calls.
     *
     * @param String $name      Method name
     * @param Array  $arguments Method arguments
     *
     * @return mixed $return Stored return value or a self reference
     */
    public function __call($name, $arguments)
    {
        if (array_key_exists($name, $this->return))
        {
            return array_pop($this->return[$name]);
        }
        else
        {
            return $this;
        }
    }

    /**
     * Specifically mock a certain method call.
     *
     * @param String $name  Method name
     * @param Mixed  $value Mocked return value
     *
     * @return void
     */
    public function mock($name, $value)
    {
        if (!array_key_exists($name, $this->return))
        {
            $this->return[$name] = [];
        }

        array_push($this->return[$name], $value);
    }

}

?>

Halo: Add a mock class for classes that use fluid interfaces.

This should make unit tests for methods that use fluid interface methods
but don't care about their functionality more compact.


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Mail\Struct\ByHourRule;

/**
 * Testcase class for ByHourRule.
 */
class ByHourRuleTest extends ZimbraMailTestCase
{
    public function testByHourRule()
    {
        $quantity = mt_rand(5, 10);
        $numbers = $this->faker->randomElements(range(0, 23), $quantity);
        $list = implode(',', $numbers);

        $byhour = new ByHourRule($list);
        $this->assertSame($list, $byhour->getList());
        $byhour->setList($list);
        $this->assertSame($list, $byhour->getList());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<byhour hrlist="' . $list . '" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $byhour);

        $array = array(
            'byhour' => array(
                'hrlist' => $list,
            ),
        );
        $this->assertEquals($array, $byhour->toArray());
    }
}

Add test case for ByHourRule.

Add test case for ByHourRule.


<?php
/**
 *  Tatoeba Project, free collaborative creation of languages corpuses project
 *  Copyright (C) 2015  Gilles Bedel
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

App::import('Model', 'Sentence');
App::import('Model', 'User');

class EditSentencesShell extends Shell {

    public $uses = array('Sentence', 'User');

    private $stderr = null;

    private function be($username) {
        putenv('HTTP_CLIENT_IP=127.0.0.1');
        $editor = $this->User->findByUsername($username);
        if ($editor === false) {
            die("'$username' is not a valid username.\n");
        }
        CurrentUser::store($editor);
    }

    public function main() {
        $nb_sentences = $nb_ignored = 0;
        $stdin = fopen('php://stdin', 'r');

        if (count($this->args) != 1) {
            $myself = basename(__FILE__, '.php');
            die("Usage: $myself <editor> < sentences.csv\n\nMakes <editor> mass-edit sentences from CSV.\nCSV must be tab-separated, first column is\nthe sentence id, second column is the sentence text.\n");
        }

        $this->be($this->args[0]);
        while (($data = fgetcsv($stdin, 0, "\t")) !== FALSE) {
            if (count($data) != 2) {
                echo "Invalid line skipped.\n";
                continue;
            }

            list($id, $text) = $data;
            if (!$this->Sentence->findById($id)) {
                echo "Sentence $id does not exists, skipping!\n";
                $nb_ignored++;
                continue;
            }

            $this->Sentence->save(array(
                'id' => $id,
                'text' => $text,
            ));
            echo ".";
            $nb_sentences++;
        }
        fclose($stdin);

        echo "\n$nb_sentences sentences edited, $nb_ignored ignored because they don't exist.\n";
    }
}

Add shell to mass-edit sentences

Add shell to mass-edit sentences


<?php

namespace mageekguy\atoum\tests\units\report\fields\runner;

use
	\mageekguy\atoum,
	\mageekguy\atoum\report\fields\runner
;

require_once(__DIR__ . '/../runner.php');
require_once(__DIR__ . '/../../../../runner.php');

abstract class result extends \mageekguy\atoum\tests\units\report\fields\runner {}

?>

<?php

namespace mageekguy\atoum\tests\units\report\fields\runner;

use
	\mageekguy\atoum,
	\mageekguy\atoum\report\fields\runner
;

require_once(__DIR__ . '/../../../../runner.php');

abstract class result extends \mageekguy\atoum\tests\units\report\fields\runner {}

?>

Improve unit test about report's field.

Improve unit test about report's field.

git-svn-id: 6e9066ea2b7311f0dbdfae11f91a207e5fe444e0@355 fe8bb9cb-3c6a-df11-91c9-004063e5cbdf


<?php

/**
 * @name Zataz
 * @homepage http://www.zataz.com/
 * @description ZATAZ Magazine - S'informer, c'est déjà se sécuriser
 * @maintainer aledeg
 * @update 07/02/2015
 */
class ZatazBridge extends BridgeAbstract {

	public function collectData(array $param) {
		$html = file_get_html($this->getURI()) or $this->returnError('Could not request ' . $this->getURI(), 404);

		$recent_posts = $html->find('#recent-posts-3', 0)->find('ul', 0)->find('li');
		foreach ($recent_posts as $article) {
			if (count($this->items) < 5) {
				$uri = $article->find('a', 0)->href;
				$this->items[] = $this->getDetails($uri);
			}
		}
	}

	private function getDetails($uri) {
		$html = file_get_html($uri) or exit;

		$item = new \Item();

		$article = $html->find('.gdl-blog-full', 0);
		$item->uri = $uri;
		$item->title = $article->find('.blog-title', 0)->find('a', 0)->innertext;
		$item->content = $article->find('.blog-content', 0)->innertext;
		$item->timestamp = $this->getTimestampFromDate($article->find('.blog-date', 0)->find('a', 0)->href);
		return $item;
	}

	private function getTimestampFromDate($uri) {
		preg_match('/\d{4}\/\d{2}\/\d{2}/', $uri, $matches);
		$date = new \DateTime($matches[0]);
		return $date->format('U');
	}

	public function getName() {
		return 'Zataz Magazine';
	}

	public function getCacheDuration() {
		return 7200; // 2h
	}

	public function getURI() {
		return 'http://www.zataz.com';
	}

}

Add support for Zataz website.

Add support for Zataz website.

It gets the last 5 articles available. The feed is missing images since hot-linking is impossible from host.
We might need a way to grab and store that content as well.


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

use Jivoo\Core\Parse\ParseInput;

/**
 * A parser for expressions.
 */
class ExpressionParser {

  /**
   * @param ParseInput $input
   * @return ast
   */
  public static function parseExpression(ParseInput $input) {
  }
}

Add empty expresion parser class.

Add empty expresion parser class.


<?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\Core\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Anna Walasek <anna.walasek@lakion.com>
 */
interface ShippingCategoryRepositoryInterface extends RepositoryInterface
{
    /**
     * @return QueryBuilder
     */
    public function createListQueryBuilder();
}

[AdminBundle] Create crud for ShippingCategory
[CoreBundle][Core] Add ShippingCategoryRepository
[UiBundle] Add translations


<?php

namespace Sitemap\Writers;

use Sitemap\Sitemap;
use Sitemap\Index;

class IndexTest extends \PHPUnit_Framework_TestCase
{
    public function testIndexXMLWriter()
    {
        $sitemap1 = new Sitemap;
        $sitemap1->setLocation('http://www.example.com/sitemap1.xml.gz');
        $sitemap1->setLastMod('2004-10-01T18:23:17+00:0');

        $sitemap2 = new Sitemap;
        $sitemap2->setLocation('http://www.example.com/sitemap2.xml.gz');
        $sitemap2->setLastMod('2005-01-01');

        $index = new Index;
        $index->addSitemap($sitemap1);
        $index->addSitemap($sitemap2);

        $writer = new \Sitemap\Writers\XML\Index($index);

        $this->assertXmlStringEqualsXmlFile(__DIR__.'/../../controls/index.xml', (string) $writer->output());
    }
}

Write a test to confirm out index output.


<?php

namespace Symm\BitpayClient\Tests;

use Symm\BitpayClient\Model\Currency;

/**
 * CurrencyTest
 */
class CurrencyTest extends \PHPUnit_Framework_TestCase
{

    protected $currency = array(
        'code' => 'SEK',
        'name' => 'Swedish Krona',
        'rate' => 4169.1658
    );

    public function getCurrencyObject()
    {
        return new Currency(
            $this->currency['code'],
            $this->currency['name'],
            $this->currency['rate']
        );
    }

    public function testItCanBeInstantiated()
    {
        $currency = $this->getCurrencyObject();
        $this->assertInstanceOf('Symm\BitpayClient\Model\Currency', $currency);
    }

    public function testItReturnsACurrencyCode()
    {
        $currency = $this->getCurrencyObject();
        $this->assertEquals($this->currency['code'], $currency->getCode());
    }

    public function testItReturnsAItsName()
    {
        $currency = $this->getCurrencyObject();
        $this->assertEquals($this->currency['name'], $currency->getName());
    }

    public function testItReturnsTheRate()
    {
        $currency = $this->getCurrencyObject();
        $this->assertEquals($this->currency['rate'], $currency->getRate());
    }
}

Add tests for the currency model

Add tests for the currency model


<?php
namespace Bolt\tests\Content;

use Bolt\Tests\BoltUnitTest;
use Bolt\Content;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class to test src/Storage.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class ContentTest extends BoltUnitTest
{

    public function testgetValues()
    {
        $app = $this->getApp();
    }

    public function testsetValues()
    {
    }

    public function testsetValue()
    {
    }

    public function testsetFromPost()
    {
    }

    public function testsetContenttype()
    {
    }

    public function testsetTaxonomy()
    {
    }

    public function testsortTaxonomy()
    {
    }

    public function testsetRelation()
    {
    }

    public function testgetTaxonomyType()
    {
    }

    public function testsetGroup()
    {
    }

    public function testgetDecodedValue()
    {
    }

    public function testpreParse()
    {
    }

    public function testgetTemplateContext()
    {
    }

    public function testget()
    {
    }

    public function testgetTitle()
    {
    }

    public function testgetTitleColumnName()
    {
    }

    public function testgetImage()
    {
    }

    public function testgetReference()
    {
    }

    public function testeditlink()
    {
    }

    public function testlink()
    {
    }

    public function testprevious()
    {
    }

    public function testnext()
    {
    }

    public function testrelated()
    {
    }

    public function testfieldinfo()
    {
    }

    public function testfieldtype()
    {
    }

    public function testexcerpt()
    {
    }

    public function testrss_safe()
    {
    }

    public function testweighSearchResult()
    {
    }

    public function testgetSearchResultWeight()
    {
    }

    public function testoffsetExists()
    {
    }

    public function testoffsetGet()
    {
    }

    public function testoffsetSet()
    {
    }

    public function testoffsetUnset()
    {
    }
}

Add start of Bolt\Content tests

Add start of Bolt\Content tests


<?php

use yii\db\Schema;
use console\components\Migration;

class m150804_073905_create_nested_set_comment_table extends Migration
{
    public function up()
    {
        $this->createTable('{{%comment_ns}}', [
            'id' => Schema::TYPE_PK,

            'post_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'author_id' => Schema::TYPE_INTEGER . ' NOT NULL',

            'left' => Schema::TYPE_INTEGER . ' NOT NULL',
            'right' => Schema::TYPE_INTEGER . ' NOT NULL',
            'level' => Schema::TYPE_INTEGER . ' NOT NULL',

            'text' => Schema::TYPE_TEXT . ' NOT NULL',

            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
            'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ]);

        $this->createIndex('comment_ns__post_id', '{{%comment_ns}}', 'post_id');
        $this->addForeignKey('comment_ns__post_id', '{{%comment_ns}}', 'post_id', '{{%post}}', 'id', 'CASCADE', 'RESTRICT');

        $this->createIndex('comment_ns__author_id', '{{%comment_ns}}', 'author_id');
        $this->addForeignKey('comment_ns__author_id', '{{%comment_ns}}', 'author_id', '{{%user}}', 'id', 'CASCADE', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('comment_ns__post_id', '{{%comment_ns}}');
        $this->dropIndex('comment_ns__post_id', '{{%comment_ns}}');

        $this->dropForeignKey('comment_ns__author_id', '{{%comment_ns}}');
        $this->dropIndex('comment_ns__author_id', '{{%comment_ns}}');

        $this->dropTable('{{%comment_ns}}');
    }
}

Create nested set comments table.

Create nested set comments table.


<?php

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

class AddTournamentOwnerColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('tournaments', function (Blueprint $table) {

            /**
             * @var $firstMember \App\Models\Member
             */
            $firstMember = DB::table('members')->first();

            if ($firstMember) {
                $table->integer('owner')->unsigned()->default($firstMember->id);
            } else {
                $table->integer('owner')->unsigned();
            }

            $table->foreign('owner', 'tournamentOwner_foreign')->references('id')->on('members')
                ->onDelete('restrict')
                ->onUpdate('restrict');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('tournaments', function (Blueprint $table) {
            Schema::table('tournaments', function (Blueprint $table) {
                $table->dropForeign('tournamentOwner_foreign');
            });

            $table->dropColumn('owner');
        });
    }
}

Add migration with column for tournament owner


<?php

namespace Bolt\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;

/**
 * Token/cookie name service provider.
 *
 * NOTE: We use hostname as that will include the TCP/IP port used if
 * non-standard, and the root URL as multiple installations can exist on the
 * same host using subdirectories.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class TokenServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['token.session.name'] = $app->share(
            function ($app) {
                $name = 'bolt_session_' . md5($app['resources']->getRequest('hostname') . $app['resources']->getUrl('root'));

                return $name;
            }
        );

        $app['token.authentication.name'] = $app->share(
            function ($app) {
                $name = 'bolt_authtoken_' . md5($app['resources']->getRequest('hostname') . $app['resources']->getUrl('root'));

                return $name;
            }
        );
    }

    public function boot(Application $app)
    {
    }
}

Add a service provider for site specific token/cookie names


<?php
/**
 * Forces expiration dates to always be set to the end of the month.
 *
 * NOTE: Changing the calculated expiration date does not change the renewal date
 * with the gateway, so using this alongside automatic renewals is not recommended.
 *
 * @param string     $expiration Calculated expiration date in MySQL format or 'none'.
 * @param int        $user_id    ID of the user the expiration date is being calculated for.
 * @param RCP_Member $member     Member object.
 *
 * @return string Modified expiration date.
 */
function ag_rcp_end_of_month_expiration( $expiration, $user_id, $member ) {

	// Don't make any changes if the expiration date is 'none'.
	if ( 'none' == $expiration ) {
		return $expiration;
	}

	// NOTE: Only use one of the following two examples.

	/**
	 * Example #1: End of month based on already calculated expiration
	 *
	 * This example forces the expiration date to use the end of *calculated* month.
	 * So if a user signs up for a one-month subscription on July 15th 2017, the regular
	 * expiration date would be August 15th 2017, and this snippet would change that to
	 * August 31st 2017.
	 */
	return date( 'Y-m-t 23:59:59', strtotime( $expiration ) );

	/**
	 * Example #2: End of current month
	 *
	 * This example forces the expiration date to use the end of the *current* month.
	 * So if a user signs up for a one-month subscription on July 15th 2017, the regular
	 * expiration date would be August 15th 2017, and this snippet would change that to
	 * July 31st 2017.
	 */
	return date( 'Y-m-t 23:59:59', current_time( 'timestamp' ) );

}

add_filter( 'rcp_member_calculated_expiration', 'ag_rcp_end_of_month_expiration', 10, 3 );

Set calculated expiration dates to last day of the month.


<?php

return [
    'isin' => ':attribute tulee olla kelvollinen International Securities Identification Number (ISIN).',
    'iban' => ':attribute tulee olla kelvollinen International Bank Account Number (IBAN).',
    'bic' => ':attribute tulee olla kelvollinen Business Identifier Code (BIC).',
    'hexcolor' => ':attribute tulee olla kelvollinen heksadesimaali värikoodi.',
    'creditcard' => ':attribute tulee olla kelvollinen luottokortin numero.',
    'isbn' => ':attribute tulee olla kelvollinen International Standard Book Number (ISBN).',
    'username' => ':attribute tulee olla kelvollinen käyttäjänimi.',
    'htmlclean' => ':attribute sisältää kiellettyä HTML-koodia.',
    'domainname' => ':attribute tulee olla kelvollinen verkkoalueen nimi.',
    'jwt' => ':attribute ei vastaa JSON Web Token muotoa',
    'imei' => ':attribute tulee olla kelvollinen Mobile Equipment Identity (IMEI).',
    'macaddress' => ':attribute tulee olla kelvollinen MAC-osoite.',
    'slug' => ':attribute tulee olla kelvollinen polkutunnus',
    'semver' => ':attribute tulee olla kelvollinen semanttisen versionumeroinnin versionumero.',
    'luhn' => ':attribute tarkistussummaa ei voida vahvistaa Luhnin algoritmilla.',
    'base64' => ':attribute tulee olla kelvollinen base64-muotoinen arvo.',
    'issn' => ':attribute tulee olla kelvollinen International Standard Serial Number (ISSN).',
    'lowercase' => ':attribute voi sisältää vain pieniä kirjaimia.',
    'uppercase' => ':attribute voi sisältää vain isoja kirjaimia.',
    'titlecase' => ':attribute kaikkien sanojen tulee alkaa isolla alkukirjaimella.',
    'kebabcase' => ':attribute tulee olla käytetty kebab case kirjoitusasua.',
    'snakecase' => ':attribute tulee olla käytetty snake case kirjoitusasua.',
    'camelcase' => ':attribute tulee olla käytetty camel case kirjoitusasua.',
];

Add Finnish translations to error messages

Add Finnish translations to validation error messages.

Use localization specific terms where possible.

 - "slug" translates to "polkutunnus" as it used in Finnish WordPress
   localization


<?php

/**
 * Created by PhpStorm.
 * User: Godluck Akyoo
 * Date: 27-Jun-16
 * Time: 20:12
 */
class Migration_Update_xforms_table extends CI_Migration
{

	public function up()
	{
		$field = array(
			'jr_form_id' => array(
				'type'       => 'VARCHAR',
				'constraint' => 255,
			),
		);
		$this->dbforge->add_column("xforms", $field);
	}

	public function down()
	{
		$this->dbforge->drop_column('xforms', 'jr_form_id');
	}
}

Add migration for updating xform tables with jr_xform_id field


<?php

namespace Jivoo\Core;

class MapTest extends \Codeception\TestCase\Test {

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

  protected function _before() {}

  protected function _after() {}

  public function testGettersAndSetters() {
    $map = new Map(array('test' => 1));
    $this->assertEquals(1, $map->test);
    $map->test2 = 2;
    $this->assertEquals(2, $map->test2);
    $this->assertTrue(isset($map->test));
    unset($map->test);
    $this->assertFalse(isset($map->test));

    $this->assertEquals(2, $map['test2']);
    $map['test3'] = 3;
    $this->assertEquals(3, $map['test3']);
    $this->assertTrue(isset($map['test2']));
    unset($map['test2']);
    $this->assertFalse(isset($map['test2']));
    $map[] = 5;
    $this->assertEquals(1, count($map));

    try {
      $map->test;
      $this->fail('MapKeyInvalidException not thrown');
    }
    catch (MapKeyInvalidException $e) {}

    foreach ($map as $key => $value) {
      $this->assertEquals('test3', $key);
      $this->assertEquals(3, $value);
    }
  }

  public function testReadOnly() {
    $map = new Map(array('test' => 1), true);
    $this->assertTrue($map->isReadOnly());

    try {
      $map->test = 5;
      $this->fail('MapReadOnlyException not thrown');
    }
    catch (MapReadOnlyException $e) {}

    $this->assertEquals(1, $map->test);

    try {
      unset($map->test);
      $this->fail('MapReadOnlyException not thrown');
    }
    catch (MapReadOnlyException $e) {}

    $this->assertTrue(isset($map->test));
  }
}

Add unit test of Map

Add unit test of Map


<?php

namespace Nwidart\Modules\Tests\Commands;

use Illuminate\Support\Facades\Schema;
use Nwidart\Modules\Repository;
use Nwidart\Modules\Tests\BaseTestCase;

abstract class MigrateCommandTest extends BaseTestCase
{
    /**
     * @var Repository
     */
    private $repository;
    /**
     * @var \Illuminate\Filesystem\Filesystem
     */
    private $finder;

    public function setUp()
    {
        parent::setUp();
        $this->repository = new Repository($this->app);
        $this->finder = $this->app['files'];
    }

    /** @test */
    public function it_migrates_a_module()
    {
        $this->repository->addLocation(__DIR__ . '/../stubs/Recipe');

        $this->artisan('module:migrate', ['module' => 'Recipe']);

        dd(Schema::hasTable('recipe__recipes') , $this->app['db']->table('recipe__recipes')->get());
    }
}

Prepare a test for migration testing

Prepare a test for migration testing


<?php
function cdash_testsuite_unlink($filename)
{
  $try_count = 1;
  echo "unlink '".$filename."'\n";
  $success = unlink($filename);

  while(file_exists($filename) && $try_count < 300)
  {
    usleep(1000000); // == 1000 ms, == 1.0 seconds

    $try_count++;
    echo "attempt $try_count to unlink '".$filename."'\n";
    $success = unlink($filename);
  }

  if ($try_count > 3)
  {
    echo "excessive try_count=$try_count unlinking '".$filename."'\n";
  }

  if (file_exists($filename))
  {
    throw new Exception("file still exists after unlink: $filename");
  }

  return $success;
}
?>

ENH: Add cdash_unlink and cdash_testsuite_unlink: debug/fix unlink problems


<?php

namespace Backend\Modules\Settings\Ajax;

use Backend\Core\Engine\Base\AjaxAction;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;

class ClearCache extends AjaxAction
{
    public function execute()
    {
        parent::execute();

        $kernel = $this->getKernel();
        $application = new Application($kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput(
            [
                'command' => 'forkcms:cache:clear'
            ]
        );

        $exitCode = $application->run($input);

        $this->output(
            self::OK,
            [
                'exitCode' => $exitCode,
            ]
        );
    }
}

Create an Ajax action which will clear the cache using the built in command


<?php

namespace Sylius\Migrations;

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

class Version20151015181310 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $paymentMethods = $this->connection->fetchAll('SELECT * FROM sylius_payment_method WHERE fee_calculator_configuration=""');;
        foreach ($paymentMethods as $paymentMethod) {
            $this->connection->update(
                'sylius_payment_method',
                array('fee_calculator' => 'fixed','fee_calculator_configuration' => serialize(array('amount' => 0))),
                array('name' => $paymentMethod['name'])
            );
        }
    }

    public function down(Schema $schema)
    {

    }
}

Fix payment method error by generating migrations for Fee calculator


<?php

/*
 * This file is part of the Foxy package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Foxy\Tests\Solver;

use Composer\Composer;
use Composer\IO\IOInterface;
use Foxy\Config\Config;
use Foxy\Solver\ComposerFallback;
use Foxy\Solver\ComposerFallbackInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Tests for composer fallback.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class ComposerFallbackTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Config
     */
    protected $config;

    /**
     * @var Composer|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $composer;

    /**
     * @var IOInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $io;

    /**
     * @var Filesystem
     */
    protected $sfs;

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

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

    /**
     * @var ComposerFallbackInterface
     */
    protected $composerFallback;

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

        $this->oldCwd = getcwd();
        $this->cwd = sys_get_temp_dir().DIRECTORY_SEPARATOR.'foxy_composer_fallback_test_'.uniqid();
        $this->config = new Config(array(
            'fallback-composer' => true,
        ));
        $this->composer = $this->getMockBuilder('Composer\Composer')->disableOriginalConstructor()->getMock();
        $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
        $this->sfs = new Filesystem();
        $this->sfs->mkdir($this->cwd);
        chdir($this->cwd);

        $this->composerFallback = new ComposerFallback($this->config);
    }

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

        chdir($this->oldCwd);
        $this->sfs->remove($this->cwd);
        $this->config = null;
        $this->composer = null;
        $this->io = null;
        $this->sfs = null;
        $this->composerFallback = null;
        $this->oldCwd = null;
        $this->cwd = null;
    }

    public function testRunWithDisableOption()
    {
        $config = new Config(array(
            'fallback-composer' => false,
        ));
        $composerFallback = new ComposerFallback($config);

        $this->io->expects($this->never())
            ->method('write');

        $composerFallback->run($this->composer, $this->io);
    }

    /**
     * @expectedException \Foxy\Exception\RuntimeException
     * @expectedExceptionMessage The fallback for the Composer lock file and its dependencies is not implemented currently
     */
    public function testRun()
    {
        $this->composerFallback->run($this->composer, $this->io);
    }
}

Add tests for composer fallback

Add tests for composer fallback


<?php
require_once CM_Util::getModulePath('CM') . 'library/CM/SmartyPlugins/function.link.php';

function smarty_function_linkDomainShort(array $params, Smarty_Internal_Template $template) {
    /** @var CM_Frontend_Render $render */
    $render = $template->smarty->getTemplateVars('render');

    $page = $params['page'];
    unset($params['page']);

    $href = $render->getUrlPage($page, $params);
    $params['href'] = $href;
    $params['label'] = preg_replace('#^https?://(www\.)?#', '', $href);

    return smarty_function_link($params, $template);
}

Add smarty helper for short domain link

Add smarty helper for short domain link


<?php

/**
 * Migration:  11
 * Started:    29/04/2021
 *
 * @package    Nails
 * @subpackage module-email
 * @category   Database Migration
 * @author     Nails Dev Team
 */

namespace Nails\Email\Database\Migration;

use Nails\Common\Console\Migrate\Base;

/**
 * Class Migration11
 *
 * @package Nails\Cms\Database\Migration
 */
class Migration11 extends Base
{
    /**
     * Execute the migration
     *
     * @return void
     */
    public function execute()
    {
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}email_archive` CHANGE `email_vars` `email_vars` JSON NULL;');
    }
}

Set JSON as email vars data type

Set JSON as email vars data type


<?php
/**
* RssBridgeHumbleStoreDiscount
* Returns the 10 first sales from the Humble Store
* Enjoy your indie games :)
*
* @name Humble Store Discount Bridge
* @homepage https://www.humblebundle.com/store
* @description Returns the 10 first sales from the Humble Store
* @maintainer 16mhz
* @update 2014-07-18
*/
class HumbleStoreDiscountBridge extends BridgeAbstract{

    public function collectData(array $param){

        $result = file_get_html('https://www.humblebundle.com/store/api?request=2&page_size=20&sort=discount&page=0')
                or $this->returnError('Could not request the Humble Store.', 404);
        $string = json_decode($result, true);
        $items = $string['results'];
        $store_link = 'https://www.humblebundle.com/store/p/';
        $limit = 0;

        foreach ($items as $key => $value) {
            if ($limit < 10) {
                $new_price = $value['current_price'][0] . ' ' . $value['current_price'][1];
                $full_price = $value['full_price'][0] . ' ' . $value['full_price'][1];
                $product_name = $value['human_name'];
                $product_uri = $store_link . $value['machine_name'];
                $platforms = str_replace('\'', '', implode("','", $value['platforms']));
                $delivery_methods = str_replace('\'', '', implode("','", $value['delivery_methods']));

                $content = '' . $product_name . '
Current price: ' . $new_price . '
Full price: ' . $full_price
                    . '
Delivery methods: ' . $delivery_methods . '
Platforms: '
                    . $platforms . '
' . $value['description'];

                $item = new \Item();
                $item->title = $product_name . ' - ' . $new_price;
                $item->uri = $product_uri;
                $item->content = $content;
                $this->items[] = $item;
                $limit++;
            }
        }
    }

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

    public function getURI(){
        return 'https://www.humblebundle.com/store';
    }

    public function getCacheDuration(){
        return 21600; // 6 hours
    }
}

Add Humble Store Discount Bridge

Add Humble Store Discount Bridge


<?php

class LocationTest extends \PHPUnit_Framework_TestCase {
    public function testEqual() {
      $l1 = new Location('abcd', 42);
      $l2 = new Location('abcd', 42);
      $l3 = new Location('abcd', 41);
      $l4 = new Location('abc', 42);

      $this->assertTrue(
        $l1->equal($l2)
      );

      $this->assertFalse(
        $l1->equal($l3)
      );

      $this->assertFalse(
        $l1->equal($l4)
      );

    }

    public function testManipulation() {
      $l1 = new Location('abcd', 42);

      $this->assertEquals(
        $l1->advanceBy(1)->offset(),
        43
      );
    }
}

Add some tests for Location.

Add some tests for Location.


<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\grid\GridView;
/**
 * @var yii\web\View $this
 */
$this->title = Yii::t('Backend', 'Cost-benefit calculation');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php
        echo GridView::widget([
            'dataProvider' => $provider,
            'columns' => [
                ['label' => Yii::t('CostbenefitCalculation', 'Name'), 'value' => function ($data) { return ucfirst(Yii::t('CostbenefitItem', $data->name)); }],
                ['label' => Yii::t('CostbenefitCalculation', 'Planned')." (".Yii::t('CostbenefitCalculation', 'monthly').")", 'value' => function ($data) { return $data->value." €"; }],
                ['label' => Yii::t('CostbenefitCalculation', 'Realized')." (".Yii::t('CostbenefitCalculation', 'weekly').")"],
                ['label' => Yii::t('CostbenefitCalculation', 'Realized')." (".Yii::t('CostbenefitCalculation', 'monthly').")"],
            ],
        ]);
    ?>

Add a cost-benefit calculation view

Add a cost-benefit calculation view


<?php

class m140730_145611_fix_measurement_reference_keys extends OEMigration
{
	public function safeUp()
	{
		$this->dropForeignKey('measurement_reference_episode_id_fk', 'measurement_reference');
		$this->dropForeignKey('measurement_reference_event_id_fk', 'measurement_reference');

		$this->dropIndex('measurement_reference_event_id_fk', 'measurement_reference');

		$this->createIndex('measurement_reference_episode_id_unique', 'measurement_reference', 'episode_id,patient_measurement_id', true);
		$this->createIndex('measurement_reference_event_id_unique', 'measurement_reference', 'event_id,patient_measurement_id', true);

		$this->addForeignKey('measurement_reference_episode_id_fk', 'measurement_reference', 'episode_id', 'episode', 'id');
		$this->addForeignKey('measurement_reference_event_id_fk', 'measurement_reference', 'event_id', 'event', 'id');
	}

	public function safeDown()
	{
		echo "m140730_145611_fix_measurement_reference_keys does not support migration down.\n";
		return false;
	}
}

[OE-4588] Fix keys for measurement_reference table.


<?php

/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::group(['before' => 'Sentinel\auth'], function()
{
	Route::resource('projects', 'ProjectsController');
	Route::resource('tickets', 'TicketsController');
	Route::resource('invoices', 'InvoicesController');
	Route::get('/tickets/status/{status}', ['as' => 'ticket.by.status', 'uses' => 'TicketsController@filterByStatus']);
	Route::post('tickets/{id}/reply', 'TicketsController@reply');
	Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
	# Override Sentinel's Default user routes with our own filter requirement
	Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
	Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});

Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
	Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
	Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});

<?php

/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::group(['before' => 'Sentinel\auth'], function()
{
	Route::resource('projects', 'ProjectsController');
	Route::resource('tickets', 'TicketsController');
	Route::resource('invoices', 'InvoicesController');
	Route::get('/tickets/status/{status}', ['as' => 'tickets.by.status', 'uses' => 'TicketsController@filterByStatus']);
	Route::get('/projects/status/{status}', ['as' => 'projects.by.status', 'uses' => 'ProjectsController@filterByStatus']);
	Route::post('tickets/{id}/reply', 'TicketsController@reply');
	Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
	# Override Sentinel's Default user routes with our own filter requirement
	Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
	Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});

Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
	Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
	Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});

Add filter by status route for projects

Add filter by status route for projects


<?php

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

use Cercanias\Provider\Web\Provider;
use Cercanias\HttpAdapter\CurlHttpAdapter;
use Cercanias\Station;

$httpAdapter = new CurlHttpAdapter();
$provider = new Provider($httpAdapter);

$route = $provider->getRoute(Provider::ROUTE_SAN_SEBASTIAN);

echo "Route 'San Sebastián': \n";

foreach ($route->getStations() as $station) {
    /* @var Station $station */
    echo sprintf(" - [%5d] %s\n", $station->getId(), $station->getName());
}

echo sprintf("results: %d\n", $route->getStations()->count());

Add example: get route using curl.

Add example: get route using curl.


<?php

namespace CommerceGuys\AuthNet\DataTypes;

class OpaqueData extends BaseDataType implements PaymentMethodInterface
{

    const NONCE = 'COMMON.ACCEPT.INAPP.PAYMENT';
    const APPLE_PAY = 'COMMON.APPLE.INAPP.PAYMENT';
    const ANDROID_PAY = 'COMMON.ANDROID.INAPP.PAYMENT';
    const VISA_CHECKOUT = 'COMMON.VCO.ONLINE.PAYMENT';

    protected $propertyMap = [
        'dataDescriptor',
        'dataValue',
        'dataKey',
    ];
}

Support Opaque data (Accept.js, Apple Pay, Android Pay, Visa Checkout)


<?php
use Migrations\AbstractMigration;

class AddSrcLangTgtLangIndexToTranslations extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('sentences_translations');
        $table->addIndex(['sentence_lang', 'translation_lang'], ['name' => 'sentence_lang_translation_lang_idx'])
              ->removeIndexByName('sentence_lang')
              ->update();
    }
}

Add index on lang pairs with migration

Add index on lang pairs with migration


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\Console\Input\ArrayInput;

class SeedCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:seed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed default Cortex data.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        collect(Artisan::all())->filter(function ($command) {
            return strpos($command->getName(), 'cortex:seed:') !== false;
        })->each->run(new ArrayInput([]), $this->output);
    }
}

Add global cortex:seed artisan command

Add global cortex:seed artisan command


<?php

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

class AddExtraColumnsToGroups extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('phpbb_groups', function (Blueprint $table) {
            $table->string('identifier')->nullable();
            $table->string('short_name')->nullable();
            $table->string('mobile_name')->nullable();
            $table->integer('display_order')->default(0);
            $table->string('colour')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('phpbb_groups', function (Blueprint $table) {
            $table->dropColumn('identifier');
            $table->dropColumn('short_name');
            $table->dropColumn('mobile_name');
            $table->dropColumn('display_order');
            $table->dropColumn('colour');
        });
    }
}

Add columns needed for database-sourced group id


<?php

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

class AddWorkflowEnumToVisitsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE visits MODIFY resource_type ENUM('page','app_instance','workflow') NOT NULL DEFAULT 'page';");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE visits MODIFY resource_type ENUM('page','app_instance') NOT NULL DEFAULT 'page';");
    }
}

Add migration for workflow type in 'visits' log


<?php

namespace OpenConext\EngineBlockBundle\Authentication\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Note: this entity is currently only used to configure doctrine to create
 * the schema on installation.
 *
 * @ORM\Entity()
 * @ORM\Table(indexes={
 *     @ORM\Index(name="user_uuid", columns={"user_uuid", "service_provider_uuid"}),
 * })
 */
class SamlPersistentId
{
    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string", length=40, options={"fixed": true, "comment": "SHA1 of service_provider_uuid + user_uuid"})
     */
    public $persistentId;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=36, options={"fixed": true})
     */
    public $userUuid;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=36, options={"fixed": true})
     */
    public $serviceProviderUuid;
}

Add doctrine configuration for saml_persistent_id table


<?php

return [

    'name'          => 'Files only',

    'description'   => 'To be used for testing only - test if the build command can copy files',

    'basePath' => __DIR__ . '/resources/',

    'files' => [
        // Source files (inside 'basePath')  =>  Destination
        '.gitkeep'                  =>  '.gitkeep',
        'logs/default.log'          =>  'log.log',
        'docs/LICENSE.txt'          =>  'LICENSE',
        'docs/README.md'            =>  'README.md',
    ],
];

Add configuration file for "copy files" test

For the build command test


Add missing chainmap table row

Add missing chainmap table row


<?php

namespace FD\PrivateMessageBundle\Tests\Form;

use FD\PrivateMessageBundle\Entity\PrivateMessage;
use FD\PrivateMessageBundle\Form\PrivateMessageType;
use Symfony\Component\Form\Test\TypeTestCase;

/**
 * Class PrivateMessageTypeTest.
 */
class PrivateMessageTypeTest extends TypeTestCase
{
    /**
     * Test form submission.
     */
    public function testSubmitValidData()
    {
        $formData = [
            'body' => 'Foo body',
        ];

        $form = $this->factory->create(PrivateMessageType::class);
        $form->submit($formData);
        $this->assertTrue($form->isSynchronized());

        $expected = new PrivateMessage();
        $expected->setBody('Foo body');

        $this->assertEquals($expected, $form->getData(), '', 1);

        $view     = $form->createView();
        $children = $view->children;

        foreach (array_keys($formData) as $key) {
            $this->assertArrayHasKey($key, $children);
        }
    }
}

Add unit test for PrivateMessage's form

Add unit test for PrivateMessage's form


<?php

namespace ZpgRtf\Tests\Helpers;

use PHPUnit\Framework\TestCase;
use ZpgRtf\Helpers\DateTimeHelper;

class DateTimeHelperTest extends TestCase
{
    public function testCanInstantiate()
    {
        $this->assertInstanceOf(
            DateTimeHelper::class,
            new DateTimeHelper()
        );
    }

    public function testCanEncodeCustomFormat()
    {
        $format = 'c';
        $timestamp = date($format);

        $dateTimeHelper = new DateTimeHelper($timestamp);
        $dateTimeHelper->setHelperFormat($format);

        $this->assertSame(
            json_decode(json_encode($dateTimeHelper)),
            $timestamp
        );
    }
}

Add test for datetime helper

Add test for datetime helper


<?php

namespace IgraalOSL\StatsTable\Aggregation;

use IgraalOSL\StatsTable\Dumper\Format;
use IgraalOSL\StatsTable\StatsTableBuilder;

/**
 * Class CountAggregation
 * Returns number of element in dataset
 */
class CountAggregation implements AggregationInterface
{
    private $columnName;
    private $format;

    public function __construct($columnName, $format = Format::INTEGER)
    {
        $this->columnName = $columnName;
        $this->format = $format;
    }

    public function aggregate(StatsTableBuilder $statsTable)
    {
        $column = $statsTable->getColumn($this->columnName)->getValues();

        return count($column);
    }

    /**
     * @return mixed
     */
    public function getFormat()
    {
        return $this->format;
    }
}

Add a new Aggregation class to count the total number of line


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

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

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

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

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

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

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

?>

Add test to create a PublicDashboard project, so that CMake dashboards running on the same machine can submit to a localhost CDash.

git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@2253 91079597-3006-4846-9bd3-4f3fb3d139a7


<?php

// Use this to convert an existing concept_tree.json file
// from the original unsorted format to the new format,
// with concepts sorted by prefLabels.
// Feed in the original file as standard input;
// the updated data appears on standard output.

$text=stream_get_contents(STDIN);

$input_structure=json_decode($text);

function cmp($a, $b) {
    // Carefully imitate the ordering defined in the Toolkit method
    // provider.transform.JsonTreeTransformProvider.Concept.compareTo().
    if (!isset($a['prefLabel'])) {
        if (!isset($b['prefLabel'])) {
            return strcmp($a['iri'], $b['iri']);
        }
        return 1;
    }
    if (!isset($b['prefLabel'])) {
        return -1;
    }
    $prefLabelCmp = strcasecmp($a['prefLabel'], $b['prefLabel']);
    if ($prefLabelCmp != 0) {
        return $prefLabelCmp;
    }
    return strcmp($a['iri'], $b['iri']);
}

function make_new_structure($structure)
{
    $newstructure = array();

    foreach ($structure as $key => $value) {
        switch ($key) {
            case 'prefLabel':
            case 'definition':
            case 'notation':
                break;
        default:
            $newelement = array();
            $newelement['iri'] = $key;
            foreach ($value as $key2 => $value2) {
                switch ($key2) {
                case 'prefLabel':
                case 'definition':
                case 'notation':
                    $newelement[$key2] = $value2;
                    break;
                }
            }
            $narrower = make_new_structure($value);
            if (sizeof($narrower) > 0) {
                $newelement['narrower'] = $narrower;
            }
            $newstructure[] = $newelement;
        }
    }
    usort($newstructure, "cmp");
    return $newstructure;
}

print json_encode(make_new_structure($input_structure),
                  JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>

CC-1714: Add converter to update existing concept_tree.json files

Add a converter that will update existing concept_tree.json
files to the new, sorted format.


		<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/elements/left_blue.png" alt="">
		新建项目分类
		<form action="#">
			<input type="hidden" name="AttributeForm[attr_name]" value="<?php echo Attribute::ATTR_PROJECT_CAT; ?>">
			分类名称
			<input type="text" name="AttributeForm[attr_value]" class="inputlist2">
			<button class="submit_button" type="submit">提交</button>
		</form>

新建项目

			<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/elements/arrow_left.png">
			添加分类

				分类列表

Add new category view of project

Add new category view of project


<?php

namespace Tests\Feature;

use App\Org;
use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class SettingsTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * Test settings page is loaded.
     *
     * @return void
     */
    public function testDashboard()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('org/'.$org->id);

        $response->assertStatus(200)
                 ->assertViewHas('org');
    }

    /**
     * Test password can be changed.
     *
     * @return void
     */
    public function testPassword()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->post('org/'.$org->id, ['org_passwd' => 'password']);
        $response->assertRedirect('org/'.$org->id)
                 ->assertSessionHas('success', 'The organization password was successfully updated.');
        $this->assertTrue(password_verify('password', $org->fresh()->password));
    }

    /**
     * Test organization can be deleted.
     *
     * @return void
     */
    public function testDelete()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->delete('org/'.$org->id);
        $response->assertRedirect('dashboard')
                 ->assertSessionHas('success', 'The organization was successfully deleted.');
        $this->assertFalse($org->exists());
    }

    /**
     * Test custom message can be changed.
     *
     * @return void
     */
    public function testCustomMessage()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->post('org/'.$org->id.'/message', ['message' => '# Markdown test']);
        $response->assertRedirect('org/'.$org->id)
                 ->assertSessionHas('success', 'The message was successfully updated.');
        $this->assertEquals('# Markdown test', $org->fresh()->custom_message);
        $response = $this->actingAs($user)
                         ->post('org/'.$org->id.'/message', ['message' => 'Some text, \'<script>alert()</script>']);
        $response->assertRedirect('org/'.$org->id)
                 ->assertSessionHas('success', 'The message was successfully updated.');
        $this->assertEquals("Some text, \"", $org->fresh()->custom_message);
        $this->assertNotEquals('Some text, \'<script>alert()</script>', $org->fresh()->custom_message);
    }
}

Add tests for the settings page

:white_check_mark: Add tests for the settings page

 #48


<?php

namespace VirtualizorCompiler;

use App\Virtualizor\Lang\Java;
use PHPUnit\Framework\TestCase;

class JavaTest extends TestCase
{
    public function test1()
    {
        $code = "
import java.*;
public class test
{
	public static void main(String[] argv)
	{
		System.out.print(\"hello world\");
	}
}
		";
        $aa = new Java($code);
        $this->assertTrue($aa->exec() == "hello world");
    }
}

Create Java bridge compiler test case

Create Java bridge compiler test case


<?php

use Aedart\Scaffold\Console\BaseCommand;
use Mockery as m;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class BaseCommandTest
 *
 * @group console
 * @group baseCommand
 *
 * @coversDefaultClass Aedart\Scaffold\Console\BaseCommand
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class BaseCommandTest extends BaseUnitTest
{
    /**
     * Returns an instance of a BaseCommand mock
     *
     * @param string $name
     *
     * @return m\Mock|BaseCommand
     */
    public function makeBaseCommand($name)
    {
        return m::mock(BaseCommand::class, [$name])->makePartial();
    }

    /********************************************************
     * Actual tests
     *******************************************************/

    // TODO: It appears that it's not possible to mock the command - Mockery yield error, cannot find setName() on mock!?

//    /**
//     * @test
//     *
//     * @covers ::execute
//     * @covers ::runCommand
//     */
//    public function canExecuteRunCommand()
//    {
//        $name = 'baseCommand';
//        $baseCommand = $this->makeBaseCommand($name);
//        $baseCommand->shouldReceive('runCommand')
//            ->andReturn(0);
//
//        $app = new Application();
//        $app->add($baseCommand);
//
//        $command = $app->find($name);
//        $commandTester = new CommandTester($command);
//        $commandTester->execute([
//           'command' => $command->getName()
//        ]);
//    }
}

Add Test for Base Command

Add Test for Base Command

NOTE: This given test is NOT completed - it fails at the moment


<?php
function cacheJson($json_data, $file_name) {
    $cacheFile = $_SERVER['DOCUMENT_ROOT'] . '/cache/json/' . $file_name  . '.json';
    $fh = fopen($cacheFile, 'w');
    fwrite($fh, $json_data);
    fclose($fh);
}

function cacheJsonFromUrl($url, $file_name) {
    $cacheFile = $_SERVER['DOCUMENT_ROOT'] . '/cache/json/' . $file_name  . '.json';
    $json = file_get_contents($url);
    $fh = fopen($cacheFile, 'w');
    fwrite($fh, $json);
    fclose($fh);

    return $json;
}

function getJson($file_name) {
    $cacheFile = $_SERVER['DOCUMENT_ROOT'] . '/cache/json/' . $file_name . '.json';
    if (file_exists($cacheFile)) {
        $fh = fopen($cacheFile, 'r');
        return fread($fh, filesize($cacheFile));
    }
    else {
        return "No data available";
    }
}

Add service for json caching

Add service for json caching


<?php

class FixStatesCommandTest extends AcceptanceTestCase
{
    public function testFixesTestModuleWithAllFlag()
    {
        $output = $this->runConsole('fix:states -a');
        $this->assertFixing($output, 'elifixstatestest');
    }

    public function testFixesSpecifiedModule()
    {
        $output = $this->runConsole('fix:states elifixstatestest');
        $this->assertFixing($output, 'elifixstatestest');
    }

    private function assertFixing($output, $moduleId)
    {
        $this->assertContains('Fixing ' . $moduleId, $output);
    }

    public static function setUpBeforeClass()
    {
        $dir = static::getTestModuleDir();
        mkdir($dir, 0777, true);
        touch(dirname($dir) . '/vendormetadata.php');

        $metadata = <<<'PHP'
<?php

$sMetadataVersion = '1.1';

$aModule = array(
    'id'          => 'elifixstatestest',
    'title'       => 'Testing module',
    'description' => 'A module generated for testing',
    'thumbnail'   => '',
    'version'     => '0.0.0',
    'author'      => 'john@doe.com',
    'extend'      => array(
    ),
    'files'       => array(
    ),
    'blocks'      => array(
    ),
);
PHP;

        file_put_contents($dir . '/metadata.php', $metadata);
    }

    public static function tearDownAfterClass()
    {
        static::removeDirectory(static::getTestModuleDir());
    }

    private static function getTestModuleDir()
    {
        return OX_BASE_PATH . 'modules/eli/fixstatestest';
    }
}

Create acceptance tests for fix:states command


<?php

$title = 'Empty application without starter, display 404';

include_once( __DIR__ . '/../../../include.php' );

$title = ucfirst( \Staq\util\string_basename( __DIR__, 2 ) );
$path = \Staq\util\string_basename( __DIR__, 4 );
$tests = [ ];

$app = new \Staq\Application( $path );
$app->run( );

$tests[ 'Extensions' ] = ( $app->get_extensions( ) == [ 'Staq/example/application/2', 'Staq/starter', 'Staq/view', 'Staq/ground' ] );
$tests[ 'Platform' ] = ( $app->get_platform( ) == 'prod' );

echo '
' . $title . '

Tests :

';
foreach ( $tests as $name => $result ) {
	echo '
' . $name .': ' . ( $result ? 'OK' : 'ERROR' ) . '
';
}
echo '
';

return array_reduce( $tests, function( &$result, $item ){ return $result && $item; }, TRUE );

Add second application use case

Add second application use case


<?php

namespace CommerceGuys\Platform\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

class EnvironmentSshCommand extends EnvironmentCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('environment:ssh')
            ->setAliases(array('ssh'))
            ->addOption('project', null, InputOption::VALUE_OPTIONAL, 'The project ID')
            ->addOption('environment', null, InputOption::VALUE_OPTIONAL, 'The environment ID')
            ->addOption('echo', NULL, InputOption::VALUE_NONE, "Print the connection string to the console.")
            ->setDescription('SSH to the current environment.');
        // $this->ignoreValidationErrors(); @todo: Pass extra stuff to ssh? -i?
    }

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

        $sshUrlString = $this->getSshUrl();

        $command = 'ssh ' . $sshUrlString;
        $execute = !$input->getOption('echo');
        if ($execute) {
            passthru($command);
            return;
        }
        else {
            $output->writeln("<info>The SSH url for the current environment is: " . $command . "</info>");
            return;
        }
    }

}

<?php

namespace CommerceGuys\Platform\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

class EnvironmentSshCommand extends EnvironmentCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('environment:ssh')
            ->setAliases(array('ssh'))
            ->addOption('project', null, InputOption::VALUE_OPTIONAL, 'The project ID')
            ->addOption('environment', null, InputOption::VALUE_OPTIONAL, 'The environment ID')
            ->addOption('pipe', NULL, InputOption::VALUE_NONE, "Output the SSH URL only.")
            ->setDescription('SSH to the current environment.');
    }

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

        $sshUrlString = $this->getSshUrl();

        if ($input->getOption('pipe')) {
            $output->write($sshUrlString);
            return;
        }

        passthru("ssh $sshUrlString");
    }

}

Add --pipe option to ssh.

Add --pipe option to ssh.

Enables commands such as:

```
  ssh -i ~/.ssh/my_id_rsa `platform ssh --pipe` 'tail -f /var/log/deploy.log'
```


<?php
/**
 * Plugin Name: Restrict Content Pro - Group Accounts Members to MailChimp
 * Description: Subscribe users to your MailChimp list when they join a group.
 * Version: 1.0
 * Author: Sandhills Development, LLC
 * Author URI: https://sandhillsdev.com
 * License: GPL2
 */

/**
 * Subscribe users to your MailChimp list when they join a group.
 *
 * @param int   $user_id User ID of the group member.
 * @param array $args    Arguments used when adding the member to the group.
 */
function ag_rcp_add_group_members_to_mailchimp( $user_id, $args ) {

	// Bail if MailChimp Pro is not installed.
	if ( ! function_exists( 'rcp_mailchimp_pro' ) || ! function_exists( 'rcpga_group_accounts' ) ) {
		return;
	}

	$user = get_userdata( $user_id );

	if ( empty( $user ) ) {
		return;
	}

	$membership_id = ! empty( $args['group_id'] ) ? rcpga_group_accounts()->groups->get_membership_id( absint( $args['group_id'] ) ) : 0;

	// Bail if there's no membership associated with this group.
	if ( empty( $membership_id ) || ! $membership = rcp_get_membership( $membership_id ) ) {
		return;
	}

	$subscribe = rcp_mailchimp_pro()->api_helper->subscribe( $user->user_email, $user_id, $membership );

	if ( $subscribe ) {
		rcp_log( sprintf( 'Successfully added group member user #%d to MailChimp list.', $user_id ) );
	} else {
		rcp_log( sprintf( 'Failed to add group member user ID #%d to MailChimp List.', $user_id ) );
	}

}

add_action( 'rcpga_add_member_to_group_after', 'ag_rcp_add_group_members_to_mailchimp', 10, 2 );

Add code snippet for subscribing group members to MailChimp.


<?php

class SimplePie_Absolutize_Test_Bug_Pct_Encoding_Invalid_Second_Char extends SimplePie_Absolutize_Test
{
	function data()
	{
		$this->data['base'] = 'http://a/b/c/d';
		$this->data['relative'] = 'f%0o';
	}

	function expected()
	{
		$this->expected = 'http://a/b/c/f%250o';
	}
}

?>

Add new test for IRI class (the first character follow a % is valid, the second is not).


<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Add PHP file for contact formular

Add PHP file for contact formular


<?php

namespace Drupal\adtechmedia\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * AdTechMedia module configuration.
 */
class AdTechMediaAdminConfigForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'adtechmedia_admin_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return ['adtechmedia.admin_settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('adtechmedia.admin_settings');

    $form['main'] = array(
      '#type' => 'details',
      '#title' => $this->t('Main configuration'),
      '#open' => TRUE,
    );

    $form['main']['use_atm'] = array(
      '#type' => 'checkbox',
      '#title' => $this->t('Enable AdTechMedia'),
      '#default_value' => $config->get('use_atm'),
      '#description' => $this->t('Activate/Deactivate AdTechMedia service.'),
    );

    $form['debug'] = array(
      '#type' => 'details',
      '#title' => $this->t('Development'),
    );

    $form['debug']['development'] = array(
      '#type' => 'checkbox',
      '#title' => $this->t('Enable development mode'),
      '#default_value' => $config->get('development'),
    );

    return parent::buildForm($form, $form_state);
  }

}

Create new admin form for Drupal configurations


<?php
namespace Graze\Queue;

use Graze\Queue\Adapter\SqsAdapter;
use Mockery as m;
use PHPUnit_Framework_TestCase as TestCase;

class SqsIntegrationTest extends TestCase
{
    public function setUp()
    {
        $this->name = 'queue_foo';
        $this->sqsClient = m::mock('Aws\Sqs\SqsClient');
        $this->client = new Client(new SqsAdapter($this->sqsClient, 'queue_foo'));
    }

    protected function stubCreateQueue()
    {
        $url = 'queue://foo';
        $model = m::mock('Guzzle\Service\Resource\Model');
        $model->shouldReceive('getPath')->once()->with('QueueUrl')->andReturn($url);

        $this->sqsClient->shouldReceive('createQueue')->once()->with([
            'QueueName' => $this->name,
            'Attributes' => []
        ])->andReturn($model);

        return $url;
    }

    protected function stubQueueVisibilityTimeout($url)
    {
        $timeout = 120;
        $model = m::mock('Guzzle\Service\Resource\Model');
        $model->shouldReceive('getPath')->once()->with('Attributes')->andReturn(['VisibilityTimeout'=>$timeout]);

        $this->sqsClient->shouldReceive('getQueueAttributes')->once()->with([
            'QueueUrl' => $url,
            'AttributeNames' => ['VisibilityTimeout']
        ])->andReturn($model);

        return $timeout;
    }

    public function testReceive()
    {
        $url = $this->stubCreateQueue();
        $timeout = $this->stubQueueVisibilityTimeout($url);

        $receiveModel = m::mock('Guzzle\Service\Resource\Model');
        $receiveModel->shouldReceive('getPath')->once()->with('Messages')->andReturn([
            ['Body'=>'foo', 'Attributes'=>[], 'MessageAttributes'=>[], 'MessageId'=>0, 'ReceiptHandle'=>'a']
        ]);
        $this->sqsClient->shouldReceive('receiveMessage')->once()->with([
            'QueueUrl' => $url,
            'AttributeNames' => ['All'],
            'MaxNumberOfMessages' => SqsAdapter::BATCHSIZE_RECEIVE,
            'VisibilityTimeout' => $timeout
        ])->andReturn($receiveModel);

        $deleteModel = m::mock('Guzzle\Service\Resource\Model');
        $deleteModel->shouldReceive('getPath')->once()->with('Failed')->andReturn([]);
        $this->sqsClient->shouldReceive('deleteMessageBatch')->once()->with([
            'QueueUrl' => $url,
            'Entries' => [['Id'=>0, 'ReceiptHandle'=>'a']]
        ])->andReturn($deleteModel);

        $msgs = [];
        $this->client->receive(function ($msg) use (&$msgs) {
            $msgs[] = $msg;
        }, 100);

        $this->assertCount(1, $msgs);
    }

    public function testSend()
    {
        $url = $this->stubCreateQueue();
        $model = m::mock('Guzzle\Service\Resource\Model');
        $model->shouldReceive('getPath')->once()->with('Failed')->andReturn([]);

        $this->sqsClient->shouldReceive('sendMessageBatch')->once()->with([
            'QueueUrl' => $url,
            'Entries' => [['Id'=>0, 'MessageBody'=>'foo', 'MessageAttributes'=>[]]]
        ])->andReturn($model);

        $this->client->send([$this->client->create('foo')]);
    }
}

Add SQS adapter integration test

Add SQS adapter integration test


<?php

namespace Illuminate\Tests\Integration\Cookie;

use Mockery;
use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Illuminate\Support\Carbon;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Session\NullSessionHandler;
use Illuminate\Contracts\Debug\ExceptionHandler;

/**
 * @group integration
 */
class CookieTest extends TestCase
{
    public function test_cookie_is_sent_back_with_proper_expire_time_when_should_expire_on_close()
    {
        $this->app['config']->set('session.expire_on_close', true);

        Route::get('/', function () {
            return 'hello world';
        })->middleware('web');

        $response = $this->get('/');
        $this->assertCount(2, $response->headers->getCookies());
        $this->assertEquals(0, ($response->headers->getCookies()[1])->getExpiresTime());
    }

    public function test_cookie_is_sent_back_with_proper_expire_time_with_respect_to_lifetime()
    {
        $this->app['config']->set('session.expire_on_close', false);
        $this->app['config']->set('session.lifetime', 1);

        Route::get('/', function () {
            return 'hello world';
        })->middleware('web');

        Carbon::setTestNow(Carbon::now());
        $response = $this->get('/');
        $this->assertCount(2, $response->headers->getCookies());
        $this->assertEquals(Carbon::now()->getTimestamp() + 60, ($response->headers->getCookies()[1])->getExpiresTime());
    }

    protected function getEnvironmentSetUp($app)
    {
        $app->instance(
            ExceptionHandler::class,
            $handler = Mockery::mock(ExceptionHandler::class)->shouldIgnoreMissing()
        );

        $handler->shouldReceive('render')->andReturn(new Response);

        $app['config']->set('app.key', Str::random(32));
        $app['config']->set('session.driver', 'fake-null');

        Session::extend('fake-null', function () {
            return new NullSessionHandler;
        });
    }
}

Add test for cookie stuff.

Add test for cookie stuff.


<?php
namespace Ora\Accounting;

use Doctrine\ORM\Mapping AS ORM;

/**
 * ORM\Embeddable
 * @author andreabandera
 *
 */
class Balance {

	/**
	 * ORM\Column(type="integer")
	 * @var int
	 */
	private $value;

	/**
	 * ORM\Column(type="datetime")
	 * @var DateTime
	 */
	private $date;

	public function __construct($value, \DateTime $date)
	{
		$this->value = $value;
		$this->date = $date;
	}

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

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

Set "disabled" Doctrine persistence waiting for @Embeddable support (or a different design)


<?php

use Fhaculty\Graph\Vertex;

use Fhaculty\Graph\GraphViz;
use Fhaculty\Graph\Edge\Base as Edge;
use Fhaculty\Graph\Algorithm\ShortestPath\BreadthFirst;
use Fhaculty\Graph\Loader\CompleteGraph;

class BreadthFirstTest extends PHPUnit_Framework_TestCase
{
    public function testOne(){
        // TODO: this should NOT be part of the unit test
        // TODO: remove randomness
        $debug = false;

        $loader = new CompleteGraph(10);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        // randomly remove 70% of the edges
        foreach(array_slice(Edge::getAll($graph->getEdges(),Edge::ORDER_RANDOM),0,$graph->getNumberOfEdges()*0.8) as $edge){
            $edge->destroy();
        }

        $start = Vertex::getFirst($graph,Vertex::ORDER_RANDOM);
        $start->setLayoutAttribute('shape','doublecircle');

        // actually start breadth search
        $alg = new BreadthFirst($start);

        // visualize all resulting edges in blue
        foreach($alg->getEdges() as $edge){
            $edge->setLayoutAttribute('color','blue');
        }

        // visualize all reachable vertices in blue
        foreach($alg->getVertices() as $vertex){
            $vertex->setLayoutAttribute('color','blue');
        }

        if($debug){
            // visualize resulting graph
            $vis = new GraphViz($graph);
            $vis->display();
        }

        $this->assertTrue(count($alg->getVertices()) >= count($start->getVerticesEdgeTo()));

        // test all reachable vertices
        foreach($alg->getDistanceMap() as $vid=>$distance){
            if($debug) echo 'vertex '.$vid.' in distance '.$distance;
            $walk = $alg->getWalkTo($graph->getVertex($vid));

            $this->assertEquals($distance,$walk->getNumberOfEdges());

            if($debug){
                echo ' (vertex walk: '.implode(', ',$walk->getVerticesSequenceId()).')';
                echo PHP_EOL;

                $vis = new GraphViz($walk->createGraph());
                $vis->display();
            }
        }

        //$alg = new BreadthFirst($startVertex);
    }
}

Add skeleton for BFS unit test

Add skeleton for BFS unit test


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

/**
 * This class defines attributes, valid values, and usage which is generated from
 * a given json schema. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
 *
 * @author Chirag Shah <chirags@google.com>
 *
 */
class apiModel {

  public function __construct( /* polymorphic */ ) {
    if (func_num_args() ==  1 && 'array' == gettype(func_get_arg(0))) {
      // Initialize the model with the array's contents.
      $array = func_get_arg(0);
      foreach ($array as $key => $val) {
        $this->$key = $val;
      }
    }
  }
}

Allow a model (generated by the discovery schema) get initialized from an array.