<?php

namespace ZpgRtf\Tests\Objects;

use ZpgRtf\Objects\ListingDeleteObject;
use PHPUnit\Framework\TestCase;

class ListingDeleteObjectTest extends TestCase
{
    /**
     * @var ListingDeleteObject
     */
    protected $object;

    public function setUp()
    {
        $this->object = new ListingDeleteObject();
    }

    public function testCanInstantiate()
    {
        $this->assertInstanceOf(
            ListingDeleteObject::class,
            $this->object
        );
    }

    public function testCanSetListingReference()
    {
        $this->assertInstanceOf(
            ListingDeleteObject::class,
            $this->object->setListingReference('listing-000001')
        );

        $this->assertSame(
            'listing-000001',
            $this->object->getListingReference()
        );
    }

    public function testCanSetDeletionReason()
    {
        $this->assertInstanceOf(
            ListingDeleteObject::class,
            $this->object->setDeletionReason('Blah blah a reason')
        );

        $this->assertSame(
            'Blah blah a reason',
            $this->object->getDeletionReason()
        );
    }

    public function testCanJsonSerialize()
    {
        $this->assertJson(
            json_encode($this->object)
        );

        $this->assertInstanceOf(
            \JsonSerializable::class,
            $this->object
        );
    }
}

Add listing delete object test

Add listing delete object test


<?php
try {
    require_once('../../global_functions.php');
    require_once('../../connections/parameters.php');

    if (!isset($_SESSION)) {
        session_start();
    }

    $db = new dbWrapper_v3($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true);
    if (empty($db)) throw new Exception('No DB!');

    $memcache = new Memcache;
    $memcache->connect("localhost", 11211); # You might need to set "localhost" to "127.0.0.1"

    checkLogin_v2();
    if (empty($_SESSION['user_id64'])) throw new Exception('Not logged in!');

    $adminCheck = adminCheck($_SESSION['user_id64'], 'admin');
    if (empty($adminCheck)) throw new Exception('Not an admin!');

    $badUserNames = $db->q("SELECT * FROM `gds_users_mmr`;");

    if (!empty($badUserNames)) {
        foreach ($badUserNames as $key => $value) {
            $sqlResult = $db->q(
                'UPDATE `gds_users_mmr` SET `user_name` = ? WHERE `user_id64` = ?;',
                'ss',
                array(htmlentities_custom(html_entity_decode($value['user_name'])), $value['user_id64'])
            );

            if ($sqlResult) {
                echo "[SUCCESS] Updated name for [" . $value['user_id64'] . "]!
";
            }
            else{
                echo "[FAILURE] Did not update name for [" . $value['user_id64'] . "]!
";
            }

            flush();
        }
    } else {
        echo bootstrapMessage('Oh Snap', 'No username entries!', 'danger');
    }

    $memcache->close();
} catch (Exception $e) {
    $message = 'Caught Exception -- ' . $e->getFile() . ':' . $e->getLine() . '

' . $e->getMessage();
    echo bootstrapMessage('Oh Snap', $message, 'danger');
}

Update unicode names in MMR list

Update unicode names in MMR list


<?php

use React\EventLoop\Factory;
use Clue\React\Buzz\Browser;

class FunctionalBrowserTest extends TestCase
{
    private $loop;
    private $browser;

    public function setUp()
    {
        $this->loop = Factory::create();
        $this->browser = new Browser($this->loop);
    }

    public function testSimpleRequest()
    {
        $this->expectPromiseResolve($this->browser->get('http://www.google.com'));

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

    public function testNotFollowingRedirectsResolvesWithRedirectResult()
    {
        $browser = $this->browser->withOptions(array('followRedirects' => false));

        $this->expectPromiseResolve($browser->get('http://www.google.com'));

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

    public function testRejectingRedirectsRejects()
    {
        $browser = $this->browser->withOptions(array('maxRedirects' => 0));

        $this->expectPromiseReject($browser->get('http://www.google.com'));

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

    public function testInvalidPort()
    {
        $this->expectPromiseReject($this->browser->get('http://www.google.com:443'));

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

    public function testInvalidPath()
    {
        $this->expectPromiseReject($this->browser->get('http://www.google.com/does-not-exist'));

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

Add functional tests for Browser

Add functional tests for Browser


<?php

use Aedart\Scaffold\Transformers\DirectoryPaths;

/**
 * Class DirectoryPathsTest
 *
 * @group transformers
 * @group directoryPaths
 *
 * @coversDefaultClass Aedart\Scaffold\Transformers\DirectoryPaths
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class DirectoryPathsTest extends BaseUnitTest
{

    /**
     * Returns a directory list (multidimensional array)
     *
     * @return array
     */
    public function makeMultidimensionalDirectoriesList()
    {
        // This is rather static - but it will do the trick
        return [
            'app',
            'config',
            'src' =>    [
                'Contracts' => [
                    'Models' => [
                        'Users',
                        'Lists' => [
                            'UsersCollections'
                        ],
                        'Factories'
                    ],
                    'Events',
                    'Controllers',
                ],
                'Controllers',
                'Events',
                'Models',
            ],
        ];
    }

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

    /**
     * @test
     *
     * @covers ::transform
     */
    public function canFlattenDirectoriesList()
    {
        $expected = [
            'app',
            'config',
            'src/Contracts/Models/Users',
            'src/Contracts/Models/Lists/UsersCollections',
            'src/Contracts/Models/Factories',
            'src/Contracts/Events',
            'src/Contracts/Controllers',
            'src/Controllers',
            'src/Events',
            'src/Models',
        ];

        $result = DirectoryPaths::transform($this->makeMultidimensionalDirectoriesList());

        $this->assertSame($expected, $result);
    }
}

Add Directory Paths transformer test

Add Directory Paths transformer test


<?php

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

namespace App\Http\Controllers;

use App\Models\Attributes\Generic\Municipality;

/**
 * This is the tax office name trait.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
trait TaxOfficeNameTrait
{
    /**
     * Get the tax office name.
     *
     * @param \Illuminate\Database\Eloquent\Collection $generic
     *
     * @return string
     */
    public function getTaxOfficeName($office)
    {
        $name = $office->code.' - ';
        $name .= Municipality::find($office->municipality_id)->pluck('name');
        if ($office->number) {
            $name .= ' ('.$office->number.')';
        }

        return $name;
    }
}

Add tax office name trait

Add tax office name trait


<?php

class KalturaDistributionProfileArray extends KalturaTypedArray
{
	public static function fromDbArray($arr)
	{
		$newArr = new KalturaDistributionProfileArray();
		if ($arr == null)
			return $newArr;

		foreach ($arr as $obj)
		{
    		$nObj = KalturaDistributionProfileFactory::createKalturaDistributionProfile($obj->getProviderType());
			$nObj->fromObject($obj);
			$newArr[] = $nObj;
		}

		return $newArr;
	}

	public function __construct()
	{
		parent::__construct("KalturaDistributionProfile");
	}
}

<?php

class KalturaDistributionProfileArray extends KalturaTypedArray
{
	public static function fromDbArray($arr)
	{
		$newArr = new KalturaDistributionProfileArray();
		if ($arr == null)
			return $newArr;

		foreach ($arr as $obj)
		{
    		$nObj = KalturaDistributionProfileFactory::createKalturaDistributionProfile($obj->getProviderType());
    		if(!$nObj)
    		{
    			KalturaLog::err("Distribution Profile Factory could not find matching profile type for provider [" . $obj->getProviderType() . "]");
    			continue;
    		}
			$nObj->fromObject($obj);
			$newArr[] = $nObj;
		}

		return $newArr;
	}

	public function __construct()
	{
		parent::__construct("KalturaDistributionProfile");
	}
}

Make sure KalturaDistributionProfileFactory returned an object

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


<?php
use Phinx\Migration\AbstractMigration;

use Pragma\Historic\Change;

class AllowNullOnFieldsBeforeAfterInChanges extends AbstractMigration{
	public function change(){
		$t = $this->table(Change::getTableName());
		$t->changeColumn('before', 'text', ['null' => true])
		$t->changeColumn('after', 'text', ['null' => true]);
		$t->update();
	}
}

Change before/after column -> allow NULL


<?php

namespace Go\Aop\Framework;

class AbstractMethodInvocationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AbstractMethodInvocation
     */
    protected $invocation;

    public function setUp()
    {
        $this->invocation = $this->getMockForAbstractClass(
            'Go\Aop\Framework\AbstractMethodInvocation',
            array(__CLASS__, __FUNCTION__, array())
        );
    }

    public function testInvocationReturnsMethod()
    {
        $this->assertEquals(__CLASS__, $this->invocation->getMethod()->class);
        $this->assertEquals('setUp', $this->invocation->getMethod()->name);
    }

    public function testStaticPartEqualsToReflectionMethod()
    {
        $this->assertInstanceOf('ReflectionMethod', $this->invocation->getStaticPart());
    }

    public function testCanAccessThis()
    {
        $this->assertNull($this->invocation->getThis());
        $this->invocation->__invoke($this, array(1, 2, 3));
        $this->assertEquals($this, $this->invocation->getThis());
        $this->assertEquals(array(1, 2, 3), $this->invocation->getArguments());
    }
}

Add a test for AbstractMethodInvocation

Add a test for AbstractMethodInvocation


<?php

namespace Tests\Functional\BackendBundle\Controller;

use Tests\Functional\WebTestCase;

class TeamAddMemberControllerTest extends WebTestCase
{
    public function testUsersCanNotBeSearchedByAnonymous()
    {
        $client = static::createClient();
        $client->request('GET', '/backend/teams/users');

        $this->assertTrue($client->getResponse()->isRedirect('/login'));
    }

    /**
     * @dataProvider searchProvider
     */
    public function testUserCanBeSearched($search, $expectedUserEmails)
    {
        $client = static::createClient();
        $this->logIn($client, 'user');

        $client->request('GET', '/backend/teams/users', [
            'q' => $search
        ]);

        $this->assertTrue($client->getResponse()->isSuccessful());
        $this->assertEquals('application/json', $client->getResponse()->headers->get('Content-Type'));

        $results = json_decode($client->getResponse()->getContent(), true);
        $emails = array_column($results['users'], 'email');

        $this->assertEquals($expectedUserEmails, $emails);
    }

    public function searchProvider()
    {
        return [
            [ '', [] ],
            [ 'admin', ['admin@admin'] ],
            [ 'ad', ['admin@admin'] ],

            [ 'us', ['user@foo.org'] ],
            [ 'foo.org', ['user@foo.org'] ],
        ];
    }
}

Add a few functional tests for the user search controller


<?php declare(strict_types=1);

$test = '
class A {
    /**
     * @param B $b
     * @param $c C
     *
     * @return D
     *
     * @throws E
     */
    public function a() {
        return 1;
    }
}';

preg_match_all('/
    @(param|return|throws)
    \h+
    ((\?<!\$)[a-zA-Z0-9_\\]+)
    \h+
    $[a-zA-Z0-9_]+
    \s*\v/mx', $test, $matches);
var_dump($matches);

Add feature for doc comment parsing

Add feature for doc comment parsing


<?php
	require_once('../lib/env.php');

	require_once('http.php');
	require_once('session.php');
	require_once('db.php');

	switch ($_SERVER['REQUEST_METHOD']) {
		case 'GET':
			checkConnected();

			httpResponse(200, array(
				'user' => $_SESSION['user']
			));

			break;

		case 'OPTIONS':
			httpOptionsMethod(HTTP_GET);
			break;

		default:
			httpUnsupportedMethod();
			break;
	}
?>

Add new function: Get information of connected user

If user is connected, get all information.
Used by ftp-adm-frontend.


<?php

use Phinx\Migration\AbstractMigration;

class Configuration extends AbstractMigration
{
    public function change()
    {
		$configuration = $this->table("configuration");
		$configuration
			->addIndex("key")
			->addIndex("value")
			->update();
    }

    /**
     * Migrate Up.
     */
    public function up()
    {

    }

    /**
     * Migrate Down.
     */
    public function down()
    {

    }
}

Update configuration table to have indexes


<?php

namespace FileNamingResolver\NamingStrategy;

use FileNamingResolver\FileInfo;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class ContentHashNamingStrategy extends AbstractNamingStrategy
{
    const ALGORITHM_MD5 = 'md5';
    const ALGORITHM_SHA1 = 'sha1';

    /**
     * @var string Hash algorithm
     */
    protected $algorithm;

    /**
     * @var int Count of parts
     */
    protected $partCount;

    /**
     * @var int Length of each part
     */
    protected $partLength;

    /**
     * @param string $algorithm
     * @param int $partCount
     * @param int $partLength
     */
    public function __construct($algorithm = self::ALGORITHM_MD5, $partCount = 2, $partLength = 2)
    {
        $this->algorithm = (string)$algorithm;
        $this->partCount = (int)$partCount;
        $this->partLength = (int)$partLength;
    }

    /**
     * {@inheritdoc}
     */
    public function provideName(FileInfo $srcFileInfo)
    {
        if (!$srcFileInfo->isFile()) {
            throw new \InvalidArgumentException(sprintf(
                'The source file does not exist on %s specified path.',
                $srcFileInfo->toString()
            ));
        }
        $hash = hash_file($this->algorithm, $srcFileInfo->toString());

        $pathSuffixParts = array();
        for ($i = 0; $i < $this->partCount; $i++) {
            $pathSuffixParts[] = substr($hash, $i * $this->partLength, $this->partLength);
        }
        $name = substr($hash, $i * $this->partLength);
        $pathSuffix = implode(FileInfo::SEPARATOR_DIRECTORY, $pathSuffixParts);
        $dstFileInfo = $srcFileInfo
            ->changeBasename($name)
            ->changePath($srcFileInfo->getPath().FileInfo::SEPARATOR_DIRECTORY.$pathSuffix)
        ;

        return $dstFileInfo;
    }

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

    /**
     * @return int
     */
    public function getPartCount()
    {
        return $this->partCount;
    }

    /**
     * @return int
     */
    public function getPartLength()
    {
        return $this->partLength;
    }
}

Add content hash naming strategy

Add content hash naming strategy


<?php

namespace SpreadsheetsReplacement\Action;

/**
 * Description of Concat
 *
 * @author florian
 */
class Concat extends Action {

    private $start = '';

    private $end = '';

    /**
     * Returns the string to add at start of the value.
     * @return string the string
     */
    public function getStart() {
        return $this->start;
    }

    /**
     * Modify the string to add at start of the value.
     * @param string $start the string
     */
    public function setStart($start) {
        $this->start = (string)$start;
    }

    /**
     * Returns the string to add at start of the value.
     * @return string the string
     */
    public function getEnd() {
        return $this->end;
    }

    /**
     * Modify the string to add at start of the value.
     * @param string $end the string
     */
    public function setEnd($end) {
        $this->end = (string)$end;
    }

    /**
     * {@inheritDoc}
     */
    public function replace($value) {
        return $this->getStart().$value.$this->getEnd();
    }

}

Add an action to concat data at value

Add an action to concat data at value


<?php
/*
 * JSON Service for station Table changes
 */
require_once 'Zend/Json.php';
require_once '../../config/settings.inc.php';
require_once "$rootpath/include/database.inc.php";
$dbconn = iemdb('mesosite');
$rs = pg_prepare($dbconn, "SELECT", "SELECT *, x(geom) as lon, y(geom) as lat " .
		"from stations WHERE modified >= $1");

$date = isset($_REQUEST["date"]) ? $_REQUEST["date"] : date('Y-m-d');

$rs = pg_execute($dbconn, "SELECT", Array($date));

$ar = Array("stations" => Array() );
for( $i=0; $row = @pg_fetch_assoc($rs,$i); $i++){
  $ar["stations"][] = $row;
}
echo Zend_Json::encode($ar);
?>

Add JSON service for station metadata

Add JSON service for station metadata


<?php

namespace OAuth\OAuth2\Service;

use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Token\TokenInterface;
use OAuth\OAuth2\Token\StdOAuth2Token;

class Eve extends AbstractService
{

    public function __construct(
        CredentialsInterface $credentials,
        ClientInterface $httpClient,
        TokenStorageInterface $storage,
        $scopes = array(),
        UriInterface $baseApiUri = null
    ) {
        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);

        if (null === $baseApiUri) {
            $this->baseApiUri = new Uri('https://login.eveonline.com/oauth/');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthorizationUri(array $additionalParameters = array())
    {
        $parameters = array_merge(
            $additionalParameters,
            array(
                'client_id'     => $this->credentials->getConsumerId(),
                'redirect_uri'  => $this->credentials->getCallbackUrl(),
                'response_type' => 'code',
            )
        );

        // Build the url
        $url = clone $this->getAuthorizationEndpoint();
        foreach ($parameters as $key => $val) {
            $url->addToQuery($key, $val);
        }

        return $url;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthorizationEndpoint()
    {
        return new Uri('https://sisilogin.testeveonline.com/oauth/authorize');
    }

    /**
     * {@inheritdoc}
     */
    public function getAccessTokenEndpoint()
    {
        return new Uri('https://sisilogin.testeveonline.com/oauth/token');
    }

    /**
     * {@inheritdoc}
     */
    protected function getAuthorizationMethod()
    {
        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
    }

    /**
     * {@inheritdoc}
     */
    protected function parseAccessTokenResponse($responseBody)
    {
        $data = json_decode($responseBody, true);

        if (null === $data || ! is_array($data)) {
            throw new TokenResponseException('Unable to parse response.');
        } elseif (isset($data['error'])) {
            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
        }

        $token = new StdOAuth2Token();
        $token->setAccessToken($data['access_token']);
        $token->setLifetime($data['expires_in']);
        $token->setRefreshToken($data['refresh_token']);

        unset($data['access_token']);

        $token->setExtraParams($data);

        return $token;
    }

    /**
     * @return array
     */
    protected function getExtraOAuthHeaders()
    {
        return array('Accept' => 'application/json');
    }

    /**
     * Return any additional headers always needed for this service implementation's API calls.
     *
     * @return array
     */
    protected function getExtraApiHeaders()
    {
        return array('Accept' => 'application/json',
					'Authorization' => 'Bearer ' . $this->credentials->getConsumerSecret());
    }
}

Add EVE OAuth2 service provider.

Add EVE OAuth2 service provider.


<?php

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

/**
 * IMPORTANT. No guarantees are provided that this works exactly correct because I have created it
 * manually after the tables already exist in the database. It has been added to make it easier for
 * people following the tutorials.
 */
class m151102_144247_basetables extends Migration
{
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%author}}', [
            'id' => Schema::TYPE_PK,
            'firstname' => Schema::TYPE_STRING . '(32) NOT NULL',
            'surname' => Schema::TYPE_STRING . '(64) NOT NULL',
            'biography' => Schema::TYPE_STRING . '(2048)',
        ], $tableOptions);

        $this->createTable('{{%book}}', [
            'id' => Schema::TYPE_PK,
            'title' => Schema::TYPE_STRING . '(64) NOT NULL',
            'description' => Schema::TYPE_STRING . '(1024) NOT NULL',
            'author_id' => Schema::TYPE_INTEGER ,
            'isbn' => Schema::TYPE_STRING . '(32)',
            'rank' => Schema::TYPE_INTEGER,
        ], $tableOptions);

        $this->addForeignKey('FK_BOOK_AUTHOR', '{{%book}}', 'author_id', '{{%author}}', 'id', 'RESTRICT', 'RESTRICT');

        $this->createTable('{{%book_user_link}}', [
            'book_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'user_id' => Schema::TYPE_INTEGER . ' NOT NULL',
        ], $tableOptions);

        $this->addForeignKey('FK_BOOK_USER_LINK_BOOK', '{{%book_user_link}}', 'book_id', '{{%book}}', 'id', 'CASCADE', 'CASCADE');
        $this->addForeignKey('FK_BOOK_USER_LINK_USER', '{{%book_user_link}}', 'user_id', '{{%user}}', 'id', 'CASCADE', 'CASCADE');
    }

    public function safeDown()
    {
        $this->dropTable('{{%author}}');
        $this->dropTable('{{%book}}');
        $this->dropTable('{{%book_user_link}}');
    }
}

Add migration for base tutorial database tables


<?php
/**
 * Remove problematic hook that escapes html in code blocks
 */
add_action('init', function() {
    if (!class_exists('WPCom_Markdown')) {
        return;
    }

    $markdown = WPCom_Markdown::get_instance();

    remove_filter('content_save_pre', array($markdown, 'preserve_code_blocks'), 1);
}, 99);

Add a fix for markdown issues

Add a fix for markdown issues


<?php
namespace Bolt\Assets\File;

/**
 * File asset base class.
 *
 * @author Gawain Lynch <gawain.lynch@gmaill.com>
 */
abstract class AssetBase
{
    /** @var string */
    protected $fileName;
    /** @var boolean */
    protected $late = false;
    /** @var integer */
    protected $priority;
    /** @var string */
    protected $attributes;

    /**
     * Constructor.
     *
     * @param string $fileName
     * @param array  $options  'late'     - True to add to the end of the HTML <body>
     *                         'priority' - Loading priority
     *                         'attrib'   - A string containing either/or 'defer', and 'async'
     */
    public function __construct($fileName, array $options = [])
    {
        $this->fileName   = $fileName;
        $this->late       = isset($options['late']) ? $options['late'] : false;
        $this->priority   = isset($options['priority']) ? $options['priority'] : 0;
        $this->attributes = isset($options['attrib']) ? $options['attrib'] : null;
    }

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

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

Add a base class for file assets

Add a base class for file assets


@extends('clearboard.main.template')

@section('title', '400 Bad Request')

@section('content')

400 Bad Request

Goto the homepage

@endsection

Add 400 Bad Request error page

Add 400 Bad Request error page


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class TownStep7ConfirmationType extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    	$resolver->setDefaults(
    			array(
    					'allow_extra_fields' => TRUE
    			)
    	);
    }

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

Add new town step 7 confirmation type

Add new town step 7 confirmation type


<?php

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

class UpdateTicketitTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('ticketit', function (Blueprint $table) {
            $table->longText('intervention')->nullable()->after('html');
			$table->longText('intervention_html')->nullable()->after('intervention');
        });
    }

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

Add intervention fields in ticketit table


<?php

class Denkmal_Paging_Venue_SearchTest extends CMTest_TestCase {

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

    public function testGetItems() {
        $venue1 = Denkmal_Model_Venue::create('Foo 1', true, false);
        $venue2 = Denkmal_Model_Venue::create('Foo Bar 2', true, false);
        $venue3 = Denkmal_Model_Venue::create('Foo 3', true, false);
        Denkmal_Model_VenueAlias::create($venue3, 'Foo Bar 3');
        $venue4 = Denkmal_Model_Venue::create('Foo 4', true, false);

        $this->assertEquals(array($venue1, $venue3, $venue4, $venue2), new Denkmal_Paging_Venue_Search('foo'));
    }
}

Add test for venue-search paging

Add test for venue-search paging


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

namespace ZendTest\Form\TestAsset\Entity;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\InputFilterAwareInterface;

class Cat implements InputFilterAwareInterface
{
    /**
     * @var string
     */
    protected $name = null;

    /**
     * @var InputFilterInterface
     */
    protected $inputFilter = null;

    /**
     * @param string $name
     * @return Cat
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

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

    /**
     * Set input filter
     *
     * @param  InputFilterInterface $inputFilter
     * @return Cat
     */
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        $this->inputFilter = $inputFilter;
        return $this;
    }

    /**
     * Retrieve input filter
     *
     * @return InputFilterInterface
     */
    public function getInputFilter()
    {
        if (null === $this->inputFilter) {
            $this->inputFilter = new InputFilter();
        }
        return $this->inputFilter;
    }
}

Add input filter aware cat test asset

Add input filter aware cat test asset


<?php
use Doctrine\ORM\Tools\Console\ConsoleRunner;

// replace with file to your own project bootstrap
require_once '../init_autoloader.php';

$app = Zend\Mvc\Application::init(require 'application.config.php');

// replace with mechanism to retrieve EntityManager in your app
$entityManager = $app->getServiceManager()->get('doctrine.entitymanager.orm_default');

return ConsoleRunner::createHelperSet($entityManager);

Add CLI Configuration for Doctrine ORM Module Schema Tool


<?php

/**
 * Class FHKiel.
 * Defines the rules, actions, action params and transformer mappings for "Fachhochschule Kiel".
 */
class FHKiel extends UniversitySeeder {

    protected $universityId = 226;
    protected $published = true;

    public function run()
    {
        // create rule
        $rule = $this->createRule("Allgemein", UniversitySeeder::RULE_SEMESTER_FORMAT_SEMESTER, '(^\w+)\s*([0-9]+)');

        // Open login page, parse login action
        $this->createAction($rule, UniversitySeeder::ACTION_TYPE_NORMAL, UniversitySeeder::HTTP_GET, '//*[@id="wrapper"]//form[@name="loginform"]/@action', $url='https://qis.fh-kiel.de/qisserver/rds?state=user&type=0');

        // Post user credentials to {login action}, parse URL to exam administration page
        $login = $this->createAction($rule, UniversitySeeder::ACTION_TYPE_NORMAL, UniversitySeeder::HTTP_POST, '//*[@id="makronavigation"]/ul/li[3]/a/@href');
        $this->createActionParam($login, "username", $type=UniversitySeeder::ACTION_PARAM_TYPE_USERNAME);
        $this->createActionParam($login, "password", $type=UniversitySeeder::ACTION_PARAM_TYPE_PASSWORD);

        // Open exam administration, parse URL to exams extract
        $this->createAction($rule, UniversitySeeder::ACTION_TYPE_NORMAL, UniversitySeeder::HTTP_GET, '//div[6]//ul/li[5]/a/@href');

        // Select degree & parse URL to actual exams extract
        $this->createAction($rule, UniversitySeeder::ACTION_TYPE_NORMAL, UniversitySeeder::HTTP_GET, '//form/ul/li/a[3]/@href');

        // Open actual exams extract & parse table containing grade data
        $this->createAction($rule, UniversitySeeder::ACTION_TYPE_TABLE_GRADES, UniversitySeeder::HTTP_GET, '//form/table[2]');

        // create transformer mappings
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_EXAM_ID, '//td[1]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_NAME, '//td[2]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_SEMESTER, '//td[7]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_EXAM_DATE, '//td[8]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_GRADE, '//td[9]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_CREDIT_POINTS, '//td[11]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_STATE, '//td[12]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_ATTEMPT, '//td[5]');
        $this->createTransformerMapping($rule, UniversitySeeder::TRANSFORMER_MAPPING_ITERATOR, '//tr[./td[not(starts-with(@class, "qis_konto"))] and count(./td) = 13]');
    }
}

Add basic rule for FH Kiel

Add basic rule for FH Kiel


<?php
declare(strict_types=1);

namespace Tests\Hydrator;

use Onion\Framework\Hydrator\Interfaces\HydratableInterface;
use Onion\Framework\Hydrator\PropertyHydrator;

class PropertyHydratorTest extends \PHPUnit_Framework_TestCase
{
    private $testable;

    public function setUp()
    {

    }

    public function testHydration()
    {
        /**
         * @var $testable HydratableInterface
         */
        $testable = new class implements HydratableInterface
        {
            use PropertyHydrator;

            public $id;
            public $name;
        };
        $result = $testable->hydrate([
            'id' => 10,
            'name' => 'George'
        ]);
        $this->assertNotSame($testable, $result);
        $this->assertSame(10, $result->id);
        $this->assertSame('George', $result->name);
    }

    public function testDehydration()
    {
        /**
         * @var $testable HydratableInterface
         */
        $testable = new class implements HydratableInterface
        {
            use PropertyHydrator;

            public $id = 10;
            public $name = 'John';
        };

        $this->assertSame([
            'id' => 10,
            'name' => 'John'
        ], $testable->extract());
    }

    public function testNamingTransformation()
    {
        /**
         * @var $testable HydratableInterface
         */
        $testable = new class implements HydratableInterface
        {
            use PropertyHydrator;

            public $firstName = 'Jane';
        };

        $this->assertArrayHasKey('first_name', $testable->extract());
        $result = $testable->hydrate(['first_name' => 'Jenny']);
        $this->assertSame('Jenny', $result->firstName);
    }

    public function testSelectiveExtraction()
    {
        /**
         * @var $testable HydratableInterface
         */
        $testable = new class implements HydratableInterface
        {
            use PropertyHydrator;

            public $firstName = 'Jane';
        };

        $this->assertSame(['first_name' => 'Jane'], $testable->extract(['first_name']));
    }
}

Add test for property hydrator

Add test for property hydrator


<?php

namespace CloudCreativity\LaravelJsonApi\Tests\Integration;

use DummyApp\Post;
use DummyApp\User;
use Illuminate\Support\Facades\Route;

/**
 * Class SubDomainTest
 *
 * Tests routing when there is a route parameter before the JSON API route
 * parameters, in this case a wildcard domain. We need to test that this
 * does not affect the JSON API controller from obtaining route parameters.
 *
 * @package CloudCreativity\LaravelJsonApi
 */
class SubDomainTest extends TestCase
{

    /**
     * @var string
     */
    protected $resourceType = 'posts';

    public function testRead()
    {
        $post = factory(Post::class)->create();

        $this->doRead($post)->assertRead([
            'type' => 'posts',
            'id' => (string) $post->getKey(),
            'links' => [
                'self' => "http://foo.example.com/api/posts/{$post->getKey()}",
            ],
        ]);
    }

    public function testUpdate()
    {
        $post = factory(Post::class)->create();

        $this->doUpdate([
            'type' => 'posts',
            'id' => (string) $post->getKey(),
            'attributes' => [
                'title' => 'Hello World',
            ],
        ])->assertStatus(200);
    }

    public function testDelete()
    {
        $post = factory(Post::class)->create();

        $this->doDelete($post)->assertStatus(204);
    }

    public function testReadRelated()
    {
        $post = factory(Post::class)->create();

        $this->doReadRelated($post, 'author')->assertStatus(200);
    }

    public function testReadRelationship()
    {
        $post = factory(Post::class)->create();

        $this->doReadRelationship($post, 'author')->assertStatus(200);
    }

    public function testReplaceRelationship()
    {
        $post = factory(Post::class)->create();
        $user = factory(User::class)->create();

        $this->doReplaceRelationship($post, 'author', [
            'type' => 'users',
            'id' => (string) $user->getKey()
        ])->assertStatus(204);
    }

    /**
     * @return $this|void
     */
    protected function withAppRoutes()
    {
        Route::group([
            'domain' => '{wildcard}.example.com',
        ], function () {
            parent::withAppRoutes();
        });
    }

    /**
     * @param array $params
     * @return array
     */
    protected function addDefaultRouteParams(array $params)
    {
        $params['wildcard'] = 'foo';

        return $params;
    }
}

[Feature-WIP] Add failing tests for extra route parameters

If there are route parameters before the JSON API route parameters,
the current implementation results in errors because the
JSON API controller is not expecting additional route parameters
to be passed into its action methods. This commit adds a failing
test for this scenario using a wildcard sub-domain as the scenario.


<?php

/**
 * This file is part of the tarantool/client package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

use Tarantool\Client\Schema\Criteria;

require __DIR__.'/../bootstrap.php';

$client = create_client();
$spaceName = 'cars';

$client->evaluate(
<<<LUA
    if box.space[...] then box.space[...]:drop() end
    local space = box.schema.space.create(...)
    space:create_index('primary', {type = 'tree', parts = {1, 'unsigned'}})
    space:create_index('price', {type = 'tree', unique = false, parts = {3, 'unsigned'}})
    space:insert({1, 'Aston Martin Lagonda EV', 250})
    space:insert({2, 'Bentley Flying Spur Speed', 215})
    space:insert({3, 'Ferrari SF90 Stradale', 625})
    space:insert({4, 'Maserati MC20', 200})
    space:insert({5, 'Rolls Royce Ghost', 315})
LUA
, $spaceName);

$cars = $client->getSpace($spaceName);

echo "Top 3 most expensive cars:\n";
foreach ($cars->select(Criteria::index('price')
    ->andLtIterator()
    ->andLimit(3)
) as $car) {
    printf("$%sk - %s\n", $car[2], $car[1]);
}

echo "\n";

echo "Top 3 most expensive cars under $500k:\n";
foreach ($cars->select(Criteria::index('price')
    ->andKey([500])
    ->andLtIterator()
    ->andLimit(3)
) as $car) {
    printf("$%sk - %s\n", $car[2], $car[1]);
}

echo "\n";

echo "Top 3 least expensive cars:\n";
foreach ($cars->select(Criteria::index('price')
    ->andGtIterator()
    ->andLimit(3)
) as $car) {
    printf("$%sk - %s\n", $car[2], $car[1]);
}

/* OUTPUT
Top 3 most expensive cars:
$625k - Ferrari SF90 Stradale
$315k - Rolls Royce Ghost
$250k - Aston Martin Lagonda EV

Top 3 most expensive cars under $500k:
$315k - Rolls Royce Ghost
$250k - Aston Martin Lagonda EV
$215k - Bentley Flying Spur Speed

Top 3 least expensive cars:
$200k - Maserati MC20
$215k - Bentley Flying Spur Speed
$250k - Aston Martin Lagonda EV
*/

Add an example of data selection with sorting using the binary protocol


<?php

declare(strict_types=1);

namespace BinSoul\Test\Net\Mqtt\Packet;

use BinSoul\Net\Mqtt\Packet;
use BinSoul\Net\Mqtt\Packet\SubscribeResponsePacket;
use BinSoul\Net\Mqtt\PacketStream;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

class SubscribeResponsePacketTest extends TestCase
{
    private function getDefaultData(): string
    {
        return "\x90\x03\x00\x00\x00";
    }

    public function test_getters_and_setters(): void
    {
        $packet = new SubscribeResponsePacket();
        $packet->setIdentifier(1);
        $this->assertEquals(1, $packet->getIdentifier());

        $packet->setReturnCodes([0, 128]);
        $this->assertEquals([0, 128], $packet->getReturnCodes());
    }

    public function test_cannot_set_negative_identifier(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $packet = new SubscribeResponsePacket();
        $packet->setIdentifier(-1);
    }

    public function test_cannot_set_too_large_identifier(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $packet = new SubscribeResponsePacket();
        $packet->setIdentifier(12345678);
    }

    public function test_cannot_set_invalid_return_code(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $packet = new SubscribeResponsePacket();
        $packet->setReturnCodes([0, 128, 256]);
    }

    public function test_knows_error_return_code(): void
    {
        $packet = new SubscribeResponsePacket();
        $this->assertFalse($packet->isError(0));
        $this->assertTrue($packet->isError(128));
    }

    public function test_returns_names(): void
    {
        $packet = new SubscribeResponsePacket();
        for ($i = 0; $i <= 128; $i++) {
            $this->assertNotEmpty($packet->getReturnCodeName($i));
        }
    }

    public function test_write(): void
    {
        $packet = new SubscribeResponsePacket();
        $packet->setIdentifier(0);
        $packet->setReturnCodes([0]);

        $stream = new PacketStream();
        $packet->write($stream);

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

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

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

Test the subscribe response packet

Test the subscribe response packet


<?php
namespace Concrete\Core\Application;

/**
 * Interface ApplicationAwareInterface
 * This interface declares awareness of the concrete5 application.
 *
 * @package Concrete\Core\Application
 */
interface ApplicationAwareInterface
{
    /**
     * Set the application object
     *
     * @param \Concrete\Core\Application\Application $application
     */
    public function setApplication(Application $application);
}

Add an interface that declares awareness of the application instance


<?php namespace Flarum\Extend;

use Illuminate\Foundation\Application;

class ApiLink implements ExtenderInterface
{
    protected $actions;

    protected $relationships;

    public function __construct($actions, $relationships)
    {
        $this->actions = $actions;
        $this->relationships = $relationships;
    }

    public function extend(Application $app)
    {
        foreach ((array) $this->actions as $action) {
            $parts = explode('.', $action);
            $class = 'Flarum\Api\Actions\\'.ucfirst($parts[0]).'\\'.ucfirst($parts[1]).'Action';

            foreach ((array) $this->relationships as $relationship) {
                $class::$link[] = $relationship;
            }
        }
    }
}

Add API to add a link to an action

Add API to add a link to an action


<?php

class CM_FormField_Money extends CM_FormField_Text {

	/**
	 * @param string $name
	 * @param null $min
	 * @param null $max
	 */
	public function __construct($name, $min = null, $max = null) {
		parent::__construct($name);
		$this->_options['lengthMin'] = isset($min) ? (int) $min : null;
		$this->_options['lengthMax'] = isset($max) ? (int) $max : null;
	}

	public function validate($userInput, CM_Response_Abstract $response) {
		if (isset($this->_options['lengthMax']) && strlen($userInput) > $this->_options['lengthMax']) {
			throw new CM_Exception_FormFieldValidation('Too long');
		}
		if (isset($this->_options['lengthMin']) && strlen($userInput) < $this->_options['lengthMin']) {
			throw new CM_Exception_FormFieldValidation('Too short');
		}
		return $userInput;
	}

	public function prepare(array $params) {
		$this->setTplParam('tabindex', isset($params['tabindex']) ? $params['tabindex'] : null);
		$this->setTplParam('class', isset($params['class']) ? $params['class'] : null);
		$this->setTplParam('placeholder', isset($params['placeholder']) ? $params['placeholder'] : null);
	}
}

t824: Adjust roles form test to new form errors


{{--
    Copyright 2015-2017 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed 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 osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}

        prefix) }}" title={{ trans('changelog.prefixes.'.$log->prefix) }}>
         $log->user_id])}}" class="changelog-change__username">{{ $log->user->username }}

major === 1 ? 'changelog-change__right--major' : '' }}">
        {{ $log->category }}: {{ $log->message }}

{{--
    Copyright 2015-2017 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed 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 osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}

        prefix) }}" title={{ trans('changelog.prefixes.'.$log->prefix) }}>
         $log->user_id])}}" class="changelog-change__username">{{ $log->user->username }}

major === 1 ? 'changelog-change__right--major' : '' }}">
        @if(presence($log->category) === true)
            {{ $log->category }}:
        @endif
        {{ $log->message }}

Hide category when not specified

Hide category when not specified


<?php
/**
 * Adds reCAPTCHA to the RCP login form
 *
 * reCAPTCHA must be enabled in Restrict > Settings > Misc.
 * @see http://docs.restrictcontentpro.com/article/1586-recaptcha-supported
 */

/**
 * Add reCAPTCHA to the login form.
 *
 * @return void
 */
function ag_rcp_show_captcha_login_form() {
	global $rcp_options, $rcp_load_scripts;

	if ( rcp_is_recaptcha_enabled() ) :
		$rcp_load_scripts = true;
		?>
		<div id="rcp_recaptcha" data-callback="rcp_validate_recaptcha" class="g-recaptcha" data-sitekey="<?php echo esc_attr( $rcp_options['recaptcha_public_key'] ); ?>">

		<input type="hidden" name="g-recaptcha-remoteip" value=<?php echo esc_attr( rcp_get_ip() ); ?>/>

	<?php endif;
}
add_action( 'rcp_login_form_fields_before_submit', 'ag_rcp_show_captcha_login_form' );

/**
 * Validate reCAPTCHA during login form submission and throw an error if invalid.
 *
 * @param array $data Data passed through the login form.
 *
 * @return void
 */
function ag_rcp_validate_login_captcha( $data ) {

	global $rcp_options;

	if ( ! rcp_is_recaptcha_enabled() ) {
		return;
	}

	if ( empty( $data['g-recaptcha-response'] ) || empty( $data['g-recaptcha-remoteip'] ) ) {
		rcp_errors()->add( 'invalid_recaptcha', __( 'Please verify that you are not a robot', 'rcp' ), 'login' );

		return;
	}

	$verify = wp_safe_remote_post(
		'https://www.google.com/recaptcha/api/siteverify',
		array(
			'body' => array(
				'secret'   => trim( $rcp_options['recaptcha_private_key'] ),
				'response' => $data['g-recaptcha-response'],
				'remoteip' => $data['g-recaptcha-remoteip']
			)
		)
	);

	$verify = json_decode( wp_remote_retrieve_body( $verify ) );

	if ( empty( $verify->success ) || true !== $verify->success ) {
		rcp_errors()->add( 'invalid_recaptcha', __( 'Please verify that you are not a robot', 'rcp' ), 'login' );
	}

}
add_action( 'rcp_login_form_errors', 'ag_rcp_validate_login_captcha' );

Add snippet for adding reCAPTCHA to the login form.


<?php

namespace fennecweb\ajax\listing;

use \fennecweb\WebService as WebService;

class OverviewTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingOverviewTestUser';
    const USERID = 'listingOverviewTestUser';
    const PROVIDER = 'listingOverviewTestUser';

    public function testExecute()
    {
        //Test for overview if user is not logged in
        list($service) = WebService::factory('listing/Overview');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
            "projects" => 0,
            "organisms" => 173716,
            "trait_entries" => 48916,
            "trait_types" => 1
        );
        $this->assertEquals($expected, $results);

        //Test of correct project if the user has only one project
        $_SESSION['user'] = array(
            'nickname' => OverviewTest::NICKNAME,
            'id' => OverviewTest::USERID,
            'provider' => OverviewTest::PROVIDER,
            'token' => 'listingOverviewTestUserToken'
        );
        list($service) = WebService::factory('listing/Overview');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected['projects'] = 1;
        $this->assertArraySubset($expected, $results);
    }
}

Add test case for listing overview webservice


<?php

/**
 * @author    Mauri de Souza Nunes <mauri870@gmail.com>
 * @copyright Copyright (c) 2015, Mauri de Souza Nunes <github.com/mauri870>
 * @license   https://opensource.org/licenses/MIT MIT License
 */

namespace Mauri870\LaravelInstaller\Tests;

use Mauri870\LaravelInstaller\Console\NewCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

use PHPUnit_Framework_TestCase as PhpUnit;

class NewCommandTest extends PhpUnit
{

    /**
     * Test execute method
     */
    public function testExecute()
    {
        $application = new Application();
        $application->add(new NewCommand());

        $command = $application->find('new');
        $commandTester = new CommandTester($command);

        $commandTester->execute(['command' => $command->getName(),'name'=>'test','version'=>'LTS']);

        $this->assertRegExp('/Application ready! Build something amazing./', $commandTester->getDisplay());
    }
}

Add test for the new command

Add test for the new command


<?php
/**
 * @author Sergii Bondarenko, <sb@firstvector.org>
 */

namespace Drupal\Tests\TqExtension\Utils;

use Drupal\TqExtension\Utils\Tags;

/**
 * Class TagsTest.
 *
 * @package Drupal\Tests\TqExtension\Utils
 */
class TagsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Tags
     */
    private $tags;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->tags = $this->getMockForTrait(Tags::class);
    }

    /**
     * @test
     */
    public function collectTags()
    {
        $this->tags->collectTags(['JavaScript', 'WYSIWYG', 'wysiwyg:CKEditor']);

        self::assertAttributeCount(2, 'tags', $this->tags);
    }

    /**
     * @test
     */
    public function hasTag()
    {
        $this->collectTags();

        self::assertTrue($this->tags->hasTag('javascript'));
        self::assertTrue($this->tags->hasTag('wysiwyg'));

        self::assertFalse($this->tags->hasTag('JavaScript'));
        self::assertFalse($this->tags->hasTag('WYSIWYG'));
    }

    /**
     * @test
     */
    public function getTag()
    {
        $this->collectTags();

        self::assertSame('CKEditor', $this->tags->getTag('wysiwyg'));
    }
}

Add unit tests for "Tags" utility

Add unit tests for "Tags" utility


<?php
namespace Math\SetTheory;

class ImmutableSetTest extends \PHPUnit_Framework_TestCase
{
    public function testAddDoesNothing()
    {
        $A = new ImmutableSet([1, 2, 3, 4]);
        $B = $A->copy();

        $A->add(5);
        $A->add(6);
        $A->add([7, 8, 9]);
        $A->add(new Set(['a', 'b']));

        $this->assertEquals($B, $A);
        $this->assertEquals($B->asArray(), $A->asArray());
    }

    public function testRemoveDoesNothing()
    {
        $A = new ImmutableSet([1, 2, 3, 4]);
        $B = $A->copy();

        $A->remove(1);
        $A->remove([2, 3]);

        $this->assertEquals($B, $A);
        $this->assertEquals($B->asArray(), $A->asArray());
    }

    public function testClearDoesNothing()
    {
        $A = new ImmutableSet([1, 2, 3, 4]);
        $B = $A->copy();

        $A->clear();

        $this->assertEquals($B, $A);
        $this->assertEquals($B->asArray(), $A->asArray());
    }
}

Add unit tests for ImmutableSet.

Add unit tests for ImmutableSet.


<?php

namespace ForkCMS\Modules\Backend\Domain\User;

use DateTimeImmutable;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

trait Blameable
{
    /**
     * @Gedmo\Blameable(on="create")
     */
    #[ORM\ManyToOne(targetEntity: User::class)]
    private User|null $createdBy;

    #[Gedmo\Timestampable(on: 'create')]
    #[ORM\Column(type: Types::DATE_IMMUTABLE)]
    private DateTimeImmutable $createdOn;

    /**
     * @Gedmo\Blameable(on="update")
     */
    #[ORM\ManyToOne(targetEntity: User::class)]
    private User|null $updatedBy;

    #[Gedmo\Timestampable]
    #[ORM\Column(type: Types::DATE_IMMUTABLE)]
    private DateTimeImmutable $updatedOn;

    public function getCreatedBy(): ?User
    {
        return $this->createdBy;
    }

    public function getCreatedOn(): DateTimeImmutable
    {
        return $this->createdOn;
    }

    public function getUpdatedBy(): ?User
    {
        return $this->updatedBy;
    }

    public function getUpdatedOn(): DateTimeImmutable
    {
        return $this->updatedOn;
    }
}

Add trait to easily track who updated when


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

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

class ProjectVariableDeleteCommand extends CommandBase
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('project:variable:delete')
            ->addArgument('name', InputArgument::REQUIRED, 'The variable name')
            ->setDescription('Delete a variable from a project');
        $this->addProjectOption()
             ->addNoWaitOption();
        $this->addExample('Delete the variable "example"', 'example');
    }

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

        $variableName = $input->getArgument('name');

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

            return 1;
        }

        if (!$variable->operationAvailable('delete')) {
            $this->stdErr->writeln("The variable <error>$variableName</error> cannot be deleted");

            return 1;
        }

        $projectId = $this->getSelectedProject()->id;
        $confirm = $this->getHelper('question')
                        ->confirm(sprintf("Delete the variable <info>%s</info> from the project <info>%s</info>?", $variableName, $projectId),
                            false
                        );

        if (!$confirm) {
            return 1;
        }

        $result = $variable->delete();

        $this->stdErr->writeln("Deleted variable <info>$variableName</info>");

        $success = true;
        if (!$result->countActivities()) {
            $this->rebuildWarning();
        }
        elseif (!$input->getOption('no-wait')) {
            $success = ActivityUtil::waitMultiple($result->getActivities(), $this->stdErr, $this->getSelectedProject());
        }

        return $success ? 0 : 1;
    }

}

Add a Project Variable Delete command.

Add a Project Variable Delete command.


<?php

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

class CascadeDeleteForiegnKeys extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('signups', function ($table) {
            $table->dropForeign('signups_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
        });

        Schema::table('reviews', function ($table) {
            $table->dropForeign('reviews_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
        });

        Schema::table('photos', function ($table) {
            $table->dropForeign('photos_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('signups', function ($table) {
            $table->dropForeign('signups_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events');
        });

        Schema::table('reviews', function ($table) {
            $table->dropForeign('reviews_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events');
        });

        Schema::table('photos', function ($table) {
            $table->dropForeign('photos_event_id_foreign');
            $table->foreign('event_id')->references('id')->on('events');
        });
    }
}

Use cascade delete on foriegn keys

Use cascade delete on foriegn keys


<?php

// this simple example reads from STDIN, assigns a random text color and then prints to STDOUT.
// you can run this example and notice anything you type will get a random color:
// $ php random-colors.php
//
// you can also pipe the output of other commands into this like this:
// $ echo hello | php random-colors.php
//
// notice how if the input contains any colors to begin with, they will be replaced
// with random colors:
// $ phpunit --color=always | php random-colors.php

use React\Stream\Stream;
use React\EventLoop\Factory;
use Clue\React\Term\ControlCodeParser;

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

$loop = Factory::create();

if (function_exists('posix_isatty') && posix_isatty(STDIN)) {
    // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
    shell_exec('stty -icanon -echo');
}

// process control codes from STDIN
$stdin = new Stream(STDIN, $loop);
$parser = new ControlCodeParser($stdin);

$stdout = new Stream(STDOUT, $loop);
$stdout->pause();

// pass all c0 codes through to output
$parser->on('c0', array($stdout, 'write'));

// replace any color codes (SGR) with a random color
$parser->on('csi', function ($code) use ($stdout) {
    // we read any color code (SGR) on the input
    // assign a new random foreground and background color instead
    if (substr($code, -1) === 'm') {
        $code = "\033[" . mt_rand(30, 37) . ';' . mt_rand(40, 47) . "m";
    }

    $stdout->write($code);
});

// reset to default color at the end
$stdin->on('close', function() use ($stdout) {
    $stdout->write("\033[m");
});

// pass plain data to output
$parser->pipe($stdout, array('end' => false));

// start with random color
$stdin->emit('data', array("\033[m"));

$loop->run();

Add example which assigns a random text color to the input


<?php
namespace Grav\Common\Twig;

use Grav\Common\GravTrait;

/**
 * A trait to add some custom processing to the identifyLink() method in Parsedown and ParsedownExtra
 */
trait WriteCacheFileTrait
{
    use GravTrait;

    protected static $umask;
    /**
     * This exists so template cache files use the same
     * group between apache and cli
     *
     * @param $file
     * @param $content
     */
    protected function writeCacheFile($file, $content)
    {
        if (!isset(self::$umask)) {
            self::$umask = self::getGrav()['config']->get('system.twig.umask_fix', false);
        }

        if (self::$umask) {
            if (!is_dir(dirname($file))) {
                $old = umask(0002);
                mkdir(dirname($file), 0777, true);
                umask($old);
            }
            parent::writeCacheFile($file, $content);
            chmod($file, 0775);
        } else {
            parent::writeCacheFile($file, $content);
        }
    }
}

<?php
namespace Grav\Common\Twig;

use Grav\Common\GravTrait;

/**
 * A trait to add some custom processing to the identifyLink() method in Parsedown and ParsedownExtra
 */
trait WriteCacheFileTrait
{
    use GravTrait;

    protected static $umask;
    /**
     * This exists so template cache files use the same
     * group between apache and cli
     *
     * @param $file
     * @param $content
     */
    protected function writeCacheFile($file, $content)
    {
        if (empty($file)) {
            return;
        }

        if (!isset(self::$umask)) {
            self::$umask = self::getGrav()['config']->get('system.twig.umask_fix', false);
        }

        if (self::$umask) {
            if (!is_dir(dirname($file))) {
                $old = umask(0002);
                mkdir(dirname($file), 0777, true);
                umask($old);
            }
            parent::writeCacheFile($file, $content);
            chmod($file, 0775);
        } else {
            parent::writeCacheFile($file, $content);
        }
    }
}

Fix for empty file when writing cache

Fix for empty file when writing cache


<?php
namespace ZBateson\MailMimeParser;

use PHPUnit_Framework_TestCase;

/**
 * Description of HeaderPartFactoryTest
 *
 * @group MimePartFactory
 * @author Zaahid Bateson
 */
class MimePartFactoryTest extends PHPUnit_Framework_TestCase
{
    protected $mimePartFactory;

    protected function setUp()
    {
        $headerFactory = $this->getMockBuilder('ZBateson\MailMimeParser\Header\HeaderFactory')
            ->disableOriginalConstructor()
            ->getMock();
        $this->mimePartFactory = new MimePartFactory($headerFactory);
    }

    public function testNewMimePart()
    {
        $part = $this->mimePartFactory->newMimePart();
        $this->assertNotNull($part);
        $this->assertInstanceOf('\ZBateson\MailMimeParser\MimePart', $part);
    }

    public function testNewNonMimePart()
    {
        $part = $this->mimePartFactory->newNonMimePart();
        $this->assertNotNull($part);
        $this->assertInstanceOf('\ZBateson\MailMimeParser\NonMimePart', $part);
    }

    public function testNewUUEncodedPart()
    {
        $part = $this->mimePartFactory->newUUEncodedPart(066, 'test');
        $this->assertNotNull($part);
        $this->assertInstanceOf('\ZBateson\MailMimeParser\UUEncodedPart', $part);
    }
}

Add unit test for MimePartFactory

Add unit test for MimePartFactory


<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

/**
 * Migration script for adding com_forum component entry if missing, or adding admin_menu_link if missing
 **/
class Migration20130918132946ComForum extends Hubzero_Migration
{
	/**
	 * Up
	 **/
	protected static function up($db)
	{
		self::addComponentEntry('Forum');

		if (version_compare(JVERSION, '1.6', 'lt'))
		{
			$query = "SELECT * FROM `#__components` WHERE `name` = 'Forum'";
			$db->setQuery($query);
			$result = $db->loadObject();

			if ($result && empty($result->admin_menu_link))
			{
				$query = "UPDATE `#__components` SET `admin_menu_link` = 'option=com_forum' WHERE `id` = '{$result->id}'";
				$db->setQuery($query);
				$db->query();
			}
		}
	}

	/**
	 * Down
	 **/
	protected static function down($db)
	{
		self::deleteComponentEntry('Forum');
	}
}

Add migration for adding/fixing forum component entry


<?php

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

namespace App\Models\Attributes\Generic;

use Illuminate\Database\Eloquent\Model;

/**
 * This is the item's purchase type model class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 *
 * @property int    $id
 * @property string $name
 * @property string $regex
 */
class ItemPurchaseType extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'item_purchase_types';

    /**
     * The primary key column.
     *
     * @var string
     */
    protected $primaryKey = 'id';
}

Add the purchase type model

Add the purchase type model


<?php
namespace Vmwarephp\Exception;

class InvalidTraversalPropertyFormat extends \Exception {

	function __construct($message = null, $code = 0, Exception $previous = null) {
		$defaultMessage = 'Invalid traversal property format provided. Valid traversal property format is: propertyName => array(propertyType, arrayOfPropertyTypeProperties)';
		parent::__construct($message ? : $defaultMessage, $code, $previous);
	}
}

Add invalid traversal property format exception


<?php

use Test\Tool\BaseTestCase;
use Knp\Component\Pager\Paginator;
use Knp\Component\Pager\Pagination\SlidingPagination;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Test\Mock\PaginationSubscriber as MockPaginationSubscriber;
use Knp\Component\Pager\Pagination\PaginationInterface;
use Knp\Component\Pager\Event\Subscriber\Paginate\DoctrineCollectionSubscriber;
use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber;
use Doctrine\Common\Collections\ArrayCollection;

class DoctrineCollectionTest extends BaseTestCase
{
    /**
     * @test
     */
    function shouldPaginateCollection()
    {
        $dispatcher = new EventDispatcher;
        $dispatcher->addSubscriber(new DoctrineCollectionSubscriber);
        $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view
        $p = new Paginator($dispatcher);

        $items = new ArrayCollection(array('first', 'second'));
        $view = $p->paginate($items, 1, 10);
        $this->assertTrue($view instanceof PaginationInterface);

        $this->assertEquals(1, $view->getCurrentPageNumber());
        $this->assertEquals(10, $view->getItemNumberPerPage());
        $this->assertEquals(2, count($view->getItems()));
        $this->assertEquals(2, $view->getTotalItemCount());
        $this->assertEquals('', $view->getAlias());
    }

    /**
     * @test
     */
    function shouldSlicePaginateAnArray()
    {
        $dispatcher = new EventDispatcher;
        $dispatcher->addSubscriber(new DoctrineCollectionSubscriber);
        $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view
        $p = new Paginator($dispatcher);

        $items = new ArrayCollection(range('a', 'u'));
        $view = $p->paginate($items, 2, 10, array('alias' => 'al'));

        $this->assertEquals(2, $view->getCurrentPageNumber());
        $this->assertEquals(10, $view->getItemNumberPerPage());
        $this->assertEquals(10, count($view->getItems()));
        $this->assertEquals(21, $view->getTotalItemCount());
        $this->assertEquals('al', $view->getAlias());
    }

    /**
     * @test
     */
    function shouldSupportPaginateStrategySubscriber()
    {
        $dispatcher = new EventDispatcher;
        $dispatcher->addSubscriber(new DoctrineCollectionSubscriber);
        $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view

        $items = new ArrayCollection(array('first', 'second'));
        $p = new Paginator($dispatcher);
        $view = $p->paginate($items, 1, 10);
        $this->assertTrue($view instanceof PaginationInterface);
    }
}

Add tests for Doctrine collection

Add tests for Doctrine collection


<?php

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

class CreateInvitesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('invites', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('realm_id');
            $table->string('to');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('invites');
    }
}

Add migration for invites table.

Add migration for invites table.


<?php

// Make sure we are called from index.php
if (!defined('SECURITY'))
die('Hacking attempt');

// Check user token
$id = $user->checkApiKey($_REQUEST['api_key']);

// We have to check if that user is admin too
if ( ! $user->isAdmin($id) ) {
  header("HTTP/1.1 401 Unauthorized");
  die("Access denied");
}

// Is it a username or a user ID
ctype_digit($_REQUEST['id']) ? $username = $user->getUserName($_REQUEST['id']) : $username = $_REQUEST['id'];
ctype_digit($_REQUEST['id']) ? $id = $_REQUEST['id'] : $id = $user->getUserId($_REQUEST['id']);

// Output JSON format
echo json_encode(array('getuserstatus' => array(
  'username' => $username,
  'shares' =>  $statistics->getUserShares($id),
  'hashrate' => $statistics->getUserHashrate($id)
)));

// Supress master template
$supress_master = 1;
?>

Add API call for getuserstatus

Add API call for getuserstatus

Fixes #126, see Github Wiki for documentation


<?php
namespace PhpSlackBot\Command;

class PokerPlanningCommand extends BaseCommand {

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

    protected function execute($message, $context) {
        $args = $this->getArgs($message);
        $command = isset($args[2]) ? $args[2] : '';

        if ($command == 'start') {
            if (count($args) < 4) {
                $this->send($this->getCurrentChannel(), $this->getCurrentUser(), 'Please specify at least one user');
            }
            else  {
                $users = array_slice($args, 3);
                var_dump($context);
                $this->send($this->getCurrentChannel(), $this->getCurrentUser(), 'Starting Poker Planning with '.implode(' ', $users));
                foreach ($users as $user) {
                    $this->send($this->getCurrentChannel(), $this->getCurrentUser(), 'Please choose a number between '.implode(' ', $this->getSequence()));
                }
            }
        }
        else if ($command == 'status') {
            $this->send($this->getCurrentChannel(), $this->getCurrentUser(), 'Status');
        }
        else {
            $this->send($this->getCurrentChannel(), $this->getCurrentUser(), 'No comprendo. Use "pokerplanning start" or "pokerplanning status"');
        }
    }

    private function getArgs($message) {
        $args = array();
        if (isset($message['text'])) {
            $args = array_values(array_filter(explode(' ', $message['text'])));
        }
        return $args;
    }

    private function getSequence() {
        return array(0, 1, 2, 3, 5, 8, 13, 20);
    }

}

Add first implementation of a "poker planning" command


<?php namespace Aedart\Scaffold\Providers;

use Aedart\Scaffold\Loggers\ConsoleWrite;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Console Logger Service Provider
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Providers
 */
class ConsoleLoggerServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerLogger();
    }

    /**
     * Register the console writer
     */
    protected function registerLogger()
    {
        $this->app->bind(LoggerInterface::class, function($app, array $data = []){
            return new ConsoleWrite(new ConsoleOutput());
        });

        $this->app->alias(LoggerInterface::class, 'log');
    }
}

Add custom service provider for console writer

The console writer is rather generic which could or perhaps should be
in its own package. However, for the time being, I decided to give it
its own service provider and thereby make it a bit easier to migrate
the components into its own package in the future


<?php

declare(strict_types=1);

/*
 * +----------------------------------------------------------------------+
 * |                          ThinkSNS Plus                               |
 * +----------------------------------------------------------------------+
 * | Copyright (c) 2018 Chengdu ZhiYiChuangXiang Technology Co., Ltd.     |
 * +----------------------------------------------------------------------+
 * | This source file is subject to version 2.0 of the Apache license,    |
 * | that is bundled with this package in the file LICENSE, and is        |
 * | available through the world-wide-web at the following url:           |
 * | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 * +----------------------------------------------------------------------+
 * | Author: Slim Kit Group <master@zhiyicx.com>                          |
 * | Homepage: www.thinksns.com                                           |
 * +----------------------------------------------------------------------+
 */

namespace Zhiyi\Plus\Utils;

use Carbon\Carbon;

trait DateTimeToIso8601ZuluString
{
    /**
     * DateTime to ISO 8601 Zulu time.
     *
     * @param {\DateTime|string|null} $dateTime
     * @return string
     */
    protected function dateTimeToIso8601ZuluString($dateTime = null): ?string
    {
        if (is_null($dateTime) || empty($dateTime)) {
            return null;
        } elseif (!($dateTime instanceof Carbon)) {
            $dateTime = new Carbon($dateTime);
        }

        return $dateTime->toIso8601ZuluString();
    }
}

Add a DataTime to Zulu time format util

feat(core): Add a DataTime to Zulu time format util


<?php

class DatabaseUpdateCommandTest extends AcceptanceTestCase
{
    public function testExecute()
    {
        $output = $this->runConsole('db:update');
        $this->assertContains('success', $output);
    }
}

Create acceptance test for database update command


<?php
/*
 * Copyright (c)
 * Kirill chEbba Cheunin <iam@chebba.org>
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.
 */

namespace Che\LogStock\Adapter\Monolog;

/**
 * Monolog Processor for Logger name. It moves name to extra, which can be used in string templates
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
class NameProcessor
{
    /**
     * Move name from context to extra
     *
     * @param array $record
     *
     * @return array
     */
    public function __invoke(array $record)
    {
        if (!isset($record['context'][MonologAdapter::NAME_KEY])) {
            return $record;
        }

        $record['extra'][MonologAdapter::NAME_KEY] = $record['context'][MonologAdapter::NAME_KEY];
        unset($record['context'][MonologAdapter::NAME_KEY]);

        return $record;
    }
}

Add monolog processor for name parameter


<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>PWP for Jeffrey Cooper - Milestone 2</title>

		<link rel="stylesheet" href="styles-documentation.css" type="text/css" />

PWP for Jeffrey Cooper

Milestone 2

Content Strategy

Wireframes

Add Milestone 2 documentation file

Add Milestone 2 documentation file


<?php

$table = new ManiphestTransaction();
$conn_w = $table->establishConnection('w');

foreach (new LiskMigrationIterator($table) as $xaction) {
  $type = $xaction->getTransactionType();
  $id = $xaction->getID();

  // This is an old ManiphestTransaction::TYPE_COLUMN. It did not do anything
  // on its own and was hidden from the UI, so we're just going to remove it.
  if ($type == 'column') {
    queryfx(
      $conn_w,
      'DELETE FROM %T WHERE id = %d',
      $table->getTableName(),
      $id);
    continue;
  }

  // This is an old ManiphestTransaction::TYPE_PROJECT_COLUMN. It moved
  // tasks between board columns; we're going to replace it with a modern
  // PhabricatorTransactions::TYPE_COLUMNS transaction.
  if ($type == 'projectcolumn') {
    try {
      $new = $xaction->getNewValue();
      if (!$new || !is_array($new)) {
        continue;
      }

      $column_phids = idx($new, 'columnPHIDs');
      if (!is_array($column_phids) || !$column_phids) {
        continue;
      }

      $column_phid = head($column_phids);
      if (!$column_phid) {
        continue;
      }

      $board_phid = idx($new, 'projectPHID');
      if (!$board_phid) {
        continue;
      }

      $before_phid = idx($new, 'beforePHID');
      $after_phid = idx($new, 'afterPHID');

      $old = $xaction->getOldValue();
      if ($old && is_array($old)) {
        $from_phids = idx($old, 'columnPHIDs');
        $from_phids = array_values($from_phids);
      } else {
        $from_phids = array();
      }

      $replacement = array(
        'columnPHID' => $column_phid,
        'boardPHID' => $board_phid,
        'fromColumnPHIDs' => $from_phids,
      );

      if ($before_phid) {
        $replacement['beforePHID'] = $before_phid;
      } else if ($after_phid) {
        $replacement['afterPHID'] = $after_phid;
      }

      queryfx(
        $conn_w,
        'UPDATE %T SET transactionType = %s, oldValue = %s, newValue = %s
          WHERE id = %d',
        $table->getTableName(),
        PhabricatorTransactions::TYPE_COLUMNS,
        'null',
        phutil_json_encode(array($replacement)),
        $id);
    } catch (Exception $ex) {
      // If anything went awry, just move on.
    }
  }

}

Migrate old task transactions to use new display code

Summary: Ref T6027. This converts the old transaction records to the new format so we don't have to keep legacy code around.

Test Plan: Migrated tasks, browsed around, looked at transaction records, didn't see any issues.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T6027

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


<?php

use App\Configs;
use Illuminate\Database\Migrations\Migration;

class ApiKeySecurityLevel extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $config = Configs::where('key','api_key')->first();
        $config->confidentiality = 3;
        $config->save();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        /**
         * This is a not reversible change.
         * Anyway the key would be deleted with the next rollback: add_api_key
         */
    }
}

Fix security issue: API Key leaking on public config


<?php

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

class AddVnVnengineColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if(Schema::hasTable('vn')) {
            if(!Schema::hasColumn('vn', 'game_engine')) {
                Schema::table('vn', function(Blueprint $table) {
                    $table->string('game_engine')->nullable();
                });
            }
        }
    }

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

Prepare migration to insert VN Game Engine column


<?php
    require_once __DIR__ . "/class/autoload.php";

    use \html\Page as Page;
    use \html\CommunityMenu as CommunityMenu;
    use \configuration\Globals as Globals;

    Page::startHeader("Processo Seletivo 2015");
    Page::closeHeader();

    $menu = new CommunityMenu();
    $menu->construct();

?>

Processos Seletivos

  2015
  2016

<?php
Page::footer();
Page::closeBody();

?>

Create new page for selective process

Create new page for selective process


<?php

namespace CatLab\Assets\Laravel\PathGenerators;

use CatLab\Assets\Laravel\Models\Asset;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Class GroupedIdPathGenerator
 *
 * This path generator is similar to the GroupedIdPathGenerator:
 * - each asset gets their own folder
 * - all variations are stored in that specific folder
 *
 * However, on root level, a random 4-char prefix is added to
 * improve performance on s3.
 *
 * @package CatLab\Assets\Laravel
 */
class GroupedRandomPrefixPathGenerator extends PathGenerator
{
    /**
     * @param Asset $asset
     * @param UploadedFile $file
     * @return string
     */
    public function generatePath(Asset $asset, UploadedFile $file)
    {
        $assetPath = $this->getFolderFromId($asset->getRootAsset()->id);
        $extension = $file->getClientOriginalExtension();

        if ($asset->id === $asset->getRootAsset()->id) {
            $filename = str_random(8);
        } else {
            $filename = 'v' . $asset->variations->count() . '-' . str_random(8);
        }

        return $this->getUploadFolder() . '/' . $assetPath
            . '/' . $filename
            . '.' . $extension;
    }

    /**
     * This is not the code you're looking for.
     * @param int $id
     * @return string
     */
    public function getFolderFromId($id)
    {
        $path = [];

        // We take 4 characters from the hex encoded md5 hash.
        // We start at 7 for no reason at all.
        $hash = substr(md5($id), 7, 4);

        $path[] = $hash;

        // Second level path should simply be the asset id.
        $path[] = $id;

        return implode('/', $path);
    }
}

Add random prefix path generator (better performance on s3)


<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;
use Doctrine\ODM\MongoDB\UnitOfWork;

class GH878Test extends BaseTest
{
    public function testSPLObjectHashCollisionOnDoubleMerge()
    {
        $document = $this->getPersistedButDetachedDocument();

        // should be detached as coming from cache
        $state = $this->uow->getDocumentState($document);
        $this->assertEquals(UnitOfWork::STATE_DETACHED, $state);
        // clear to have again clear state
        $this->dm->clear();

        // merge + flush twice the same detached document
        $first = $this->dm->merge($document);
        $this->dm->flush();

        $state = $this->uow->getDocumentState($first);
        $this->assertEquals(UnitOfWork::STATE_MANAGED, $state);

        $second = $this->dm->merge($document);
        $this->dm->flush();

        $state = $this->uow->getDocumentState($second);
        $this->assertEquals(UnitOfWork::STATE_MANAGED, $state);

        $someOtherDocument = new GH878OtherDocument();

        $state = $this->uow->getDocumentState($someOtherDocument);
        $this->assertEquals(UnitOfWork::STATE_NEW, $state);
    }

    /**
     * @return GH878Document
     */
    private function getPersistedButDetachedDocument() {
        $document = new GH878Document();
        $document->embeddedField = new GH878SubDocument();

        $this->dm->persist($document);
        $this->dm->flush();
        // clear here to simulate a cache
        $this->dm->clear();

        return $document;
    }
}

/** @ODM\Document */
class GH878Document
{
    /** @ODM\Id */
    public $id;

    /** @ODM\EmbedOne(targetDocument="GH878SubDocument") */
    public $embeddedField;
}

/** @ODM\EmbeddedDocument */
class GH878SubDocument
{
    /** @ODM\String */
    public $some = '2';
}

/** @ODM\Document */
class GH878OtherDocument
{
    /** @ODM\Id */
    public $id;
}

Test to prove, that when calling merge twice on the same detached document a spl_object_hash collision occurs.


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

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

use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Flow\Log\PsrLoggerFactory;

/**
 * Adjust "Settings.yaml" to new PSR-3 logging settings (see https://github.com/neos/flow-development-collection/pull/1574)
 */
class Version20190515215000 extends AbstractMigration
{

    public function getIdentifier()
    {
        return 'Neos.Flow-20190515215000';
    }

    /**
     * @return void
     */
    public function up()
    {
        $this->processConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            function (array &$configuration) {
                $this->processLogSettings($configuration);
            },
            true
        );
    }

    /**
     * Adjust Neos.Flow.log.* syntax & nesting
     *
     * @param array $configuration
     * @return void
     */
    public function processLogSettings(array &$configuration): void
    {
        if (!isset($configuration['Neos']['Flow']['log']) || !is_array($configuration['Neos']['Flow']['log'])) {
            return;
        }
        $logConfiguration = &$configuration['Neos']['Flow']['log'];

        if (isset($logConfiguration['psr3']['loggerFactory']) && $logConfiguration['psr3']['loggerFactory'] === 'legacy') {
            $logConfiguration['psr3']['loggerFactory'] = PsrLoggerFactory::class;
        }
        foreach ($logConfiguration as $loggerName => $options) {
            if ($loggerName === 'psr3') {
                continue;
            }

            if (isset($options['logger'])) {
                unset($options['logger']);
            }
            if (isset($options['backend'])) {
                $options['class'] = $options['backend'];
                unset($options['backend']);
            }
            if (isset($options['backendOptions'])) {
                $options['options'] = $options['backendOptions'];
                unset($options['backendOptions']);
            }

            $logConfiguration['psr3'][PsrLoggerFactory::class][$loggerName]['default'] = $options;
            unset($logConfiguration[$loggerName]);

            $this->showNote(sprintf('Adjusted configuration of the "%s" logger settings.', $loggerName));
        }
    }
}

Add code migration for log settings

TASK: Add code migration for log settings


<?php

namespace OpenConext\EngineBlock\Doctrine\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20161209145942 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // Make sure consent_date is not updated every time a row is updated
        $this->addSql('ALTER TABLE consent CHANGE consent_date consent_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $this->addSql('ALTER TABLE consent CHANGE consent_date consent_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;');

    }
}

Make sure consent_date is not updated every time a row is updated

This sets consent_date only the first time, causing only usage_date to get updated every time someone gives or checks consent


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, 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\Utils\Templating;

/**
 * Templating provider
 */
interface TemplatingProviderInterface
{
    /**
     * @return \Symfony\Component\Templating\EngineInterface
     */
    public function getTemplating();
}

Move templating provider interface to utils lib.


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiAnalyticsService.php';
session_start();

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

// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  $props = $service->webproperties->listManagementWebproperties("~all");
  print "
Web Properties

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

  $accounts = $service->accounts->listManagementAccounts();
  print "
Accounts

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

$_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "Connect Me!";
}

Add a sample application for the Google Analytics V3 API.


<?php

require_once dirname(__FILE__) . '/config.php';

$InvoiceService = new QuickBooks_IPP_Service_Invoice();

$invoices = $InvoiceService->query($Context, $realm, "SELECT * FROM Invoice STARTPOSITION 1 MAXRESULTS 1");
$invoice = reset($invoices);
$id = substr($invoice->getId(), 2, -1);

header("Content-Disposition: attachment; filename='example_invoice.pdf'");
header("Content-type: application/x-pdf");
print $InvoiceService->pdf($Context, $realm, $id);

Add documentation for getting an invoice pdf


<?php

namespace Tests\Regis\Application\Reporter;

use Regis\Application\Model\Github\PullRequest;
use Regis\Application\Model\Github\ReviewComment;
use Regis\Application\Model\Violation;
use Regis\Application\Reporter\Github as GithubReporter;
use Regis\Github\Client as GithubClient;

class GithubTest extends \PHPUnit_Framework_TestCase
{
    /** @var GithubClient */
    private $client;

    /** @var GithubReporter */
    private $reporter;

    public function setUp()
    {
        $this->client = $this->createMock(GithubClient::class);

        $this->reporter = new GithubReporter($this->client);
    }

    public function testViolationsAreReportedAsReviewCOmments()
    {
        $violation = $this->createMock(Violation::class);
        $pullRequest = $this->createMock(PullRequest::class);

        $this->client->expects($this->once())
            ->method('sendComment')
            ->with($pullRequest, $this->callback(function ($subject) {
                return $subject instanceof ReviewComment;
            }));

        $this->reporter->report($violation, $pullRequest);
    }
}

Add tests for the github reporter

Add tests for the github reporter


<?php
/**
 * Plugin Name: Disable CSS animations
 * Description: Plugin for disabling CSS animations during E2E tests.
 */

function enqueue_disable_animations_stylesheet() {
	$custom_css = '* { animation-duration: 0ms !important; }';
	wp_add_inline_style( 'dashicons', $custom_css );
}
add_action( 'admin_enqueue_scripts', 'enqueue_disable_animations_stylesheet' );
add_action( 'login_enqueue_scripts', 'enqueue_disable_animations_stylesheet' );
add_action( 'wp_enqueue_scripts', 'enqueue_disable_animations_stylesheet' );

Disable CSS animations during E2E.

Disable CSS animations during E2E.


<?php

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

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('failed_jobs');
    }
}

Add a table for holding failed jobs.

Add a table for holding failed jobs.


<?php

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

class FixArtworkTypeIndexes extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        // Leftovers from 2018_02_20_165300_rename_object_type_to_artwork_type
        Schema::table('artwork_types', function (Blueprint $table) {

            $table->dropUnique('object_types_lake_guid_unique');
            $table->dropUnique('object_types_lake_uri_unique');

            $table->unique('lake_guid');
            $table->unique('lake_uri');

        });

    }

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

        Schema::table('artwork_types', function (Blueprint $table) {

            $table->dropUnique(['lake_guid']);
            $table->dropUnique(['lake_uri']);

            $table->unique('lake_guid', 'object_types_lake_guid_unique');
            $table->unique('lake_uri', 'object_types_lake_uri_unique');

        });

    }
}

Add migration to fix ArtworkType indexes


<?php
/*
Plugin Name: MAPP for WordPress
Plugin URI: http://github.com/lockergnome/mapp-wordpress
Description: Multi-Author Payment Plugin for WordPress
Version: 0.1-alpha1
Author: Eddie Ringle
Author URI: http://eddieringle.com
License: New BSD
*/
?>

Add initial plugin php file

Add initial plugin php file

Signed-off-by: Eddie Ringle <bacc1c505cb1756c59242c0a8ee25cd990a210e9@eringle.net>


<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * An encapsulation around the data from Webhook events. This allows us to
 * change the structure of the webhook request data without having to change it
 * throughout the code.
 */
class WC_Gateway_Komoju_Webhook_Event {

    private $requestJson;

    /**
	 * Constructor
	 * @param string $requestBody the body of the webhook request
	 */
    public function __construct($requestBody) {
        // TODO: Handle and log json decoding errors
        $this->requestJson = json_decode($requestBody, true);
    }

    /**
     * A getter to retrieve the event type from the webhook event
     */
    public function event_type() {
        return $this->requestJson['type'];
    }

    private function data() {
        return $this->requestJson['data'];
    }

    /**
     * A getter to retrieve the status of the webhook event
     */
    public function status() {
        return $this->data()['status'];
    }

    /**
     * A getter to retrieve the external_order_num from the webhook event
     */
    public function external_order_num() {
        return $this->data()['external_order_num'];
    }

    /**
     * A getter to retrieve the payment id from the webhook event
     */
    public function uuid() {
        return $this->data()['id'];
    }

    /**
     * A getter to retrieve the currency from the webhook event
     */
    public function currency() {
        return $this->data()['currency'];
    }

    /**
     * A getter to retrieve the total of the payment from the webhook event. This
     * is the price of the purchase + tax + payment_method_fee.
     */
    public function grand_total() {
        return $this->data()['total'];
    }

    /**
     * A getter to retrieve the payment method fee from the webhook event
     */
    public function payment_method_fee() {
        return $this->data()['payment_method_fee'];
    }

    /**
     * A getter to retrieve the additional information from the webhook event
     */
    public function additional_information() {
        // TODO: this field doesn't seem to exist directly on the response
        // in the example callback data I've got it looks like it has a 'brand'
        // param set to 'master', which is the same as the payment_details object
        return $this->data()['payment_details'];
    }

    /**
     * A getter to retrieve the tax from the webhook event
     */
    public function tax() {
        return $this->data()['tax'];
    }

    /**
     * A getter to retrieve the amount from the webhook event
     */
    public function amount() {
        return $this->data()['amount'];
    }
}

Add new PHP class to encapsulate the webhook data.

Since the callback_url process is deprecated we need to switch to
using webhooks instead. And to prevent future change to the webhooks
requiring changes throughout the system a new class is being added to
encapsulate the webhook events. This way future changes can be contained
to the new class and don't require the calling code to have to be
updated each time.


<?php

namespace JWX\JWT\Parameter;

use JWX\JWT\Claim\Claim;

/**
 * Parameter allowing claims to be inserted into header.
 *
 * @link https://tools.ietf.org/html/rfc7519#section-5.3
 */
class ReplicatedClaimParameter extends JWTParameter
{
	/**
	 * Constructor
	 *
	 * @param Claim $claim
	 */
	public function __construct(Claim $claim) {
		parent::__construct($claim->name(), $claim->value());
	}
}

Add support for replicated claims in header