<?php
/**
 * Tlumx Framework (https://framework.tlumx.xyz/)
 *
 * @author    Yaroslav Kharitonchuk <yarik.proger@gmail.com>
 * @link      https://github.com/tlumx/framework
 * @copyright Copyright (c) 2016-2017 Yaroslav Kharitonchuk
 * @license   https://framework.tlumx.xyz/license  (MIT License)
 */
namespace Tlumx\Test\Log;

use Psr\Log\Test\LoggerInterfaceTest;
use Tlumx\Log\Logger;

class LoggerTest extends LoggerInterfaceTest
{
    private $logHandler;

    public function getLogger()
    {
        $logger = new Logger();
        $this->logHandler = $logger;

        return $logger;
    }

    public function getLogs()
    {
        $logger = $this->logHandler;

        $messages = $logger->getLogMessages();

        $return = array();
        foreach ($messages as $message) {
            $return[] = $message[1] . ' ' . $message[3];
        }

        return $return;
    }
}

Add test fot PSR-3 Logger Class

Add test fot PSR-3 Logger Class


<?php

/**
 * SQLayerExampleDbo
 * Example of SQLayerDbo implemented as singleton
 *
 * @category   Frameworks
 * @package    SQLayer
 * @author     Roderic Linguri <rlinguri@mac.com>
 * @copyright  2016 Digices, Inc.
 * @license    https://opensource.org/licenses/MIT
 * @version    0.0.5
 * @link       http://www.sqlayer.com
 */

class SQLayerExampleDbo extends SQLayerDbo
{

    /** *obj* the database singleton object **/
    protected static $dbo;

    /** @method dbo getter
      * @param  void
      * @return *obj* of this class **/
    public static function dbo()
    {
        if (!isset(self::$dbo)) {
            self::$dbo = new self();
        }
        return self::$dbo;
    }

    /** @method constructor
      * @param  void
      * @return void **/
    public function __construct()
    {
        /** define where the database file is stored **/
        $this->dbDir = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR.'var'.DIRECTORY_SEPARATOR.'db';

        /** the base name of the file (no extension) **/
        $this->dbName = 'example';

        /** create the database connection **/
        parent::__construct();
    }

}

Create example of extended Dbo class.

Create example of extended Dbo class.


<?php

/**
 * Migration:   15
 * Started:     21/04/2021
 *
 * @package     Nails
 * @subpackage  module-auth
 * @category    Database Migration
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Database\Migration\Nails\ModuleAuth;

use Nails\Auth\Auth\PasswordEngine\Sha1;
use Nails\Common\Console\Migrate\Base;

class Migration15 extends Base
{
    /**
     * Execute the migration
     *
     * @return Void
     */
    public function execute()
    {
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}user_group` CHANGE `password_rules` `password_rules` JSON NULL;');
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}user_group` CHANGE `acl` `acl` JSON NULL;');
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}user` CHANGE `user_acl` `user_acl` JSON NULL;');
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}user_event` CHANGE `data` `data` JSON NULL;');
        $this->query('ALTER TABLE `{{NAILS_DB_PREFIX}}user_meta_admin` CHANGE `nav_state` `nav_state` JSON NULL;');
    }
}

Use JSON for json data types

Use JSON for json data types


<?php

namespace Ob\CampaignBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;

class SnapshotCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('campaign:generate:snapshots')
            ->setDescription('Generate snapshots for templates')
            ->addArgument('limit', InputArgument::OPTIONAL, 'How many images to process', 10)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $limit = $input->getArgument('limit');

        // In 2.4 these deps would be injected in the service definition
        $entityManager = $this->getContainer()->get('doctrine')->getManager();
        $snappy = $this->getContainer()->get('ob_campaign.snapshot');

        $templates = $this->getTemplates($entityManager, $limit);

        foreach ($templates as $template) {
            $output->writeln("Generating snapshot for template " . $template->getName());

            $html = $template->getCode();
            $imagePath = $snappy->render($html);

            $template->setSnapshot($imagePath);
        }

        $entityManager->flush();
    }

    // This should go in a repository class
    private function getTemplates($entityManager, $limit)
    {
        $templates = $entityManager->getRepository('ObCampaignBundle:Template')->findBy(
            array('snapshot' => null),
            null,
            $limit
        );

        return $templates;
    }
}

Create a command to generate snapshots

Create a command to generate snapshots


<?php
/**
 * Plugin Name: Restrict Content Pro - Prevent Payment Plan Cancellations
 * Description: Prevents customers from cancelling recurring memberships that have a payment plan.
 * Version: 1.0
 * Author: Sandhills Development, LLC
 * Author URI: https://sandhillsdev.com
 * License: GPL2
 */

/**
 * Prevents the "Cancel your membership" link from showing if the membership is a payment plan.
 *
 * @param bool           $can_cancel    Whether or not the membership can be cancelled.
 * @param int            $membership_id ID of the membership being checked.
 * @param RCP_Membership $membership    Membership object.
 *
 * @return bool
 * @throws Exception
 */
function ag_rcp_prevent_payment_plan_cancellations( $can_cancel, $membership_id, $membership ) {

	global $rcp_options;

	// Only do this on the Account Page
	if ( empty( $rcp_options['account_page'] ) || ! is_page( $rcp_options['account_page'] ) ) {
		return $can_cancel;
	}

	// Return early if other conditions aren't already met.
	if ( ! $can_cancel ) {
		return false;
	}

	if ( $membership->has_payment_plan() && ! $membership->is_payment_plan_complete() ) {
		$can_cancel = false;
	}

	return $can_cancel;

}
add_filter( 'rcp_membership_can_cancel', 'ag_rcp_prevent_payment_plan_cancellations', 100, 3 );

Add snippet preventing customers from cancelling payment plan memberships


<?php
namespace Mongolid\Tests\Integration;

use Mongolid\Tests\Integration\Stubs\ReferencedUser;

class AttributesKeyTest extends IntegrationTestCase
{
    public function testAttributesKeysShouldNotBeReserved()
    {
        $user = new ReferencedUser();
        $user->name = 'John';
        $user->email = 'john@doe.com';

        // attributes that used to be "reserved"
        $user->attributes = ['my', 'attributes'];
        $user->originalAttributes = ['my', 'original', 'attributes'];

        $this->assertSame('John', $user->name);
        $this->assertSame('john@doe.com', $user->email);
        $this->assertSame(['my', 'attributes'], $user->attributes);
        $this->assertSame(['my', 'original', 'attributes'], $user->originalAttributes);
        $this->assertSame(
            [
                'name' => 'John',
                'email' => 'john@doe.com',
                'attributes' => ['my', 'attributes'],
                'originalAttributes' => ['my', 'original', 'attributes'],
            ],
            $user->getDocumentAttributes()
        );
        $this->assertSame([], $user->getOriginalDocumentAttributes());
    }
}

Add a test for old reserved words

Add a test for old reserved words


<?php

namespace CultuurNet\UDB3;

class EntityNotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_has_the_HTTP_NOT_FOUND_status_code_by_default()
    {
        $exception = new EntityNotFoundException();

        $this->assertEquals(404, $exception->getCode());
    }
}

III-1092: Add a test for the EntityNotFoundException


<?php
	class Email
	{
		public static function Verify($Email)
		{
			return filter_var($Email, FILTER_VALIDATE_EMAIL) === $Email ? true : false;
		}

		const DEC = 1;
		const HEXA = 2;

		public static function Obfuscate($Email, $Mode = 1, $WithMailto = true)
		{
			if(static::Verify($Email))
			{
				if($Mode == static::DEC)
					$Format = '&#%d;';
				elseif($Mode == static::HEXA)
					$Format = '&#x%x;';
				else
					return false;

				$Code = $WithMailto ? 'mailto:' : null;

				$Length = strlen($Email);
				for($i = 0; $i < $Length; $i++)
					$Code .= sprintf($Format, ord($Email[$i]));

				return $Code;
			}

			return false;
		}
	}

Verify & Obfuscate functions added

Verify & Obfuscate functions added

Obfuscate function based on
https://gist.github.com/fermino/812f2731f9d92a2dfafe


<?php

namespace Mopa\Bundle\BootstrapBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class TabType extends AbstractType
{
    public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'compound' => true,
        ));
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['tab_active'] = false;
    }

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

<?php

namespace Mopa\Bundle\BootstrapBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class TabType extends AbstractType
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['tab_active'] = false;
    }

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

Remove default compound option. Not needed.


<?php
/*
 * CodeMOOC TreasureHuntBot
 * ===================
 * UWiClab, University of Urbino
 * ===================
 * Generates QR Code package for a given game.
 */

require_once(dirname(__FILE__) . '/game.php');
require_once(dirname(__FILE__) . '/lib.php');
require_once(dirname(__FILE__) . '/model/context.php');

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

if(!isset($argv[1])) {
    die("Usage: " . basename(__FILE__) . " <GAME ID>\n");
}
$game_id = intval($argv[1]);

$context = Context::create_for_game_admin($game_id);

echo "Impersonating game administrator " . $context->sender->get_full_name() . PHP_EOL;

$output = bot_creation_generate_codes($context);

echo "Generated QR Code pack at " . $output . PHP_EOL;

Add QR Code zip generation script

Add QR Code zip generation script


<?php
namespace Slackyboy\Plugins\Contributing;

use Slackyboy\Message;
use Slackyboy\Plugins\AbstractPlugin;

class Plugin extends AbstractPlugin
{
    public function enable()
    {
        // attach event handlers
        $this->bot->on('mention', function (Message $message) {
            if ($message->matchesAny('/how/i', '/(help|contribute)/i', '/(to\s+you)|(your\s+code)/i')) {
                $this->bot->say('http://github.com/coderstephen/slackyboy', $message->getChannel());
            }
        });
    }
}

Add plugin for telling people about contributing


<?php

	class Browsers {

		function getAll($version) {
			$results = array();

			$types = array('desktop', 'tablet', 'mobile', 'television', 'gaming');

			foreach($types AS $type) {
				$res = mysql_query("
					SELECT
						b.variant, IFNULL(b.version,'') AS version, b.nickname, b.details, b.listed
					FROM
						browserVersions AS b
						LEFT JOIN scores AS s ON (b.variant = s.variant AND (b.version = s.version OR (b.version IS NULL AND s.version IS NULL)))
						LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint)
					WHERE
						FIND_IN_SET('" . $type . "',b.type) AND
						s.release = '" . $version . "' AND
						f.points != ''
					ORDER BY
						b.variant, ISNULL(b.release), b.release, b.version
				");

				echo mysql_error();

				while ($row = mysql_fetch_object($res)) {
					$row->uid = $type . '-' . $row->variant . '-' . $row->version;
					$row->type = $type;
					$row->listed = $row->listed == '1';

					$results[] = $row;
				}
			}

			return $results;
		}

	}

<?php

	class Browsers {

		function getAll($version) {
			$results = array();

			$types = array('desktop', 'tablet', 'mobile', 'television', 'gaming');

			foreach($types AS $type) {
				$res = mysql_query("
					SELECT
						b.variant, IFNULL(b.version,'') AS version, b.nickname, b.details, b.listed, IFNULL(v.replaced,v.id) AS id, f.score
					FROM
						browserVariants AS v
						LEFT JOIN browserVersions AS b ON (v.id = b.variant)
						LEFT JOIN scores AS s ON (b.variant = s.variant AND (b.version = s.version OR (b.version IS NULL AND s.version IS NULL)))
						LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint)
					WHERE
						FIND_IN_SET('" . $type . "',b.type) AND
						s.release = '" . $version . "' AND
						f.points != ''
					ORDER BY
						b.variant, ISNULL(b.release), b.release, b.version
				");

				echo mysql_error();

				while ($row = mysql_fetch_object($res)) {
					$row->uid = $type . '-' . $row->variant . '-' . $row->version;
					$row->type = $type;
					$row->listed = $row->listed == '1';

					$results[] = $row;
				}
			}

			return $results;
		}

	}

Add extra information about the browser for use in the browser popup


<?php

namespace Asmaster\EquipTwig\Tests\Traits;

use Asmaster\EquipTwig\Traits\PayloadInterfaceRenderTrait;
use Equip\Adr\PayloadInterface;
use Equip\Payload;
use PHPUnit_Framework_TestCase as TestCase;

class PayloadInterfaceRenderTraitTest extends TestCase
{
    use PayloadInterfaceRenderTrait;

    protected function setUp()
    {
        $this->payload = new Payload;
    }

    public function testPayloadInterface()
    {
        $this->assertInstanceOf(PayloadInterface::class, $this->payload);
    }

    public function testPayloadInterfaceRender()
    {
        $template = 'test.html.twig';
        $output = [
            'body' => 'body'
        ];

        $payload = $this->render($template, $output);

        $this->assertEquals($output, $payload->getOutput());
    }
}

Add the test for PayloadInterfaceRenderTrait


<?php

namespace Tests\AppBundle\API\Mapping;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class FullByDbxrefIdTest extends WebserviceTestCase
{
    public function testByNcbiTaxonomy()
    {
        $service = $this->webservice->factory('mapping', 'fullByDbxrefId');
        $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db, 'db' => 'ncbi_taxonomy')), null);
        $this->assertEquals(181839, count($result));
        $this->assertEquals(29, $result['3070']);
        $this->assertEquals(748, $result['3880']);
        $this->assertEquals(3894, $result['38212']);
        $this->assertEquals(7983, $result['53750']);
    }

    public function testByEOL()
    {
        $service = $this->webservice->factory('mapping', 'fullByDbxrefId');
        $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db, 'db' => 'EOL')), null);
        $this->assertEquals(173027, count($result));
        $this->assertEquals(24571, $result['3812']);
        $this->assertEquals(148571, $result['994360']);
        $this->assertEquals(6664, $result['99084']);
        $this->assertEquals(18587, $result['93252']);
    }
}

Add unit test for fullByDbxrefId webservice


<?php

return [
    /**
     * User class used for ACL.
     */
    'user' => App\Models\User::class,

    /**
     * Role class used for ACL.
     */
    'role' => Yajra\Acl\Models\Role::class,

    /**
     * Permission class used for ACL.
     */
    'permission' => Yajra\Acl\Models\Permission::class,

    /**
     * Cache config.
     */
    'cache' => [
        'enabled' => true,

        'key' => 'permissions.policies',
    ],
];

Remove extra line on cache config

Remove extra line on cache config


<?php

return [
    // Register shortcode tag(s) to template mapping
    'shortcodes' => [
        'tags' => [
            'audio' => '_doxter/shortcode/audio',
            'img:image' => '_doxter/shortcodes/image',
            'vimeo:youtube' => '_doxter/shortcodes/video',
        ]
    ]
];

Update example to show shortcode tag registration


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

namespace ZendTest\Cache\Storage\Adapter;

use Zend\Cache;
use Zend\Cache\Storage\Adapter\Memory as MemoryStorage;
use Zend\Cache\Storage\Adapter\KeyListIterator;

/**
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage UnitTests
 * @group      Zend_Cache
 */
class KeyListIteratorTest extends \PHPUnit_Framework_TestCase
{

    public function testCount()
    {
        $keys = array('key1', 'key2', 'key3');
        $storage = $this->getMock('Zend\Cache\Storage\StorageInterface');
        $iterator = new KeyListIterator($storage, $keys);
        $this->assertEquals(3, $iterator->count());
    }
}

Test added for count() in KeyListIterator


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for filter Mimic library function.
 *
 * @since 0.1.0
 */
class CleanFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(array(1, 2, 3, 4), array(1, false, 0, 2, 3, 4, '')),
			array(array('something', 'else', 'hello'), array('something', 'else', false, 0, '', 'hello')),
		);
	}

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

Add clean function test suite.

Add clean function test suite.


<?php return

within('datastructures',
    describe('pair',
        it('can be compared for equality', function() { return
            expect(pair(a, b), toBeEqualTo(pair(a, b)));
        }),

        it('can be deconstructed using head', function() { return
            expect(head(pair(a, b)), toBe(a));
        }),

        it('can be deconstructed using tail', function() { return
            expect(tail(pair(a, b)), toBe(b));
        })
    ),

    describe('ispair',
        it('recognises a pair', function() { return
            expect(ispair(pair(a, b)), toBeTrue());
        }),

        it('does not accuse atoms of being a pair', function() { return
            expect(ispair(a), toBeFalse());
        })
    ),

    describe('list',
        it('starts with a list constructor', function() { return
            expect(l(), toBe(nil));
        }),

        it('has its element as head of the outer pair, as a singleton', function() { return
            expect(head(l(a)), toBe(a));
        }),

        it('has the list constructor as tail of the outer pair, as a singleton', function() { return
            expect(tail(l(a)), toBe(nil));
        }),

        it('has the second element as head of the first inner pair', function() { return
            expect(head(tail(l(a, b))), toBe(b));
        }),

        it('has the list constructor as tail of the innermost pair', function() { return
            expect(tail(tail(l(a, b))), toBe(nil));
        })
    ),

    describe('islist',
        it('recognises empty lists as lists', function() { return
            expect(islist(l()), toBeTrue());
        }),

        it('recognises non-empty lists as lists', function() { return
            expect(islist(l(a, b, c)), toBeTrue());
        }),

        it('does not accuse atoms of being a list', function() { return
            expect(islist(a), toBeFalse());
        }),

        it('does not recognise arrays as lists', function() { return
            expect(islist([a, b]), toBeFalse());
        })
    ),

    describe('al',
        it('returns an empty list when given an empty array', function() { return
            expect(al([]), toBeEqualTo(l()));
        }),

        it('returns a list, created from an array', function() { return
            expect(al([a, b, c]), toBeEqualTo(l(a, b, c)));
        })
    ),

    describe('la',
        it('returns an empty array when given an empty list', function() { return
            expect(la(l()), toBeEqualTo([]));
        }),

        it('returns an array, created from a list', function() { return
            expect(la(l(a, b, c)), toBeEqualTo([a, b, c]));
        })
    )
);

Add omikron tests for datastructures

Add omikron tests for datastructures


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

namespace ZendTest\Stdlib\Strategy;

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

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

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

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

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

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

Add unit tests for serializable strategy

Add unit tests for serializable strategy


<?php

namespace Zimbra\Mail\Tests;

use Zimbra\Mail\MailFactory;

/**
 * Testcase class for MailFactory.
 */
class MailFactoryTest extends ZimbraMailTestCase
{
    public function testMailFactory()
    {
        $httpApi = MailFactory::instance();
        $this->assertInstanceOf('\Zimbra\Mail\Base', $httpApi);
        $this->assertInstanceOf('\Zimbra\Mail\Http', $httpApi);
    }
}

Add testcase class for MailFactory.

Add testcase class for MailFactory.


<?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\Tests\Adapter\Monolog;

use Che\LogStock\Adapter\Monolog\MonologAdapter;
use Che\LogStock\Adapter\Monolog\NameProcessor;
use PHPUnit_Framework_TestCase as TestCase;

/**
 * NameProcessor test
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
class NameProcessorTest extends TestCase
{
    /**
     * @var NameProcessor
     */
    private $processor;

    protected function setUp()
    {
        $this->processor = new NameProcessor();
    }

    /**
     * @test __invoke move name parameter in record
     */
    public function moveNameParameter()
    {
        $record = array(
            'context' => array(MonologAdapter::NAME_KEY => 'name'),
            'extra' => array()
        );

        self::assertEquals(
            array(
                'context' => array(),
                'extra' => array(MonologAdapter::NAME_KEY => 'name')
            ),
            $this->processor->__invoke($record)
        );
    }

    /**
     * @test __invoke do nothing if context does not have name parameter
     */
    public function doNothingIfNoParameter()
    {
        $record = array(
            'context' => array(),
            'extra' => array()
        );

        self::assertEquals(
            array(
                'context' => array(),
                'extra' => array()
            ),
            $this->processor->__invoke($record)
        );
    }
}

Add test for monolog NameProcessor

Add test for monolog NameProcessor


<?php
/**
 * contentinum - accessibility websites
 *
 * LICENSE
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category contentinum components
 * @package Controller
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 * @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
 * @license http://www.opensource.org/licenses/bsd-license
 * @since contentinum version 5.0
 * @link      https://github.com/Mikel1961/contentinum-components
 * @version   1.0.0
 */
namespace Contentinum\Controller;

use Zend\Mvc\Controller\AbstractActionController;

/**
 * Contentinum Abstract Controller
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 *
 */
abstract class ContentinumAbstractController extends AbstractActionController
{
	/**
	 * Returns doctrine entity default manager
	 *
	 * @return EntityManager
	 */
	public function getDoctrineDefault()
	{
		return $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
	}
}

Add Contentinum Abstract Controller with serval standard methods

Change-Id: I696e1d5c4305c5d6ba8f3a7b945edcb7ebbb78da


<?php
/**
 * Created by IntelliJ IDEA.
 * User: rek
 * Date: 2017/11/17
 * Time: 上午12:41
 */

namespace x2ts\db\orm;

class ReferenceBatchLoader implements BatchLoader {

    private $name;

    private $prop;

    private $model;

    public function __construct(string $name, string $refProp, Model $refModel) {
        $this->name = $name;
        $this->prop = $refProp;
        $this->model = $refModel;
    }

    /**
     * @param Model[] $models
     * @param array   $subWiths
     *
     * @return void
     */
    public function batchLoadFor($models, $subWiths) {
        if (count($models) === 0) {
            return;
        }
        $ids = [];
        foreach ($models as $model) {
            $id = $model->properties[$this->prop];
            if (is_string($id)) {
                $ids[] = "'$id'";
            } else {
                $ids[] = $id;
            }
        }
        $idStr = implode(',', $ids);
        /** @var Model[] $foreignModels */
        $foreignModels = $this->model
            ->with(...$subWiths)
            ->many("`{$this->model->pkName}` IN ($idStr)");
        $map = [];
        foreach ($foreignModels as $foreignModel) {
            $map[$foreignModel->pk] = $foreignModel;
        }
        foreach ($models as $model) {
            $model->{$this->name} = $map[$model->properties[$this->prop]] ?? null;
        }
    }

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

Add a generic implementation of BatchLoader which loads foreign models by reference property.

 ReferenceBatchLoader works like the BelongToRelation, but not any of foreign keys is required.


<?php

class CM_FormField_ColorTest extends CMTest_TestCase {

    public function testValidate() {
        $field = new CM_FormField_Color(['name' => 'foo']);
        $environment = new CM_Frontend_Environment();

        $value = $field->validate($environment, '#00FF00');
        $this->assertSame('00FF00', $value->getHexString());
    }

    /**
     * @expectedException CM_Exception_FormFieldValidation
     */
    public function testValidateInvalid() {
        $field = new CM_FormField_Color(['name' => 'foo']);
        $environment = new CM_Frontend_Environment();

        $field->validate($environment, '#zzzzzzzzz');
    }

    public function testRender() {
        $field = new CM_FormField_Color(['name' => 'foo']);
        $field->setValue(CM_Color_RGB::fromHexString('00FF00'));

        $html = $this->_renderFormField($field);

        $this->assertSame('color', $html->find('input')->getAttribute('type'));
        $this->assertSame('#00FF00', $html->find('input')->getAttribute('value'));
    }

}

Add test for color formfield

Add test for color formfield


<?php

require_once __DIR__ . '/CommandTestCase.php';

class DiffTest extends CommandTestCase
{
    public function testDiff()
    {
        $this->runCommand('diff', array(
            'env1' => 'dev',
            'env2' => 'prod'
        ));

        $reader = $this->app['configuration'];
        $valueBar = $reader->read('bar');

        // Command must sumup displayed environments
        $this->assertDisplay("~dev~");
        $this->assertDisplay("~prod~");

        // A CLI table is displayed
        $this->assertDisplay("~|---~");

        // Bar has only a default clause => no differences between environments
        $this->assertNotDisplay("~$valueBar~");
    }
}

Add diff command unit test

Add diff command unit test


<?php

// Make this require relative to the parent of the current folder
// http://stackoverflow.com/questions/24753758

require_once dirname(__DIR__)."/tsugi/config.php";

Add the empty module folder

Add the empty module folder


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\CommandHandling;

use Broadway\Domain\Metadata;

interface ContextAwareInterface
{

    public function setContext(Metadata $context = null);
}

Add interface for components that will need to be contextual information aware, like commands, command busses, meta data enrichers.


<?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\Items\Attributes;

use Illuminate\Database\Eloquent\Model;

/**
 * This is the corporate model class.
 *
 * @property int $nif
 * @property string $name
 * @property string $address
 * @property string $postal_code
 * @property string $city
 * @property string $cae
 * @property string $activity
 * @property string $nature
 * @property float $capital
 * @property string $capital_currency
 * @property bool $is_active
 * @property string|null $email
 * @property int|null $phone
 * @property string|null $website
 * @property int|null $fax
 */
class Corporate extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'corporates';

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

    /**
     * Indicate if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['created_at', 'updated_at'];
}

Add the corporate model class

Add the corporate model class


<?php

namespace OpenDominion\Tests\Http\Auth;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Notification;
use OpenDominion\Notifications\User\ResetPasswordNotification;
use OpenDominion\Tests\AbstractBrowserKitTestCase;
use Password;

class ResetPasswordTest extends AbstractBrowserKitTestCase
{
    use DatabaseMigrations;

    public function testResetPasswordPage()
    {
        $this->visitRoute('auth.password.request')
            ->seeStatusCode(200);
    }

    public function testUserCanRequestPasswordReset()
    {
        $user = $this->createUser();

        $this->visitRoute('auth.password.request')
            ->see('Reset Password')
            ->type($user->email, 'email')
            ->press('Send Password Reset Link')
            ->see('If that email address exists in our system, we will send it a reset password email.')
            ->seeInDatabase('password_resets', [
                'email' => $user->email,
            ]);

        Notification::assertSentTo($user, ResetPasswordNotification::class);
    }

    public function testShowSameMessageIfEmailIsInvalid()
    {
        $this->visitRoute('auth.password.request')
            ->see('Reset Password')
            ->type('nonexistant@example.com', 'email')
            ->press('Send Password Reset Link')
            ->see('If that email address exists in our system, we will send it a reset password email.');

        Notification::assertNothingSent();
    }

    public function testUserCanResetPassword()
    {
        $user = $this->createUser();
        $token = Password::getRepository()->create($user);

        $this->visitroute('auth.password.reset', [$token])
            ->see('Reset Password')
            ->type($user->email, 'email')
            ->type('secret', 'password')
            ->type('secret', 'password_confirmation')
            ->press('Reset Password')
            ->seeRouteIs('home')
            ->see('Your password has been reset and you are now logged in.')
            ->seeIsAuthenticatedAs($user);
    }

    public function testUserCannotResetPasswordWithInvalidToken()
    {
        $user = $this->createUser();
        $token = Password::getRepository()->create($user);

        $this->visitroute('auth.password.reset', ['invalidtoken'])
            ->see('Reset Password')
            ->type($user->email, 'email')
            ->type('secret', 'password')
            ->type('secret', 'password_confirmation')
            ->press('Reset Password')
            ->seeRouteIs('auth.password.reset', ['invalidtoken'])
            ->see('This password reset token for that e-mail address is invalid.');
    }

    public function testUserCannotResetSomeoneElsesPassword()
    {
        $user1 = $this->createUser(null, ['email' => 'email1@example.com']);
        $user2 = $this->createUser(null, ['email' => 'email2@example.com']);
        $token = Password::getRepository()->create($user1);

        $this->visitroute('auth.password.reset', [$token])
            ->see('Reset Password')
            ->type('email2@example.com', 'email')
            ->type('secret', 'password')
            ->type('secret', 'password_confirmation')
            ->press('Reset Password')
            ->seeRouteIs('auth.password.reset', [$token])
            ->see('This password reset token for that e-mail address is invalid.');
    }
}

Add tests for password reset

Add tests for password reset


<?php
namespace Neblion\ScrumBundle\Listener;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class RequestListener
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        $locale = $event->getRequest()->getPreferredLanguage(array('en', 'fr'));
        $event->getRequest()->setLocale($locale);
    }
}

Create simple request listener for setting Locale based on browser preferred language


<?php

/**
 * Plugin Name: WP REST API
 * Description: JSON-based REST API for WordPress, developed as part of GSoC 2013.
 * Version: 1.2.0
 * Author: wonderfan
 * Author URI: http://www.wonderfan.net
 * Plugin URI: https://github.com/wonderfan/
 */

Use this as boil-template to create wp plugin


<?php
/**
 * Displays on the invoice how much of the payment was for VAT. This assumes you've bundled
 * the VAT into the cost of the subscription level. This will calculate your chosen
 * VAT percentage (20% by default) from the full cost of the subscription level and
 * display the amount of money on the invoice right above the total amount.
 *
 * @param object $rcp_payment Payment object from the database.
 *
 * @return void
 */
function ag_rcp_display_vat_on_invoice( $rcp_payment ) {
	// Don't show VAT if payment is free.
	if ( empty( $rcp_payment->amount ) ) {
		return;
	}

	$vat_percentage = 20; // This is 20% VAT by default. Adjust number here to change VAT percentage.
	?>

		<?php printf( __( '%d%% VAT' ), $vat_percentage ); ?>

			<?php
			$vat = round( $rcp_payment->amount * ( $vat_percentage / 100 ), 2 );
			echo rcp_currency_filter( $vat );
			?>

	<?php
}

add_action( 'rcp_invoice_items_before_total_price', 'ag_rcp_display_vat_on_invoice' );

Add snippet for showing VAT percentage on invoices.


<?php namespace Aedart\Scaffold\Contracts\Templates\Data;

/**
 * Template Value Type
 *
 * Various supported template "value" types. Depending upon
 * what type is specified, different action must be performed
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Contracts\Templates
 */
interface ValueType
{

    /**
     * Default - the user is not prompted
     * for any value.
     */
    const VALUE = 10;

    /**
     * Should prompt the user for a value,
     * via a question.
     */
    const QUESTION = 20;

    /**
     * Should prompt the user with a
     * multiple choice question
     */
    const CHOICE = 30;

    /**
     * Should prompt the user for a value,
     * via a question, where the input is
     * hidden
     */
    const HIDDEN = 40;

    /**
     * Ask user for confirmation
     */
    const CONFIRM = 50;
}

Add template data value types

Add template data value types

Defines a series of supported value types, each of which is supposed
to invoke different behaviour when the build command must read and
process them.


<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Security;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

class AuthorizationCheckerTest extends TestCase
{
    /**
     * @var AuthorizationCheckerInterface|MockObject
     */
    private $authorizationChecker;

    /**
     * @var AuthorizationChecker
     */
    private $decorator;

    public function setUp()
    {
        $this->authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $this->decorator = new AuthorizationChecker($this->authorizationChecker);
    }

    public function testIsGrantedEmptyAttributes()
    {
        $this->assertTrue($this->decorator->isGranted([]));
    }

    public function testIsGrantedScalarAttribute()
    {
        $attributes = 'ROLE_ADMIN';
        $subject = new \stdClass();
        $this->authorizationChecker
            ->expects($this->once())
            ->method('isGranted')
            ->with($attributes, $subject)
            ->willReturn(true);

        $result = $this->decorator->isGranted($attributes, $subject);

        $this->assertTrue($result);
    }

    public function testIsGrantedSecondAttributeGranted()
    {
        $attributes = ['ROLE_ADMIN', 'ROLE_MANAGER'];
        $subject = new \stdClass();
        $this->authorizationChecker
            ->expects($this->exactly(2))
            ->method('isGranted')
            ->withConsecutive(['ROLE_ADMIN', $subject], ['ROLE_MANAGER', $subject])
            ->willReturnOnConsecutiveCalls(false, true);

        $result = $this->decorator->isGranted($attributes, $subject);

        $this->assertTrue($result);
    }

    public function testIsGrantedNoAttributeGranted()
    {
        $attributes = ['ROLE_ADMIN', 'ROLE_MANAGER'];
        $subject = new \stdClass();
        $this->authorizationChecker
            ->expects($this->exactly(2))
            ->method('isGranted')
            ->withConsecutive(['ROLE_ADMIN', $subject], ['ROLE_MANAGER', $subject])
            ->willReturnOnConsecutiveCalls(false, false);

        $result = $this->decorator->isGranted($attributes, $subject);

        $this->assertFalse($result);
    }

    public function testIsGrantedWillCatchAuthenticationCredentialsNotFoundException()
    {
        $attributes = 'ROLE_ADMIN';
        $this->authorizationChecker
            ->expects($this->once())
            ->method('isGranted')
            ->with($attributes, null)
            ->willThrowException(new AuthenticationCredentialsNotFoundException());

        $result = $this->decorator->isGranted($attributes);

        $this->assertTrue($result);
    }
}

Add unit tests for Authorization checker


<?php

namespace Croogo\Core\Listener;

use Cake\Event\Event;
use Crud\Listener\BaseListener;

class ChooserListener extends BaseListener
{
    public function beforeFilter(Event $event)
    {
        if (!$this->_controller()->request->query('chooser')) {
            return;
        }

        $this->_controller()->viewBuilder()->layout('Croogo/Core.admin_popup');
    }
}

Add listener for chooser pages

Add listener for chooser pages


<?php

namespace FD\PrivateMessageBundle\Tests\Event;

use FD\PrivateMessageBundle\Entity\Conversation;
use FD\PrivateMessageBundle\Event\ConversationEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Class ConversationEventTest.
 */
class ConversationEventTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test ConversationEvent object.
     */
    public function testConversationEvent()
    {
        $conversation = new Conversation();
        /** @var Request $request */
        $request = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock();
        /** @var UserInterface $user */
        $user = $this->getMockBuilder(UserInterface::class)->getMock();

        $event = new ConversationEvent($conversation, $request, $user);

        $this->assertSame($conversation, $event->getConversation());
        $this->assertSame($request, $event->getRequest());
        $this->assertSame($user, $event->getUser());
    }
}

Add unit test for ConversationEvent

Add unit test for ConversationEvent


<!DOCTYPE html>

    <meta charset="utf-8">
    <title>@yield('title', 'Good Gateway Football')</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    @yield('meta')

    {!! HTML::style('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css') !!}
    {!! HTML::style('//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.min.css') !!}

    {!! HTML::script('//cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js') !!}

        @yield('content')

{!! HTML::script('//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js') !!}
{!! HTML::script('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js') !!}

Add simple master layout for backend app


<?php get_header(); ?>

<?php while (have_posts()): the_post(); ?>

            <?php the_title(); ?>

            <?php the_content(); ?>

            <?php the_date(); ?>

<?php endwhile; ?>

<?php get_footer(); ?>

<?php get_header(); ?>

<?php while (have_posts()): the_post(); ?>

        <a href="<?php the_permalink(); ?>">

                <?php the_title(); ?>

            <?php the_content(); ?>

            <?php the_date(); ?>

<?php endwhile; ?>

<?php get_footer(); ?>

Add permalink to post titles

Add permalink to post titles


<?php
/**
 * This file is part of the bee4/transport package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2015
 * @author  Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Transport
 */

namespace Bee4\Transport;

/**
 * A client builder
 * @package Bee4\Transport
 */
class ClientFactory
{
	protected function __construct() {
		//Just a factory helper, can't be instantiated
	}

	/**
	 * Create a new client instance
	 * @param  string $url The root URL used by the client
	 * @return ClientInterface The generated instance
	 */
	public static function create($url = '') {
		$instance = new Client($url);
		return new MagicHandler($instance);
	}
}

Add a factory to build client

Add a factory to build client

Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>


<?php
/*
 * This file is part of the Harmony package.
 *
 * (c) Tim Goudriaan <tim@harmony-project.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Harmony\Component\ModularRouting\Provider;

use Harmony\Component\ModularRouting\Model\ModuleInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\RouteCollection;

/**
 * ProviderInterface
 *
 * Returns RouteCollection objects for Module instances.
 *
 * @author Tim Goudriaan <tim@harmony-project.io>
 */
interface ProviderInterface
{
    /**
     * Returns the route collection associated with a module
     *
     * @param ModuleInterface|int $module Module object or id
     *
     * @return RouteCollection
     * @throws RouteNotFoundException If the module doesn't exist
     */
    public function getRouteCollectionByModule($module);

    /**
     * Returns the route collection associated with a request
     *
     * Required parameters:
     *
     *   * _modular_segment: Segment of path to use to match the request against
     *                       a module.
     *
     * @param Request $request    The request
     * @param array   $parameters Parameters returned by an UrlMatcher
     *
     * @return RouteCollection
     */
    public function getRouteCollectionForRequest(Request $request, array $parameters = []);
}

Create an interface for Provider objects


<?php

namespace Risan\OAuth1\Request;

interface RequestConfigInterface
{
    /**
     * Get the request HTTP method.
     *
     * @return string
     */
    public function getMethod();

    /**
     * Get the request URI.
     *
     * @return string
     */
    public function getUri();

    /**
     * Get the request options.
     *
     * @return array
     */
    public function getOptions();
}

Add new interface for RequestConfig.

:sparkles: Add new interface for RequestConfig.


<?php

/*

Plugin Name: Castlegate IT WP Tweak Tool
Plugin URI: https://github.com/castlegateit/cgit-wp-tweak-tool
Description: Tweaks various parts of the WordPress dashboard.
Version: 2.2.1
Author: Castlegate IT
Author URI: https://www.castlegateit.co.uk/
License: MIT

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_TWEAK_TOOL_PLUGIN', __FILE__);

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

$plugin = new \Cgit\TweakTool\Plugin();

do_action('cgit_tweak_tool_plugin', $plugin);
do_action('cgit_tweak_tool_loaded');

<?php

/*

Plugin Name: Castlegate IT WP Tweak Tool
Plugin URI: https://github.com/castlegateit/cgit-wp-tweak-tool
Description: Tweaks various parts of the WordPress dashboard.
Version: 2.2.1
Author: Castlegate IT
Author URI: https://www.castlegateit.co.uk/
License: AGPL

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_TWEAK_TOOL_PLUGIN', __FILE__);

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

$plugin = new \Cgit\TweakTool\Plugin();

do_action('cgit_tweak_tool_plugin', $plugin);
do_action('cgit_tweak_tool_loaded');

Switch license from MIT to AGPL in plugin file


<?php

require_once "functions.php";

class Af_AmazingSuperPowers extends Plugin {

    function about() {
        return array(0.1, "Fetch larger image from Amazing SuperPowers webcomic", "Markus Wiik");

    }
    function init($host) {
        $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
    }

    function hook_article_filter($article) {
        $owner_uid = $article["owner_uid"];
        if (strpos($article["link"], "amazingsuperpowers.com") !== FALSE) {
            $article["content"] = preg_replace("/comics-rss/", "comics", $article['content']);
            $doc = new DOMDocument();
            @$doc->loadHTML($article['content']);
            $xpath = new DOMXPath($doc);
            $img = $xpath->query('(//img)')->item(0);
            $article['content'] = $doc->saveHTML($img);
        }
        return $article;
    }
}
?>

Add plugin for Amazing SuperPowers webcomic


<?php
namespace NamelessCoder\TYPO3RepositoryClient\Tests\Unit;

/**
 * Class SoapDataCompilerTest
 */
class SoapDataCompilerTest extends \PHPUnit_Framework_TestCase {

	/**
	 * @param string $username
	 * @param string $password
	 * @param array $data
	 * @param array $expectation
	 * @dataProvider getCreateSoapDataTestValues
	 */
	public function testCreateSoapData($username, $password, $data, $expectation) {

	}

	/**
	 * @return array
	 */
	public function getCreateSoapDataTestValues() {
		return array(
			array(
				'user',
				'pass',
				array('foo' => 'bar'),
				array('foo' => 'bar', 'accountData' => array('username' => 'user', 'password' => 'pass'))
			),
			array(
				'user',
				'pass',
				array('foo' => 'bar', 'accountData' => array('username' => 'user2', 'password' => 'pass2')),
				array('foo' => 'bar', 'accountData' => array('username' => 'user2', 'password' => 'pass2'))
			),
		);
	}

}

Add test case for SoapDataCompiler

[TASK] Add test case for SoapDataCompiler


/* require the user as the parameter */
if(isset($_GET['player']) && intval($_GET['player'])) {

	/* soak in the passed variable or set our own */
	$score = isset($_GET['score']) ? intval($_GET['score']) : 10; //10 is the default
	$player_id = intval($_GET['user']); //no default
	$time = intval($_GET['time']);
	$bus = strval($_GET['bus']);

	/* connect to the db */
	$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
	mysql_select_db('db_name',$link) or die('Cannot select the DB');

	/* grab the posts from the db */
	$query = "INSERT Score (player, time, score, bus) VALUES ($player_id,$time,$score,$bus)";
	$result = mysql_query($query,$link) or die('Errant query:  '.$query);

	if($result){
 		// successfully insert
        $response["success"] = 1;
        $response["message"] = "Score successfully recorded.";

        // echoing JSON response
        echo json_encode($response);
     } else {
     	// insert failed.
     	$response["success"] = 0;
     	$response["message"] = "Score failed to record!"
     }

	/* disconnect from the db */
	@mysql_close($link);
}

Add php script for score insertions.

Add php script for score insertions.


<?php //var_dump($rooms); ?>

								#
								Room No.
								Purpose
								Reservation Date
								Time Start
								Time End
								Date Reserved
								Reserved by
								Date Approved
								Approved by

							<?php $counter = 1; ?>
							<?php foreach($rooms as $row): ?>

									<?php echo $counter ?>
									<?php echo $row->room_no ?>
									<?php echo $row->purpose ?>
									<?php echo $row->date_reserved ?>
									<?php echo $row->time_start ?>
									<?php echo $row->time_end ?>
									<?php echo $row->date_reserved ?>
									<?php echo $row->fullname ?>
									<?php echo $row->approved_datetime ?>
									<?php echo $row->approver ?>

								<?php $counter++; ?>
							<?php endforeach; ?>

Create view for approved request

Create view for approved request


<?php

namespace App\Http\Controllers;

use DB;
use App\Member;
use Illuminate\Http\Request;

class MembersController extends Controller
{
    public function index()
    {
        $members = Member::all();

        return view('members.index', compact('members'));
    }

    public function show(Member $member)
    {
        return view('members.show', compact('member'));
    }
}

Add controller with show and index

Add controller with show and index


<?php

namespace Embark\CMS\Configuration;

use Embark\CMS\Metadata\MetadataInterface;
use Embark\CMS\Metadata\MetadataTrait;

class Admin implements MetadataInterface
{
    use MetadataTrait;

    public function __construct()
    {
        $this->setSchema([

        ]);
    }
}

<?php

namespace Embark\CMS\Configuration;

use Embark\CMS\Metadata\MetadataInterface;
use Embark\CMS\Metadata\MetadataTrait;
use Embark\CMS\Metadata\Filters\Boolean;

class Admin implements MetadataInterface
{
    use MetadataTrait;

    public function __construct()
    {
        $this->setSchema([
        	'minify-assets' => [
        		'filter' =>		new Boolean(),
        		'required' =>	true
        	]
        ]);
    }
}

Make sure sure admin css minification can be turned off.


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

namespace PH7\Test\Unit\Framework\Security;

use PH7\Framework\Security\Security;

class SecurityTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \PH7\Framework\Error\CException\PH7InvalidArgumentException
     */
    public function testUserHashWithInvalidAlgorithm()
    {
        Security::userHash('my nice string', 40, 'wrongAlgo');
    }

    public function testUserHashWithWhirlpoolAlgorithm()
    {
        $sActualHash = Security::userHash('my nice string', 48, Security::WHIRLPOOL_ALGORITHM);
        $this->assertEquals('33b041b1faf2fcf6515509bdc207fd8fe6e9d2bf182f609d', $sActualHash);
    }

    public function testUserHashWithSha512Algorithm()
    {
        $sActualHash = Security::userHash('my lovely string', 30, Security::SHA512_ALGORITHM);
        $this->assertEquals('bcd841a3456ccf8a6381b58a7aab75', $sActualHash);
    }

    public function testHash()
    {
        $sActualHash = Security::hash('blablabla ...');
        $sExpectedHash = '19fe127eb53178ab6b0c576bcfe90d41225443c6064139e6a058b4b0a4eb040ef912a89dd97c3fb6';
        $this->assertEquals($sExpectedHash, $sActualHash);
    }
 }

Add unit tests for Security class

Add unit tests for Security class


<?php declare(strict_types=1);

namespace Onion\Framework\Event;

use Onion\Framework\Event\Interfaces\ManagerInterface;

trait ManagerAware
{
    private $eventManager;

    public function getEventManager(): ManagerInterface
    {
        if (!$this->eventManager) {
            throw new \BadMethodCallException('No instance of event manager has been set.');
        }

        return $this->eventManager;
    }

    public function setEventManager(ManagerInterface $manager)
    {
        $this->eventManager = $manager;
    }
}

Add event manager aware trait

Add event manager aware trait


<?php
/**
 * MiniAsset
 * Copyright (c) Mark Story (http://mark-story.com)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Mark Story (http://mark-story.com)
 * @since         1.1.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace MiniAsset\Test\TestCase;

use MiniAsset\AssetTarget;

class AssetTargetTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->target = new AssetTarget(APP . 'example.js');
    }

    public function testOutputDir()
    {
        $this->assertSame(rtrim(APP, DIRECTORY_SEPARATOR), $this->target->outputDir());
    }

    public function testExt()
    {
        $this->assertSame('js', $this->target->ext());
    }

    public function testName()
    {
        $this->assertSame('example.js', $this->target->name());
    }

    public function testModifiedTimeNotExisting()
    {
        $this->assertSame(0, $this->target->modifiedTime());
    }

    public function testModifiedTimeExisting()
    {
        $target = new AssetTarget(__FILE__);
        $this->assertSame(filemtime(__FILE__), $target->modifiedTime());
    }
}

Add additional coverage for AssetTarget.

Add test coverage for AssetTarget. It is a simple/easy class to test, so
there is no reason to not have tests.


<?php
namespace TYPO3\Flow\Tests\Unit\Persistence\Doctrine\DataTypes;

/*
* This file is part of the TYPO3.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.
*/

/**
 * Testcase for \TYPO3\Flow\Persistence\Doctrine\DataTypes\JsonArrayType
 *
*/
class JsonArrayTypeTest extends \TYPO3\Flow\Tests\UnitTestCase
{
    /**
     * @var \TYPO3\Flow\Persistence\Doctrine\DataTypes\JsonArrayType|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $jsonArrayTypeMock;

    /**
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $abstractPlatformMock;

    /**
     * @return void
     */
    public function setUp()
    {
        $this->jsonArrayTypeMock = $this->getMockBuilder('TYPO3\Flow\Persistence\Doctrine\DataTypes\JsonArrayType')
            ->setMethods(['initializeDependencies'])
            ->disableOriginalConstructor()
            ->getMock();

        $this->abstractPlatformMock = $this->getMockBuilder('Doctrine\DBAL\Platforms\AbstractPlatform')->getMock();
    }

    /**
     * @test
     */
    public function jsonConversionReturnsNullIfArrayIsNull()
    {
        $json = $this->jsonArrayTypeMock->convertToDatabaseValue(null, $this->abstractPlatformMock);
        $this->assertEquals(null, $json);
    }

    /**
     * @test
     */
    public function passSimpleArrayAndConvertToJson()
    {
        $json = $this->jsonArrayTypeMock->convertToDatabaseValue(['simplestring',1,['nestedArray']], $this->abstractPlatformMock);
        $this->assertEquals("{\n    \"0\": \"simplestring\",\n    \"1\": 1,\n    \"2\": {\n        \"0\": \"nestedArray\"\n    }\n}", $json);
    }
}

TASK: Add small unit test for ``JsonArrayType``


<?php

namespace Knplabs\Snappy;

class MediaTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @dataProvider dataForBuildCommand
	 */
	public function testBuildCommand($binary, $url, $path, $options)
	{
		$media = $this->getMockForAbstractClass('Knplabs\Snappy\Media');
		$media
			->expects($this->any())
			->method('isExecAllowed')
			->will($this->returnValue(true))
		;

		$r = new \ReflectionMethod($media, 'buildCommand');
		$r->setAccessible(true);

		$this->assertEquals($expected, $r->invokeArgs($media, array($binary, $url, $path, $options)));
	}

	public function dataForBuildCommand()
	{
		return array(
			array(
				'thebinary',
				'http://the.url/',
				'/the/path',
				array(),
				'thebinary http://the.url/ /the/path'
			),
			array(
				'thebinary',
				'http://the.url/',
				'/the/path',
				array(
					'foo'	=> null,
					'bar'	=> false,
					'baz'	=> array()
				),
				'thebinary http://the.url/ /the/path'
			),
			array(
				'thebinary',
				'http://the.url/',
				'/the/path',
				array(
					'foo'	=> 'foovalue',
					'bar'	=> array('barvalue1', 'barvalue2'),
					'baz'	=> true
				),
				'thebinary http://the.url/ /the/path --foo=foovalue --bar=barvalue1 --bar=barvalue2 --baz'
			),
		);
	}
}

Add some tests for the Media class

Add some tests for the Media class


<?php
require_once "PHPUnit/Framework/IncompleteTestError.php";
require_once dirname(dirname(__FILE__)) . "/src/Ginq.php";

class GinqPluginTest extends PHPUnit_Framework_TestCase {
    /**
     * Runs the test methods of this class.
     *
     * @access public
     * @static
     */
    public static function main()
    {
        require_once "PHPUnit/TextUI/TestRunner.php";
        $suite  = new PHPUnit_Framework_TestSuite("GinqPluginTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function testResiterPlugin() {
    	SamplePlugin::register();

    	$sum = 0;
    	Ginq::range(1, 10)
    		->foreach(function ($v) {
    			$sum += $v;
    		})
   		;

   		$this->assertEquals(55, $sum);
    }
}

class SamplePlugin {
	public static function register() {

	}
}

Add a test to register plugin.

Add a test to register plugin.


Add template mtgox API config file.

Add template mtgox API config file.


<?php

namespace Vela\App\Controllers;

use \Sabre\HTTP\Request;
use \Sabre\HTTP\Response;
use \Purl\Url;

/**
 * Homepage Controller
 */
class Homepage
{
    /** @var object $response **/
    private $response;
    /** @var object $response **/
    private $request;
    /** @var object $response **/
    private $url;

    public function __construct(Response $response, Request $request, Url $url)
    {
        $this->response = $response;
        $this->request  = $request;
        $this->url      = $url;
    }

    public function show()
    {
        $this->response->setBody('
Hello World
');
        \Sabre\HTTP\Sapi::sendResponse($this->response);
    }
}

Move controller to app directory

Move controller to app directory


<?php

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

namespace ActiveCollab\Bootstrap\TestCase;

use ActiveCollab\Bootstrap\Command\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * @package ActiveCollab\Id\Test\Base
 */
abstract class CommandTestCase extends ModelTestCase
{
    /**
     * @var Application
     */
    private $application;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        parent::setUp();

        $this->application = new Application();
    }

    /**
     * @param  string        $command_class
     * @return CommandTester
     */
    protected function getCommandTesterFor($command_class)
    {
        /** @var Command $command */
        $command = new $command_class();
        $command->setContainer($this->getContainer());

        $this->application->add($command);

        return new CommandTester($this->application->find($command->getName()));
    }

    /**
     * @param  string        $command_class
     * @param  string        $command
     * @param  array         $command_arguments
     * @return CommandTester
     */
    protected function executeCommand($command_class, $command, array $command_arguments = [])
    {
        $command_tester = $this->getCommandTesterFor($command_class);
        $command_tester->execute(array_merge(['command' => $command], $command_arguments));

        return $command_tester;
    }
}

Add model command test case

Add model command test case


<?php

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

class AddCountryAcronymToScoresHigh extends Migration
{
    const TABLES = [
        'osu_scores_high',
        'osu_scores_taiko_high',
        'osu_scores_fruits_high',
        'osu_scores_mania_high',
    ];

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        foreach (static::TABLES as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->char('country_acronym', 2)->default('');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        foreach (static::TABLES as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->dropColumn('country_acronym');
            });
        }
    }
}

Add missing migration adding country acronym column


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\NotificationBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;

class CleanupCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this->setName('sonata:notification:cleanup');
        $this->setDescription('Clean up backend message');
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return void
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->write('<info>Starting ... </info>');

        $this->getContainer()->get('sonata.notification.backend')->cleanup();

        $output->writeln("done!");
    }
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\NotificationBundle\Command;

use Sonata\NotificationBundle\Backend\QueueDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;

class CleanupCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this->setName('sonata:notification:cleanup');
        $this->setDescription('Clean up backend message');
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return void
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->write('<info>Starting ... </info>');

        $this->getBackend()->cleanup();

        $output->writeln("done!");
    }

    /**
     * @return \Sonata\NotificationBundle\Backend\BackendInterface
     */
    private function getBackend()
    {
        $backend = $this->getContainer()->get('sonata.notification.backend');

        if ($backend instanceof QueueDispatcherInterface) {
            return $backend->getBackend(null);
        }

        return $backend;
    }
}

Fix cleanup command backend error

Fix cleanup command backend error


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

namespace Darvin\ImageBundle\Form\Type;

use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Image edit form type
 */
class EditType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {

    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'csrf_token_id' => md5(__FILE__.__METHOD__.$this->getBlockPrefix()),
            'data_class'    => AbstractImage::class,
        ]);
    }

    /**
     * {@inheritDoc}
     */
    public function getBlockPrefix(): string
    {
        return 'darvin_image_edit';
    }
}

Implement dummy edit form type.

Implement dummy edit form type.


<?php
/**
 * This file is part of Railgun package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);

namespace Serafim\Railgun\Reflection\Common;

use Hoa\Compiler\Llk\TreeNode;
use Serafim\Railgun\Compiler\Dictionary;
use Serafim\Railgun\Compiler\Exceptions\CompilerException;
use Serafim\Railgun\Reflection\Abstraction\ArgumentInterface;

/**
 * Trait HasArguments
 * @package Serafim\Railgun\Reflection\Common
 */
trait HasArguments
{
    /**
     * @param TreeNode $ast
     * @param Dictionary $dictionary
     */
    protected function compileHasArguments(TreeNode $ast, Dictionary $dictionary): void
    {
        $allowed = in_array($ast->getId(), $this->astHasArguments ?? ['#Argument'], true);

        if ($allowed) {
            throw new CompilerException('TODO: Add arguments compilation for ' . get_class($this));
        }
    }

    /**
     * @return iterable|ArgumentInterface[]
     */
    public function getArguments(): iterable
    {
        throw new \LogicException(__METHOD__ . ' not implemented yet');
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasArgument(string $name): bool
    {
        throw new \LogicException(__METHOD__ . ' not implemented yet');
    }

    /**
     * @param string $name
     * @return null|ArgumentInterface
     */
    public function getArgument(string $name): ?ArgumentInterface
    {
        throw new \LogicException(__METHOD__ . ' not implemented yet');
    }
}

Add arguments parser helper trait

Add arguments parser helper trait


<?php

namespace Silktide\LazyBoy\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * RestControllerTrait
 */
trait RestControllerTrait
{

    private $prohibitedKeys = [
        "password" => true,
        "salt" => true
    ];

    protected function success($data = null, $code = 200)
    {
        if ($data === null) {
            $data = ["success" => true];
        } elseif (is_array($data)) {
            $data = $this->filterProhibitedKeys($data);
        }
        return new JsonResponse($data, $code);
    }

    protected function error($message, $data = [], $code = 400)
    {
        $payload = [
            "success" => false,
            "error" => $message
        ];
        if (!empty($data)) {
            $payload["context"] = $this->filterProhibitedKeys($data);
        }
        return new JsonResponse($payload, $code);
    }

    private function filterProhibitedKeys($data)
    {
        foreach ($data as $key => $value) {
            if (isset($this->prohibitedKeys[$key])) {
                unset ($data[$key]);
            } elseif (is_array($value)) {
                $data[$key] = $this->filterProhibitedKeys($value);
            }
        }
        return $data;
    }

}

Add a trait for common functions used by rest controllers


<?php

use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Filesystem\Filesystem;

class MediaControllerTest extends TestCase
{
	use WithoutMiddleware;

	protected $uploadedFile;

	public function test_media_can_be_added()
	{
		$filePath = resource_path('assets/support/images/valid-image-file.jpg');
		$sha1 = sha1_file($filePath);

		$upload = new UploadedFile(
			$filePath,
			'valid-image-file.jpg',
			'image/jpeg',
			filesize($filePath),
			null,
			true
		);

		$response = $this->postJson('api/media', [
			'upload' => $upload
		]);

		$response->assertStatus(200);

		$response->assertJsonStructure([
			'data' => [
				'id',
				'name',
				'sha1',
				'size',
				'format',
				'mime_type',
				'width',
				'height',
				'aspect_ratio',
				'duration'
			]
		]);

		$this->assertDatabaseHas('media', [
			'sha1' => $sha1
		]);

		$responseData = $response->json();

		$this->uploadedFile = storage_path(
			'app/public/uploads/' . $responseData['data']['id'] . '/valid-image-file.jpg'
		);

		$this->assertFileExists($this->uploadedFile);
	}

	/**
	 * Clean up the testing environment before the next test.
	 *
	 * @return void
	 */
	protected function tearDown()
	{
		(new FileSystem())->delete($this->uploadedFile);
		unset($this->uploadedFile);

		parent::tearDown();
	}
}

Add media upload feature test.

Add media upload feature test.


<?php

use Karma\Configuration\InMemoryReader;

class InMemoryReaderTest extends PHPUnit_Framework_TestCase
{
    private
        $reader;

    protected function setUp()
    {
        $this->reader = new InMemoryReader(array(
            'foo:dev' => 'foodev',
            'foo:prod' => 'fooprod',
            'bar:dev' => 'bardev',
            'baz:recette' => 'bazrecette',
        ));
    }

    /**
     * @dataProvider providerTestRead
     */
    public function testRead($variable, $environment, $expected)
    {
        $this->assertSame($expected, $this->reader->read($variable, $environment));
    }

    /**
     * @dataProvider providerTestRead
     */
    public function testReadWithDefaultEnvironment($variable, $environment, $expected)
    {
        $this->reader->setDefaultEnvironment($environment);
        $this->assertSame($expected, $this->reader->read($variable));
    }

    public function providerTestRead()
    {
        return array(
            array('baz', 'recette', 'bazrecette'),
            array('bar', 'dev', 'bardev'),
            array('foo', 'prod', 'fooprod'),
            array('foo', 'dev', 'foodev'),
            array('donotexist', 'dev', null),
        );
    }
}

Add unit tests for InMemoryReader

Add unit tests for InMemoryReader


<?php

namespace Marein\Nchan\Api\Model;

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

class ChannelInformationTest extends TestCase
{
    /**
     * @test
     */
    public function itShouldBeCreatedWithItsValues(): void
    {
        $channelInformation = new ChannelInformation(
            10,
            1,
            100,
            '1504818382:1'
        );

        $this->assertSame(10, $channelInformation->numberOfMessages());
        $this->assertSame(1, $channelInformation->secondsUntilLastRequested());
        $this->assertSame(100, $channelInformation->numberOfCurrentSubscribers());
        $this->assertSame('1504818382:1', $channelInformation->lastMessageIdentifier());
    }

    /**
     * @test
     */
    public function itShouldBeCreatedFromValidJson(): void
    {
        $json = $this->validJson();

        $channelInformation = ChannelInformation::fromJson($json);

        $this->assertSame(10, $channelInformation->numberOfMessages());
        $this->assertSame(1, $channelInformation->secondsUntilLastRequested());
        $this->assertSame(100, $channelInformation->numberOfCurrentSubscribers());
        $this->assertSame('1504818382:1', $channelInformation->lastMessageIdentifier());
    }

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

        $json = 'malformed json"}';

        ChannelInformation::fromJson($json);
    }

    /**
     * @test
     * @dataProvider missingKeysProvider
     */
    public function itShouldBeThrowAnExceptionWhenJsonHasMissingKeys($json): void
    {
        $this->expectException(NchanException::class);

        ChannelInformation::fromJson($json);
    }

    /**
     * Returns various json with missing keys.
     *
     * @return array
     */
    public function missingKeysProvider(): array
    {
        return [
            ['{"requested": 1, "subscribers": 100, "last_message_id": "1504818382:1"}'],
            ['{"messages": 10, "subscribers": 100, "last_message_id": "1504818382:1"}'],
            ['{"messages": 10, "requested": 1, "last_message_id": "1504818382:1"}'],
            ['{"messages": 10, "requested": 1, "subscribers": 100}']
        ];
    }

    /**
     * Returns a valid json for tests.
     *
     * @return string
     */
    private function validJson(): string
    {
        return '{"messages": 10, "requested": 1, "subscribers": 100, "last_message_id": "1504818382:1"}';
    }
}

Add unit test for ChannelInformation

Add unit test for ChannelInformation


<?php namespace Alfredoem\Ragnarok\Api\v1;

use Alfredoem\Ragnarok\Utilities\Make;
use Illuminate\Support\Facades\Auth;
use Alfredoem\Ragnarok\SecUsers\SecUserSessions;
use Alfredoem\Ragnarok\AuthRagnarok;
use Alfredoem\Ragnarok\RagnarokResponse;
use Illuminate\Support\Facades\Session;

class RagnarokApi
{
    protected $success = false;
    protected $userRagnarok;
    protected $responseRagnarok;

    public function __construct(AuthRagnarok $userRagnarok, RagnarokResponse $responseRagnarok)
    {
        $this->responseRagnarok = $responseRagnarok;
        $this->userRagnarok = $userRagnarok;
    }

    /**
     * @param $data
     * @return \Alfredoem\Ragnarok\RagnarokResponse
     */

    public function login($data)
    {
        if( ! key_exists('remember', $data)) {
            $data['remember'] = false;
        }

        // login attempt
        if (Auth::once(['email' => $data['email'], 'password' => $data['password']], $data['remember'])) {

            $auth = Auth::user();

            // Store session user
            $session = SecUserSessions::create(['userId' => $auth->userId, 'sessionCode' => Make::uniqueString(),
                'ipAddress' => $data['ipAddress'], 'status' => 1, 'dateIns' => date('Y-m-d'),
                'datetimeIns' => date('Y-m-d H:m:s')]);

            $auth->ipAddress = $data['ipAddress'];
            $auth->sessionCode = $session->sessionCode;
            $auth->userSessionId = $session->userSessionId;
            $auth->environment = Session::get('environment');

            // Make ragnarok user
            $this->userRagnarok ->make($auth);

            $this->success = true;
        }

        return $this->responseRagnarok->make($this->success, $this->userRagnarok);
    }
}

Rename folder api to Api

Rename folder api to Api


<?php

namespace Voronkovich\SberbankAcquiring;

/**
 * Helper class with currencies codes (ISO 4217).
 *
 * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
 * @see https://en.wikipedia.org/wiki/ISO_4217
 */
class Currency
{
    const EUR = 978;
    const RUB = 643;
    const UAH = 980;
    const USD = 840;
}

Add helper class with currencies codes

Add helper class with currencies codes


<?php

namespace Risan\OAuth1\Request;

use Risan\OAuth1\Credentials\TemporaryCredentials;
use Risan\OAuth1\Credentials\ServerIssuedCredentials;

interface ProtocolParameterInterface
{
    /**
     * Get the ConfigInterface instance.
     *
     * @return \Risan\OAuth1\Config\ConfigInterface
     */
    public function getConfig();

    /**
     * Get the SignerInterface instance.
     *
     * @return \Risan\OAuth1\Signature\SignerInterface
     */
    public function getSigner();

    /**
     * Get the NonceGeneratorInterface instance.
     *
     * @return \Risan\OAuth1\Request\NonceGeneratorInterface
     */
    public function getNonceGenerator();

    /**
     * Get the current timestamp in seconds since Unix Epoch.
     *
     * @return int
     */
    public function getCurrentTimestamp();

    /**
     * Get the OAuth1 protocol version.
     *
     * @return string
     */
    public function getVersion();

    /**
     * Get the base protocol parameters.
     *
     * @return array
     */
    public function getBase();

    /**
     * Create the signature.
     *
     * @param  array $protocolParameters
     * @param  string uri
     * @param  \Risan\OAuth1\Credentials\ServerIssuedCredentials|null $serverIssuedCredentials
     * @param  array $requestOptions
     * @param  string httpMethod
     * @return string
     */
    public function getSignature(array $protocolParameters, $uri, ServerIssuedCredentials $serverIssuedCredentials = null, array $requestOptions = [], $httpMethod = 'POST');

    /**
     * Get protocol parameters for obtaining temporary credentials.
     *
     * @return array
     */
    public function forTemporaryCredentials();

    /**
     * Get protocol parameters for obtaining token credentials.
     *
     * @param  \Risan\OAuth1\Credentials\TemporaryCredentials $temporaryCredentials
     * @param  string               $verificationCode
     * @return array
     */
    public function forTokenCredentials(TemporaryCredentials $temporaryCredentials, $verificationCode);
}

:sparkles: Add new interface for ProtocolParameter.


<?php

namespace Application\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20121126184553 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

        $this->addSql("CREATE TABLE content_press_edition (id INT NOT NULL, title VARCHAR(255) NOT NULL, slug VARCHAR(255) NOT NULL, PRIMARY KEY(id))");
        $this->addSql("ALTER TABLE content_press_archive ADD edition_id INT DEFAULT NULL");
        $this->addSql("ALTER TABLE content_press_archive ADD CONSTRAINT FK_176E9B0574281A5E FOREIGN KEY (edition_id) REFERENCES content_press_edition (id) NOT DEFERRABLE INITIALLY IMMEDIATE");
        $this->addSql("CREATE INDEX IDX_176E9B0574281A5E ON content_press_archive (edition_id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

        $this->addSql("ALTER TABLE content_press_archive DROP CONSTRAINT FK_176E9B0574281A5E");
        $this->addSql("DROP TABLE content_press_edition");
        $this->addSql("ALTER TABLE content_press_archive DROP edition_id");
    }
}

Add migration for paper arhives

Add migration for paper arhives


<?php
namespace Jivoo\Http;

use Jivoo\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class SapiServerTest extends TestCase
{

    public function testListen()
    {
        $server = $this->getMock('Jivoo\Http\SapiServer', ['serve']);

        $response1 = new Message\Response(200);
        $response2 = new Message\Response(200);
        $response3 = new Message\Response(200);

        // Middleware 1
        $server->add(function ($request, $response, $next) use ($response1, $response2) {
            $this->assertSame($response2, $response);
            return $response1;
        });

        // Middleware 2
        $server->add(function ($request, $response, $next) use ($response2, $response3) {
            $this->assertSame($response3, $response);
            return $next($request, $response2); // Calls middleware 1
        });

        // Middleware 3
        $server->add(function ($request, $response, $next) use ($response3) {
            return $next($request, $response3); // Calls middleware 2
        });

        $server->expects($this->once())
            ->method('serve')
            ->with($this->equalTo($response1));

        $server->listen();
    }
}

Add test for SAPI server.

Add test for SAPI server.


<?php
$this->pageTitle=Yii::app()->name . ' - Error';
$this->breadcrumbs=array(
	'Error',
);
?>

Error <?php echo $code; ?>

	<?php echo CHtml::encode($message); ?>

Add missing view to the demo

Add missing view to the demo


<?php

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

class AddPaymentData extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('payment');
      $table
        ->addColumn('data', 'blob', [
                      'limit' => MysqlAdapter::BLOB_MEDIUM,
                      'null' => true,
                    ])
        ->save();
    }
}

Add data field to payment table

Add data field to payment table


<?php

namespace Isotop\Tests\Cargo\Admin;

use Closure;
use Isotop\Cargo\Cargo;

class User_Test extends \WP_UnitTestCase {

	public function test_push_login() {
		$user_id = 0;
		$cargo   = Cargo::instance();
		$fn      = Closure::fromCallable( '\\Isotop\\Cargo\\Admin\\push_login' )->bindTo( $cargo );

		$this->assertFalse( $fn( $user_id, null ) );

		$user_id = $this->factory->user->create( ['role' => 'administrator'] );

		$this->assertFalse( $fn( $user_id, null ) );

		add_filter( 'pre_http_request', function () {
			return ['body' => '{"success":true}'];
		} );

		$this->assertTrue( $fn( $user_id, get_user_by( 'ID', $user_id ) ) );
	}
}

Add tests for push login

Add tests for push login


<?php
namespace CouchDB\Tests\Encoder;

use CouchDB\Tests\TestCase;
use CouchDB\Encoder\NativeEncoder;
use CouchDB\Exception\JsonDecodeException;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class NativeEncoderTest extends TestCase
{
    protected function setUp()
    {
        $this->encoder = new NativeEncoder();
    }

    /**
     * @dataProvider getEncodeData
     */
    public function testEncode($value, $expected)
    {
        $this->assertEquals($expected, $this->encoder->encode($value));
    }

    /**
     * @dataProvider getDecodeData
     */
    public function testDecode($json, $expected)
    {
        $this->assertEquals($expected, $this->encoder->decode($json));
    }

    public function testInvalidDecode()
    {
        try {
            $this->encoder->decode('[invalid}');
            $this->fail('Syntax error');
        } catch (JsonDecodeException $e) {
            $this->assertEquals('Json decode error [Syntax error]: [invalid}', $e->getMessage());
        }
    }

    static public function getEncodeData()
    {
        return array(
            array('foo', '"foo"'),
            array(1, '1'),
            array(1.1, '1.1'),
            array(array('foo', 'bar'), '["foo","bar"]'),
            array(array('foo' => 'bar'), '{"foo":"bar"}'),
        );
    }
    static public function getDecodeData()
    {
        return array(
            array('"foo"', 'foo'),
            array('1', 1),
            array('1.1', 1.1),
            array('["foo", "bar"]', array('foo', 'bar')),
            array('{"foo":"bar"}', array('foo' => 'bar')),
        );
    }

}

Add unit test for NativeEncoder

Add unit test for NativeEncoder


<?php
/**
 * @package Neolao\Behavior
 */
namespace Neolao\Behavior;

/**
 * Objects that implement this interface are serializable to json format
 */
interface SerializableJson
{
    /**
     * Serialize to a json
     *
     * @return  string                  The serialized json
     */
    public function serializeJson();

    /**
     * Unserialize from a json
     *
     * @param   string      $json       The json
     */
    public function unserializeJson($json);
}

Add a behavior to serialize (and unserialize) to a json format


<?php

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

namespace Sylius\Component\Core\Model;

use Sylius\Component\User\Model\UserInterface as BaseUserInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface AdminUserInterface extends BaseUserInterface
{
    const DEFAULT_ADMIN_ROLE = 'ROLE_ADMINISTRATION_ACCESS';

    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @param string $firstName
     */
    public function setFirstName($firstName);

    /**
     * @return string
     */
    public function getLastName();

    /**
     * @param string $lastName
     */
    public function setLastName($lastName);

    /**
     * @return string
     */
    public function getLocaleCode();

    /**
     * @param string $code
     */
    public function setLocaleCode($code);
}

<?php

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

namespace Sylius\Component\Core\Model;

use Sylius\Component\User\Model\UserInterface as BaseUserInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface AdminUserInterface extends BaseUserInterface
{
    const DEFAULT_ADMIN_ROLE = 'ROLE_ADMINISTRATION_ACCESS';

    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @param string $firstName
     */
    public function setFirstName($firstName);

    /**
     * @return string
     */
    public function getLastName();

    /**
     * @param string $lastName
     */
    public function setLastName($lastName);

    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @param string $firstName
     */
    public function setFirstName($firstName);

    /**
     * @return string
     */
    public function getLastName();

    /**
     * @param string $lastName
     */
    public function setLastName($lastName);

    /**
     * @return string
     */
    public function getLocaleCode();

    /**
     * @param string $code
     */
    public function setLocaleCode($code);
}

[Admin] Tweak the admin users UI and naming conventions


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3;

use Broadway\Repository\AggregateNotFoundException;
use Broadway\Repository\RepositoryInterface;
use CultuurNet\UDB3\Event\ReadModel\DocumentRepositoryInterface;

class LocalEventServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var LocalEventService
     */
    protected $eventService;

    /**
     * @var DocumentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $documentRepository;

    /**
     * @var RepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $eventRepository;

    public function setUp()
    {
        $this->documentRepository = $this->getMock('\\CultuurNet\\UDB3\\Event\\ReadModel\\DocumentRepositoryInterface');
        $this->eventRepository = $this->getMock('Broadway\\Repository\\RepositoryInterface');
        $this->eventService = new LocalEventService(
            $this->documentRepository,
            $this->eventRepository
        );
    }
    /**
     * @test
     */
    public function it_throws_an_EventNotFoundException_when_aggregate_is_not_found_in_event_repository()
    {
        $id = 'some-unknown-id';

        $this->eventRepository->expects($this->once())
            ->method('load')
            ->with($id)
            ->willThrowException(new AggregateNotFoundException());

        $this->setExpectedException('\\CultuurNet\\UDB3\\EventNotFoundException', 'Event with id: ' . $id . ' not found');

        $this->eventService->getEvent($id);

    }
}

iii-89: Add test for LocalEventService exception handling


<?php

namespace Ivory\GoogleMapBundle\Model\Overlays;

/**
 * Each class implements this interface can be extend by a bound
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
interface IExtendable
{

}

Add Iextendable class which describes a class that can be extended by a bound


<?php
declare(strict_types=1);

namespace Apha\EventStore;

final class EventDescriptor
{
    /**
     * @var string
     */
    private $identity;

    /**
     * @var string
     */
    private $event;

    /**
     * @var string
     */
    private $payload;

    /**
     * @var string
     */
    private $recorded;

    /**
     * @var int
     */
    private $playHead;

    /**
     * @param string $identity
     * @param string $event
     * @param string $payload
     * @param int $playHead
     * @return EventDescriptor
     */
    public static function record(string $identity, string $event, string $payload, int $playHead) : self
    {
        return new self(
            $identity,
            $event,
            $payload,
            date('r'),
            $playHead
        );
    }

    /**
     * @param array $data
     * @return EventDescriptor
     */
    public static function reconstructFromArray(array $data) : self
    {
        return new self(
            $data['identity'],
            $data['event'],
            $data['payload'],
            $data['recorded'],
            $data['playHead']
        );
    }

    /**
     * @param string $identity
     * @param string $event
     * @param string $payload
     * @param string $recorded
     * @param int $playHead
     */
    private function __construct(string $identity, string $event, string $payload, string $recorded, int $playHead)
    {
        $this->identity = $identity;
        $this->event = $event;
        $this->payload = $payload;
        $this->recorded = $recorded;
        $this->playHead = $playHead;
    }

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

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

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

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

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            'identity' => $this->identity,
            'event' => $this->event,
            'payload' => $this->payload,
            'playHead' => $this->playHead,
            'recorded' => $this->recorded
        ];
    }
}

Create event descriptor for storage.

Create event descriptor for storage.


<?php

/*
 * This file is part of the GitCommandBundle package.
 *
 * (c) Paul Schweppe <paulschweppe@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace VersionControl\GitCommandBundle\GitCommands\Exception;

/**
 * InvalidArgumentException.
 *
 * @author Paul Schweppe <paulschweppe@gmail.com>
 */
class InvalidDirectoryException extends \Exception implements ExceptionInterface
{
}

Create Exception for invalid directory

Create Exception for invalid directory


<?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Groups with the most posts section
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Widget
 * @package   Laconica
 * @author    Evan Prodromou <evan@controlyourself.ca>
 * @copyright 2009 Control Yourself, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://laconi.ca/
 */

if (!defined('LACONICA')) {
    exit(1);
}

/**
 * Groups with the most posts section
 *
 * @category Widget
 * @package  Laconica
 * @author   Evan Prodromou <evan@controlyourself.ca>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://laconi.ca/
 */

class GroupsByPostsSection extends GroupSection
{
    function getGroups()
    {
        $qry = 'SELECT user_group.*, count(*) as value ' .
          'FROM user_group JOIN group_inbox '.
          'ON user_group.id = group_inbox.group_id ' .
          'GROUP BY user_group.id ' .
          'ORDER BY value DESC ';

        $limit = GROUPS_PER_SECTION;
        $offset = 0;

        if (common_config('db','type') == 'pgsql') {
            $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        } else {
            $qry .= ' LIMIT ' . $offset . ', ' . $limit;
        }

        $group = Memcached_DataObject::cachedQuery('User_group',
                                                   $qry,
                                                   3600);
        return $group;
    }

    function title()
    {
        return _('Groups with most posts');
    }

    function divId()
    {
        return 'top_groups_by_post';
    }
}

Add a section to show popular groups (by posts)


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

require_once '../../src/apiClient.php';
session_start();

$client = new apiClient();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');

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

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

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
  $val = $client->getIo()->authenticatedRequest($req);

  // The contacts api only returns XML responses.
  $response = json_encode(simplexml_load_string($val->getResponseBody()));
  print "
" . print_r(json_decode($response, true), true) . "
";

  // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $auth = $client->createAuthUrl();
}

if (isset($auth)) {
    print "Connect Me!";
  } else {
    print "Logout";
}

Add an (unsupported) sample application for the Google Contacts API.