<?php
namespace Mapbender\DigitizerBundle\Utils;

/**
 * Class System
 *
 * @package Mapbender\DigitizerBundle\Utils
 * @author  Andriy Oblivantsev <eslider@gmail.com>
 */
class System
{

    /**
     * Generate password
     *
     * Modes:
     * - "PWD_CHARS_SMALL" Small chars only
     * - "PWD_CHARS_BIG"   Big chars only
     * - "PWD_CHARS_MIXED" Big and small chars
     * - "PWD_NUMBERS"     Numbers only (PINS)
     * - "PWD_MIXED_SMALL" Small chars and numbers.
     * - "PWD_MIXED_BIG"   Big chars and numbers.
     *  -"PWD_MIXED_MIXED" Number, small and big and chars.
     *
     * @param int    $len  Length.
     * @param string $mode Mode. Default: "PWD_MIXED_MIXED"
     * @return string
     */
    public static function generatePassword($len = 6, $mode = "PWD_MIXED_MIXED")
    {
        $sChars = range('a', 'z');
        $bChars = range('A', 'Z');
        $number = range('0', '9');
        $pwd    = "";
        $lib    = null;

        switch ($mode) {
            case "PWD_CHARS_SMALL":
                $lib = $sChars;
                break;
            case "PWD_CHARS_BIG":
                $lib = $bChars;
                break;
            case "PWD_CHARS_MIXED":
                $lib = array_merge($sChars, $bChars);
                break;
            case "PWD_NUMBERS":
                $lib = $number;
                break;

            case "PWD_MIXED_SMALL":
                $lib = array_merge($number, $sChars);
                break;
                break;
            case "PWD_MIXED_BIG":
                array_merge($number, $bChars);
                break;
            default:
                $lib = array_merge($number, $bChars, $sChars);
        }

        for ($i = 0, $c = count($lib); $i < $len; $i++) {
            srand((float)microtime(true) * 1000000);
            $pwd .= $lib[mt_rand(0, $c - 1)];
        }
        return $pwd;
    }
}

Add system utility (password generator)

Add system utility (password generator)


<?php

/**
 *  Drupal 7 - Field API snippets
 *
 *  Sources :
 *  http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way
 *  http://stackoverflow.com/questions/11694770/print-drupal-field-view-field-value-only
 */

//--------------------------------------------
//  Getting items

//  Get item(s) - Term entity ex.
$term = taxonomy_term_load($tid);
$field_images_items = field_get_items('taxonomy_term', $term, 'field_images');
$field_sub_title_item = @reset(field_get_items('taxonomy_term', $term, 'field_sub_title'));

//  Get item(s) - Node entity ex.
$node = menu_get_object();
$field_images_items = field_get_items('node', $node, 'field_images');
$field_sub_title_item = @reset(field_get_items('node', $node, 'field_sub_title'));

//  Get item(s) - User entity ex.
$field_name_item = @reset(field_get_items('user', $account, 'field_name'));

//--------------------------------------------
//  Getting values
//  NB: the key may vary

//  Example with 'value' :
$field_description_item = @reset(field_get_items('node', $node, 'field_description'));
$description = $field_description_item['value'];

//--------------------------------------------
//  Rendering

//  Render a single field value
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

//  Using drupal_render()
//  $field will be an array with the following keys : #theme, #weight, #title, #access, #label_display, #view_mode, #language, #field_name, #field_type, #field_translatable, #entity_type, #bundle, #object, #items, #formatter, 0
//  where #items will have the values
//  ex: $field['#items'][0]['whatever_field_data']
//  Note : http://stackoverflow.com/questions/11694770/print-drupal-field-view-field-value-only
//  field_view_value() takes a $display argument that you can use to hide the label:
$display = array('label' => 'hidden');
$view = field_view_field('node', $node, 'field_description', $display);
print drupal_render($view);

//  The column name ($first_item['whatever']) will depend on the type of field you're using. For text fields it will be value. Remember to sanitise the input with check_plain() before you output it as Drupal's convention is to store the raw input data and sanitise it upon output.

//  Get sanitised rendered field in the current language in render-array form
$field = field_view_field('node', $node, 'field_name');

Add Drupal 7 Field API snippets

Add Drupal 7 Field API snippets


<?php

$template->assign('PageTopic','Space Merchant Realms Chat Room Rules');

$autoChannels = '#SMR';
if($player->hasAlliance()) {
	$allianceChan = $player->getAlliance()->getIrcChannel();
	if($allianceChan != '') {
		$autoChannels .= ',' . urlencode($allianceChan);
	}
}
$template->assign('AutoChannels', $autoChannels);
?>

<?php

$template->assign('PageTopic','Space Merchant Realms Chat Room Rules');

$autoChannels = '#SMR';
if($player->hasAlliance()) {
	$allianceChan = $player->getAlliance()->getIrcChannel();
	if($allianceChan != '') {
		$autoChannels .= ',' . $allianceChan;
	}
}
$template->assign('AutoChannels', $autoChannels);
?>

Remove the urlencode, it was breaking things.


<?php
/**
 * Plugin Name: E2E Tests Proxy Auth Plugin
 * Plugin URI:  https://github.com/google/site-kit-wp
 * Description: Utility plugin for bypassing set up and authentication during E2E tests.
 * Author:      Google
 * Author URI:  https://opensource.google.com
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

use Google\Site_Kit\Core\Authentication\Clients\OAuth_Client;
use Google\Site_Kit\Core\Storage\Data_Encryption;
use Google\Site_Kit\Plugin;

/**
 * Load proxy credentials.
 */
require_once __DIR__ . '/proxy-credentials.php';

/**
 * Provide a dummy access token to fake an authenticated state.
 */
add_filter(
	'get_user_option_googlesitekit_access_token',
	function () {
		return ( new Data_Encryption() )->encrypt(
			serialize( array( 'access_token' => 'test-access-token' ) ) // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
		);
	}
);

/**
 * Fake all required scopes have been granted.
 */
add_filter(
	'get_user_option_googlesitekit_auth_scopes',
	function () {
		return ( new OAuth_Client( Plugin::instance()->context() ) )->get_required_scopes();
	}
);

Add E2E proxy auth utility plugin.

Add E2E proxy auth utility plugin.


<?php
namespace OC\Migrations;

use OCP\Migration\ISimpleMigration;
use OCP\Migration\IOutput;

/**
 * Split the shareapi_only_share_with_group_member key to distinguish users and groups.
 * The behaviour will be similar as well as the values, so we'll copy the value from one key to
 * another to keep the same behaviour between versions
 */
class Version20171026130750 implements ISimpleMigration {

	/**
	 * @param IOutput $out
	 */
	public function run(IOutput $out) {
		$config = \OC::$server->getConfig();
		$shareWithGroupMemberStatus = $config->getAppValue('core', 'shareapi_only_share_with_group_members', null);

		if ($shareWithGroupMemberStatus !== null) {
			$config->setAppValue('core', 'shareapi_only_share_with_membership_groups', $shareWithGroupMemberStatus);
		}
	}
}

Add migration to keep the same behvaiour between versions


<?php

// this simple example reads from STDIN, removes ALL codes and then prints to STDOUT.
// you can run this example and notice that special keys will be filtered out:
// $ php remove-codes.php
//
// you can also pipe the output of other commands into this to remove any control
// codes like this:
// $ phpunit --color=always | php remove-codes.php

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

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

$loop = Factory::create();

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

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

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

// pipe data from STDIN to STDOUT without any codes
$parser->pipe($stdout);

// only forward \r, \n and \t
$parser->on('c0', function ($code) use ($stdout) {
    if ($code === "\n" || $code === "\r" || $code === "\t") {
        $stdout->write($code);
    }
});

$loop->run();

Add example which removes any control codes from input


<?php

namespace Fuel\Migrations;

class Alter_reports
{
    public function up()
    {
        \DBUtil::drop_fields('reports', array(
            'location'
        ));

        \DBUtil::add_fields('reports', array(
            'ip_address' => array('type' => 'varchar', 'constraint' => 15, 'null' => true),
        ));
    }

    public function down()
    {
        \DBUtil::add_fields('reports', array(
            'location' => array('type' => 'varchar', 'constraint' => 255),
        ));

        \DBUtil::drop_fields('reports', array(
            'ip_address'
        ));
    }
}

Remove location and add ipaddress instead


<?php

use Mockery as m;
use Basset\Console\CleanCommand;

class CleanCommandTest extends PHPUnit_Framework_TestCase {

    public function tearDown()
    {
        m::close();
    }

    public function testCleanCommand()
    {
        $cleaner = m::mock('Basset\BuildCleaner');
        $cleaner->shouldReceive('clean')->once()->with(null)->andReturn(true);
        $cleaner->shouldReceive('clean')->once()->with('foo')->andReturn(true);

        $command = new CleanCommand($cleaner);

        $this->runCommand($command);
        $this->runCommand($command, array('collection' => 'foo'));
    }

    protected function runCommand($command, $input = array(), $output = null)
    {
        $output = $output ?: new Symfony\Component\Console\Output\NullOutput;

        return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), $output);
    }

}

Test coverage for clean command.

Test coverage for clean command.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<?php

require "Student.php";
require "OCCPortal.php";

$myOCC = new OCCPortal();
$student = new Student($myOCC);
$student->setUsername('username');
$student->setPassword('password');
$transcripts = $student->getTranscript();

echo $transcripts;

Add tests for the new OOD

Add tests for the new OOD


<?php

namespace MS\PHPMD\Rule\Test;

use PHPMD\AbstractNode;
use PHPMD\Node\ClassNode;

/**
 * Class MethodNameUnderstandable
 *
 * The method names in your test should describe what they will check. This work only with a few more words.
 *
 * @package MS\PHPMD\Rule\Test
 */
class MethodNameUnderstandable extends AbstractTestRule
{
    /**
     * @param AbstractNode $node
     */
    public function apply(AbstractNode $node)
    {
        if (!$node instanceof ClassNode) {
            return;
        }

        if (false === $this->isTest($node)) {
            return;
        }

        $match = $this->getBooleanProperty('match');
        $number = $this->getIntProperty('number');

        foreach ($node->getMethods() as $method) {
            $words = count(preg_split($match, $method->getImage()));

            if ($number > $words) {
                $this->addViolation($method, [$number, $words]);
            }
        }
    }
}

Add new rule for method naming in tests

Add new rule for method naming in tests


<?php

use Composer\Factory;
use Composer\IO\NullIO;
use Composer\Package\Loader\ArrayLoader;
use Composer\Repository\ComposerRepository;
use Guzzle\Http\Client;

/**
 * Interacts with Packagist to retrieve package listings and details.
 */
class PackagistService {

	const PACKAGIST_URL = 'https://packagist.org';

	/**
	 * @var Composer\Repository\RepositoryInterface
	 */
	private $repository;

	public function __construct() {
		$conf = array('url' => self::PACKAGIST_URL);

		$this->repository = new ComposerRepository($conf, new NullIO(), Factory::createConfig());
		$this->client = new Client($conf['url']);
	}

	/**
	 * Gets all SilverStripe packages.
	 *
	 * @return \Composer\Package\PackageInterface[]
	 */
	public function getPackages() {
		$packages = array();
		$loader = new ArrayLoader();

		foreach ($this->repository->getMinimalPackages() as $info) {
			if (strpos($info['raw']['type'], 'silverstripe-') === 0) {
				$packages[] = $loader->load($info['raw']);
			}
		}

		return $packages;
	}

	/**
	 * Gets all SilverStripe packages, grouped by package name.
	 *
	 * @return array
	 */
	public function getGroupedPackages() {
		$grouped = array();

		foreach ($this->getPackages() as $package) {
			$name = $package->getName();

			if (array_key_exists($name, $grouped)) {
				$grouped[$name][] = $package;
			} else {
				$grouped[$name] = array($package);
			}
		}

		return $grouped;
	}

	/**
	 * Gets detailed information for a package.
	 *
	 * @param string $name
	 * @return array
	 */
	public function getPackageDetails($name) {
		return $this->client->get("/packages/$name.json")->send()->json();
	}

}

Add a service for interacting with Packagist.


<?php
/*
 * Copyright (c) 2011
 * 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\Loader;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * ContainerLoader uses container for finding loggers
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
class ContainerLoader implements LoggerLoader
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * Constructor
     *
     * @param ContainerInterface $container Container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function load($name)
    {
        return $this->container->get($name, ContainerInterface::NULL_ON_INVALID_REFERENCE);
    }
}

Add container loader for Symfony2 service container


<?php

namespace VirtualizorNonCompiler;

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

class RubyTest extends TestCase
{
	public function test1()
	{
		$code = "puts \"hello world\";";
		$aa = new Ruby($code);
		$this->assertTrue(trim($aa->exec()) == "hello world");
	}
}

Create Ruby virtualizor test case

Create Ruby virtualizor test case


<?php

declare(strict_types=1);

namespace tests\Http\Client\Common;

use Closure;
use Http\Client\Common\Plugin;
use Http\Client\Common\PluginClient;
use Http\Client\Common\PluginClientBuilder;
use Http\Client\HttpAsyncClient;
use Http\Client\HttpClient;
use PHPUnit\Framework\TestCase;

class PluginClientBuilderTest extends TestCase
{
    /** @dataProvider clientProvider */
    public function testPriority(string $client): void
    {
        $builder = new PluginClientBuilder();

        $plugins = [
            10 => $this->prophesize(Plugin::class)->reveal(),
            -10 => $this->prophesize(Plugin::class)->reveal(),
            0 => $this->prophesize(Plugin::class)->reveal(),
        ];

        foreach ($plugins as $priority => $plugin) {
            $builder->addPlugin($plugin, $priority);
        }

        $client = $this->prophesize($client)->reveal();
        $client = $builder->createClient($client);

        $closure = Closure::bind(
            function (): array {
                return $this->plugins;
            },
            $client,
            PluginClient::class
        );

        $plugged = $closure();

        $expected = $plugins;
        krsort($expected);
        $expected = array_values($expected);

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

    public function clientProvider(): iterable
    {
        yield 'sync\'d http client' => [HttpClient::class];
        yield 'async\'d http client' => [HttpAsyncClient::class];
    }
}

Add a test on the plugin client builder

Add a test on the plugin client builder


<?php if ( !defined( 'HABARI_PATH' ) ) { die('No direct access'); } ?>

<?php _e('DB Profiling'); ?>

	<?php
	$profiles = DB::get_profiles();
	$total_time_querying = 0;
	foreach ( $profiles as $profile ) {
	?>

			<?php echo $profile->query_text; ?>

<?php _e('Time to Execute:'); ?> <?php echo $profile->total_time; ?>

		<?php if ( !empty( $profile->backtrace ) ) { ?>

			BACKTRACE:

			<?php print_r($profile->backtrace); ?>

		<?php } ?>

	<?php
			$total_time_querying+= $profile->total_time;
	}
	?>

<?php _e('Total Time Executing Queries:'); ?> <?php echo $total_time_querying; ?>

Add the db profiling template file from K2.


<?php

/* Define database connection parameters.
 * KEEP THIS FILE SECURE AND READ ONLY. */

$GLOBALS['DB'] = [
	'SERVER' => '',
	'USERNAME' => '',
	'PASSWORD' => '',
	'DATABASE' => ''
];

?>

Add template secure constants file

Add template secure constants file


<?php

use Illuminate\Database\Seeder;
use App\User;
// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class InvoicesTableSeeder extends Seeder {

	public function run()
	{
		$faker = Faker::create();

		foreach(range(1, 10) as $index)
		{
			$status = Status::orderByRaw("RAND()")->first();
			$user = User::orderByRaw("RAND()")->first();
			Invoice::create([
				'due' => $faker->date(),
				'status_id' => $status->id,
				'amount' => $faker->randomFloat($nbMaxDecimals = 2),
				'owner_id' => $user->id
			]);
		}
	}

}

<?php

use Illuminate\Database\Seeder;
use SimpleLance\User;
// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class InvoicesTableSeeder extends Seeder {

	public function run()
	{
		$faker = Faker::create();

		foreach(range(1, 10) as $index)
		{
			$status = Status::orderByRaw("RAND()")->first();
			$user = User::orderByRaw("RAND()")->first();
			Invoice::create([
				'due' => $faker->date(),
				'status_id' => $status->id,
				'amount' => $faker->randomFloat($nbMaxDecimals = 2),
				'owner_id' => $user->id
			]);
		}
	}

}

Fix namespace in table seeder

Fix namespace in table seeder


<?php namespace App\Console\Commands;

use App\Items;
use App\Services\ContentExtractor;
use Illuminate\Console\Command;
use \Log;

class FetchContent extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'articles:fetch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sychronise pocket feed for all users';

    /**
     * @var \GuzzleHttp\Client $httpClient
     */
    protected $httpClient;

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $contentExtractor = new ContentExtractor();

        Items::where('status', '=', Items::STATUS_NEW)
            ->chunk(100, function ($items) use ($contentExtractor) {
            foreach ($items as $item) {
                $item->status = Items::STATUS_BEING_FETCHED;
                $item->save();

                $content = $contentExtractor->fetchContent($item->url);
                if ($content) {
                    $item->content = $content;
                    $item->status = Items::STATUS_FETCHED;
                    $item->save();
                } else {
                    Log::error('Unable to find content for ' . $item->$url);
                    $item->status = Items::STATUS_FETCH_FAILED;
                    $item->save();
                }
            }
        });
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [];
    }
}

Add console command for finding synchronised articles that need content fetching.


<?php

namespace JWX\JWT;

use JWX\JWT\Parameter\JWTParameter;

/**
 * Interface for classes providing JOSE header parameters.
 */
interface HeaderParameters
{
	/**
	 * Get an array of JOSE header parameters representing this object.
	 *
	 * @return JWTParameter[]
	 */
	public function headerParameters();
}

Add interface for header parameter provision


<?php

namespace RapidRoute\Tests\Integration;

use RapidRoute\RapidRouteException;
use RapidRoute\RouteCollection;
use RapidRoute\MatchResult;

/**
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class EdgeCasesRouterTest extends RouterTestBase
{
    protected function compiledFileName()
    {
        return 'edge-cases';
    }

    protected function definitions(RouteCollection $routes)
    {
        $routes->get('/abc/{param}/bar', ['name' => 'middle-param']);
        $routes->get(['/123/{param}/bar', 'param' => '.*'], ['name' => 'all-middle-param']);
    }

    /**
     * Should return each case in the format:
     *
     * [
     *      'GET',
     *      '/user/1',
     *      RouterResult::found(['route_data'], ['id' => '1'])
     * ]
     *
     * @return array[]
     */
    public function routerMatchingExamples()
    {
        return [
            ['GET', '/abc//bar', MatchResult::notFound()],
            ['GET', '/abc/a/bar', MatchResult::found(['name' => 'middle-param'], ['param' => 'a'])],

            ['GET', '/123//bar', MatchResult::found(['name' => 'all-middle-param'], ['param' => ''])],
            ['GET', '/123/a/bar', MatchResult::found(['name' => 'all-middle-param'], ['param' => 'a'])],
        ];
    }

    public function testThrowsExceptionForNonEmptyRouteWithoutPrecedingSlash()
    {
        $this->setExpectedExceptionRegExp(RapidRouteException::getType(), '#prefixed with \'\\/\'#');
        $this->router->match('GET', 'abc/a/bar');
    }
}

Add tests for some edge cases

Add tests for some edge cases


<?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 / Util
 */

namespace PH7\Test\Unit\Framework\Util;

use PH7\Framework\Util\Various;

class VariousTest extends \PHPUnit_Framework_TestCase
{
    public function testPaddingString()
    {
        $this->assertEquals('abc def ghiabc def ghiabc def ghiabc def', Various::padStr('abc def ghi'));
    }
 }

Add Padding String unit test for Various class


<?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_Db
 */

namespace Zend\Db\Adapter;

use Zend\ServiceManager\FactoryInterface;

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Adapter
 */
class AdapterServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        return new Adapter($config['db']);
    }
}

Add DB adapter factory for the service manager


<?php

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

require 'SharedConfigurations.php';

// Predis allows to set Lua scripts as read-only operations in the context of
// replication. This works for both EVAL and EVALSHA and also for the client-side
// abstraction built upon them (Predis\Commands\ScriptedCommand). This example
// shows a slightly more complex configuration that injects a new scripted command
// in the server profile used by the new client instance and marks it marks it as
// a read-only operation for replication so that it will be executed on slaves.

use Predis\Profiles\ServerProfile;
use Predis\Commands\ScriptedCommand;
use Predis\Network\MasterSlaveReplication;

// ------------------------------------------------------------------------- //

// Define a new scripted command that returns all the fields
// of a variable number of hashes with a single roundtrip.

class HashMultipleGetAll extends ScriptedCommand {
    const BODY = <<<EOS
local hashes = {}
for _, key in pairs(KEYS) do
    table.insert(hashes, key)
    table.insert(hashes, redis.call('hgetall', key))
end
return hashes
EOS;

    public function getScript() {
        return self::BODY;
    }
}

// ------------------------------------------------------------------------- //

$parameters = array(
    'tcp://127.0.0.1:6379/?alias=master',
    'tcp://127.0.0.1:6380/?alias=slave',
);

$options = array(
    'profile' => function($options) {
        $profile = ServerProfile::get('dev');
        $profile->defineCommand('hmgetall', 'HashMultipleGetAll');

        return $profile;
    },
    'replication' => function($options) {
        $replication = new MasterSlaveReplication();
        $replication->setScriptReadOnly(HashMultipleGetAll::BODY);

        return $replication;
    },
);

// ------------------------------------------------------------------------- //

$client = new Predis\Client($parameters, $options);

// Execute the following commands on the master server using redis-cli:
// $ ./redis-cli HMSET metavars foo bar hoge piyo
// $ ./redis-cli HMSET servers master host1 slave host2

$hashes = $client->hmgetall('metavars', 'servers');

$replication = $client->getConnection();
$stillOnSlave = $replication->getCurrent() === $replication->getConnectionById('slave');

echo "Is still on slave? ", $stillOnSlave ? 'YES' : 'NO', "!\n";
var_export($hashes);

Add a new example for complex replication configuration.


<?php namespace Orchestra\Foundation\Composer;

use Orchestra\Foundation\Application;
use Illuminate\Foundation\ComposerScripts;

class Command extends ComposerScripts
{
    /**
     * Clear the cached Laravel bootstrapping files.
     *
     * @return void
     */
    private static function clearCompiled()
    {
        $laravel = new Application(getcwd());

        if (file_exists($compiledPath = $laravel->getCachedCompilePath())) {
            @unlink($compiledPath);
        }

        if (file_exists($servicesPath = $laravel->getCachedServicesPath())) {
            @unlink($servicesPath);
        }

        if (file_exists($extensionServicesPath = $laravel->getCachedExtensionServicesPath())) {
            @unlink($extensionServicesPath);
        }
    }
}

Add composer post install/update for Orchestra Platform.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace FeatureBrowser\FeatureBrowser\Cli;

use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

final class GenerateCommand extends BaseCommand
{
}

Create Generate Command which will generate html files for interactive docs


<?php
/**
 * phpDocumentor
 *
 * PHP Version 5.3
 *
 * @copyright 2010-2013 Mike van Riel / Naenius (http://www.naenius.com)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://phpdoc.org
 */

namespace phpDocumentor\Compiler;

/**
 * Tests the functionality for the Compiler.
 */
class CompilerTest extends \PHPUnit_Framework_TestCase
{
    /** @var Compiler $fixture */
    protected $fixture;

    /**
     * Creates a new fixture to test with.
     */
    protected function setUp()
    {
        $this->fixture = new Compiler();
    }

    /**
     * @covers phpDocumentor\Compiler\Compiler::insert
     */
    public function testDefaultPassHasDefaultPriority()
    {
        $this->fixture->insert('test');
        $this->fixture->setExtractFlags(Compiler::EXTR_PRIORITY);

        $this->assertEquals(Compiler::PRIORITY_DEFAULT, $this->fixture->extract());
    }
}

Add test for Compiler class

Add test for Compiler class


<?php

use Aedart\Scaffold\Traits\PostProcess;
use Aedart\Testing\Laravel\TestCases\unit\GetterSetterTraitTestCase;

/**
 * Class PostProcessTraitTest
 *
 * @group traits
 * @group postProcess
 *
 * @coversDefaultClass Aedart\Scaffold\Traits\PostProcess
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class PostProcessTraitTest extends GetterSetterTraitTestCase
{

    /**
     * Returns the class path to the trait in question
     *
     * @return string
     */
    public function getTraitClassPath()
    {
        return PostProcess::class;
    }

    /**
     * Returns the name of the property, which the given
     * trait has implemented its getter and setter methods
     *
     * @return string
     */
    public function propertyName()
    {
        return 'postProcess';
    }

    /**
     * Returns a new closure
     *
     * @return Closure
     */
    public function makeCallableMethod()
    {
        return function(){
            // N/A;
            $x = mt_rand(1, 10);
            return $x;
        };
    }

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

    /**
     * @test
     *
     * @covers ::setPostProcess
     * @covers ::getPostProcess
     * @covers ::hasPostProcess
     * @covers ::hasDefaultPostProcess
     * @covers ::getDefaultPostProcess
     */
    public function runPostProcessTraitMethods(){
        $this->assertGetterSetterTraitMethods($this->makeCallableMethod(), $this->makeCallableMethod());
    }
}

Add test for post process trait

Add test for post process trait


<?php
/**
 * Redirect to Metadata Games.
 *
 */

// Redirect from the base directory to www/, because that's where Yii
// wants all the action to happen.

header('Location: www/');

?>

Add redirect from root folder to www/

Add redirect from root folder to www/

Redirect from the base directory to www/, because that's where Yii
wants all the action to happen.


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, 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 / Api
 */

namespace PH7\Test\Unit\Framework\Api;

use PH7\Framework\Api\AllowCors;
use PHPUnit_Framework_TestCase;

class AllowCorsTest extends PHPUnit_Framework_TestCase
{
    public function testCorsHeader()
    {
        if (!function_exists('xdebug_get_headers')) {
            $this->markTestSkipped('Xdebug is required for this test. Please install it.');
        }

        $oCors = new AllowCors();
        $oCors->init();

        $aHeaders = xdebug_get_headers();
        $this->assertContains('Access-Control-Allow-Origin:*', $aHeaders);
        $this->assertContains('Access-Control-Allow-Methods:GET, POST, PUT, DELETE, PATCH, OPTIONS', $aHeaders);
    }

    protected function tearDown()
    {
        header_remove();
    }
}

Add test for Allow CORS class

Add test for Allow CORS class


<?php

/*
 * This file is part of Mustache.php.
 *
 * (c) 2012 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Mustache Lambda Helper.
 *
 * Passed to section and interpolation lambdas, giving them access to a `render`
 * method for rendering a string with the current context.
 */
class Mustache_LambdaHelper
{
    private $mustache;
    private $context;

    /**
     * Mustache Lambda Helper constructor.
     *
     * @param Mustache_Engine  $mustache Mustache engine instance.
     * @param Mustache_Context $context  Rendering context.
     */
    public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
    {
        $this->mustache = $mustache;
        $this->context  = $context;
    }

    /**
     * Render a string as a Mustache template with the current rendering context.
     *
     * @param string $string
     *
     * @return Rendered template.
     */
    public function render($string)
    {
        return $this->mustache
            ->loadLambda((string) $string)
            ->renderInternal($this->context);
    }
}

<?php

/*
 * This file is part of Mustache.php.
 *
 * (c) 2012 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Mustache Lambda Helper.
 *
 * Passed as the second argument to section lambdas (higher order sections),
 * giving them access to a `render` method for rendering a string with the
 * current context.
 */
class Mustache_LambdaHelper
{
    private $mustache;
    private $context;

    /**
     * Mustache Lambda Helper constructor.
     *
     * @param Mustache_Engine  $mustache Mustache engine instance.
     * @param Mustache_Context $context  Rendering context.
     */
    public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
    {
        $this->mustache = $mustache;
        $this->context  = $context;
    }

    /**
     * Render a string as a Mustache template with the current rendering context.
     *
     * @param string $string
     *
     * @return Rendered template.
     */
    public function render($string)
    {
        return $this->mustache
            ->loadLambda((string) $string)
            ->renderInternal($this->context);
    }
}

Update Lambda Helper docblock. It was a lie.


<?php

namespace PhpTabsTest\Component;

use Exception;
use PHPUnit_Framework_TestCase;
use PhpTabs\PhpTabs;

/**
 * Tests Dumper component
 */
class DumperTest extends PHPUnit_Framework_TestCase
{
  /**
   * @expectedException Exception
   */
  public function testException()
  {
    (new PhpTabs())->dump('exception');
  }
}

Add test for dumper exception

Add test for dumper exception


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

/**
 * Configuration with profiles
 *
 * Example of json file:
 * {
 *      "profile"   : "production",
 *      "myName"    : "unknown",
 *
 *      "profiles"  : {
 *          "production" : {
 *              "myName" : "A"
 *          },
 *
 *          "development" : {
 *              "myName" : "B"
 *          }
 *      }
 * }
 *
 * PHP:
 * $config = new \Neolao\Util\Config();
 * $config->parseJson($jsonContent);
 * echo $config->myName; // A
 *
 */
class Config
{
    /**
     * Parse a json
     *
     * @param   string      $json       Json string
     */
    public function parseJson($json)
    {
        // Decode the json string if necessary
        if (is_string($json)) {
            $json = json_decode($json);
        }

        // Import properties except the profiles
        foreach ($json as $propertyName => $propertyValue) {
            if ($propertyName === 'profiles') {
                continue;
            }
            $this->$propertyName = $propertyValue;
        }

        // Get the selected profile
        $profile = 'default';
        if (isset($json->profile)) {
            $profile = (string) $json->profile;
        }

        // Override the properties with the selected profile
        if (isset($json->profiles) && isset($json->profiles->$profile)) {
            $newProperties = $json->profiles->$profile;

            foreach ($newProperties as $propertyName => $propertyValue) {
                $this->$propertyName = $propertyValue;
            }
        }
    }
}

Add a configuration util that manages profiles


<?php

namespace CouchDbHypermediaApi\Test;

use PHPUnit_Framework_TestCase as TestCase;
use Doctrine\CouchDB\CouchDBClient;
use Doctrine\CouchDB\View\FolderDesignDocument;
use Guzzle\Service\Client;

class CollectionTest extends TestCase
{
    const ROOT_URI = 'http://localhost:5984/{dbname}/_design/app/_rewrite/';

    const INITIAL_URI = '/';

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

    /**
     * @var Doctrine\CouchDB\CouchDBClient
     */
    private $couchDbClient;

    public function setUp()
    {
        $this->testDbName = uniqid('test_');
        $this->couchDbClient = CouchDBClient::create(array(
            'dbname'    => $this->testDbName,
        ));
        $this->couchDbClient->createDatabase($this->testDbName);
        $dir = new \DirectoryIterator(APPLICATION_ROOT . '/_design');
        foreach ($dir as $file) {
            if ($file->isDir() && !$file->isDot()) {
                $designDoc = new FolderDesignDocument($file->getPathname());
                $this->couchDbClient->createDesignDocument($file->getFilename(), $designDoc);
            }
        }
    }

    public function tearDown()
    {
        $this->couchDbClient->deleteDatabase($this->testDbName);
    }

    public function testGetInitialUri()
    {
        $client = new Client(self::ROOT_URI, array(
        	'dbname' => $this->testDbName,
        ));
        $request = $client->get(ltrim(self::INITIAL_URI, '/'), array(
            'Accept'    => 'application/hal+json',
        ));
        $response = $request->send();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/hal+json', (string) $response->getHeader('Content-Type'));
        $resource = json_decode((string) $response->getBody());
        $this->assertEquals(self::INITIAL_URI, $resource->_links->self->href);
        $this->assertCount(0, $resource->_links->item);
        $this->assertEquals('Collections', $resource->title);
    }
}

Create collection test case with get initial URI test.


<?php
/*©lgpl*************************************************************************
*                                                                              *
* This file is part of FRIEND UNIFYING PLATFORM.                               *
* Copyright (c) Friend Software Labs AS. All rights reserved.                  *
*                                                                              *
* Licensed under the Source EULA. Please refer to the copy of the GNU Lesser   *
* General Public License, found in the file license_lgpl.txt.                  *
*                                                                              *
*****************************************************************************©*/

?>

Add calendar share info call.

Add calendar share info call.


<?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 FilterFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testEverythingAccepted() {
		$collection = range(0, 10);
		$expected = $collection;
		$actual = F\filter($collection, function() { return true; });
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testNothingAccepted() {
		$collection = range(0, 10);
		$expected = array();
		$actual = F\filter($collection, function() { return false; });
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testOnlyOddElements() {
		$collection = range(0, 10);
		$expected = array(1 => 1, 3 => 3, 5 => 5, 7 => 7, 9 => 9);
		$actual = F\filter($collection, function($element) { return ! (($element % 2) === 0); });
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testOnlyEvenElements() {
		$collection = range(0, 10);
		$expected = array(0 => 0, 2 => 2, 4 => 4, 6 => 6, 8 => 8, 10 => 10);
		$actual = F\filter($collection, function($element) { return (($element % 2) === 0); });
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testOnlyOddIndexes() {
		$collection = range(0, 10);
		$expected = array(1 => 1, 3 => 3, 5 => 5, 7 => 7, 9 => 9);
		$actual = F\filter($collection, function($element, $index) { return ! (($index % 2) === 0); });
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\filter
	 */
	public function testOnlyEvenIndexes() {
		$collection = range(0, 10);
		$expected = array(0 => 0, 2 => 2, 4 => 4, 6 => 6, 8 => 8, 10 => 10);
		$actual = F\filter($collection, function($element, $index) { return (($index % 2) === 0); });
		$this->assertEquals($expected, $actual);
	}
}

Add filter function test suite.

Add filter function test suite.


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

namespace Darvin\ContentBundle\Traits;

use Doctrine\ORM\QueryBuilder;

/**
 * Translatable entity repository trait
 */
trait TranslatableRepositoryTrait
{
    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string                     $locale    Locale
     * @param bool                       $addSelect Whether to add select
     *
     * @return TranslatableRepositoryTrait
     */
    protected function joinTranslations(QueryBuilder $qb, $locale = null, $addSelect = true)
    {
        $qb->innerJoin('o.translations', 'translations');

        if (!empty($locale)) {
            $qb->andWhere('translations.locale = :locale')->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb->addSelect('translations');
        }

        return $this;
    }
}

Implement translatable entity repository trait.


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Enum\GranteeType;
use Zimbra\Mail\Struct\ActionGrantSelector;

/**
 * Testcase class for ActionGrantSelector.
 */
class ActionGrantSelectorTest extends ZimbraMailTestCase
{
    public function testActionGrantSelector()
    {
        $rights = $this->faker->word;
        $zimbraId = $this->faker->word;
        $displayName = $this->faker->word;
        $args = $this->faker->word;
        $password = $this->faker->word;
        $accessKey = $this->faker->word;

        $grant = new ActionGrantSelector(
            $rights, GranteeType::USR(), $zimbraId, $displayName, $args, $password, $accessKey
        );

        $this->assertSame($rights, $grant->getRights());
        $this->assertTrue($grant->getGranteeType()->is('usr'));
        $this->assertSame($zimbraId, $grant->getZimbraId());
        $this->assertSame($displayName, $grant->getDisplayName());
        $this->assertSame($args, $grant->getArgs());
        $this->assertSame($password, $grant->getPassword());
        $this->assertSame($accessKey, $grant->getAccessKey());

        $grant->setRights($rights)
              ->setGranteeType(GranteeType::USR())
              ->setZimbraId($zimbraId)
              ->setDisplayName($displayName)
              ->setArgs($args)
              ->setPassword($password)
              ->setAccessKey($accessKey);
        $this->assertSame($rights, $grant->getRights());
        $this->assertTrue($grant->getGranteeType()->is('usr'));
        $this->assertSame($zimbraId, $grant->getZimbraId());
        $this->assertSame($displayName, $grant->getDisplayName());
        $this->assertSame($args, $grant->getArgs());
        $this->assertSame($password, $grant->getPassword());
        $this->assertSame($accessKey, $grant->getAccessKey());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<grant perm="' . $rights . '" gt="' . GranteeType::USR() . '" zid="' . $zimbraId . '" d="' . $displayName . '" args="' . $args . '" pw="' . $password . '" key="' . $accessKey . '" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $grant);

        $array = array(
            'grant' => array(
                'perm' => $rights,
                'gt' => GranteeType::USR()->value(),
                'zid' => $zimbraId,
                'd' => $displayName,
                'args' => $args,
                'pw' => $password,
                'key' => $accessKey,
            ),
        );
        $this->assertEquals($array, $grant->toArray());
    }
}

Add Test case for ActionGrantSelector.

Add Test case for ActionGrantSelector.


<?php declare(strict_types=1);

namespace Siler\Test\Unit\Prelude;

use PHPUnit\Framework\TestCase;
use function Siler\Arr\set;

class ArrTest extends TestCase
{
    public function testSet()
    {
        $fixture = ['foo' => ['bar' => 'baz']];
        $expected = ['foo' => ['bar' => 'qux']];
        $this->assertSame($expected, set($fixture, 'foo.bar', 'baz'));
    }
}

Add test to new Arr module

Add test to new Arr module


<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Log\SoapLogger;

use Biplane\YandexDirect\Log\SoapLogger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

final class PsrLogger implements SoapLogger
{
    private const MESSAGE = 'service={service} method={method} requestId={request_id} fault={fault}';

    /** @var LoggerInterface */
    private $logger;

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

    /**
     * @psalm-param LogLevel::* $errorLogLevel
     */
    public function __construct(LoggerInterface $logger, string $errorLogLevel = LogLevel::ERROR)
    {
        $this->logger = $logger;
        $this->errorLogLevel = $errorLogLevel;
    }

    /**
     * {@inheritDoc}
     */
    public function log(array $context): void
    {
        $this->logger->log($context['failed'] ? $this->errorLogLevel : LogLevel::DEBUG, self::MESSAGE, $context);
    }
}

Add simple adapter for PSR logger

Add simple adapter for PSR logger


<?php
/**
 * @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
 *    Confidential and Proprietary. Any dissemination outside of Quicken Loans
 *    is strictly prohibited.
 */

namespace QL\Panthor\Setup;

use Composer\Script\Event;

class PostInstallCommand
{
    public static function derp(Event $event)
    {
        $composer = $event->getComposer();
        $io = $event->getIO();

        $wd = $composer->getConfig()->get('working-dir');
        $io->write('derp derp');
        $io->write('working dir='. $wd);

        // sanitize these files:

        // bin/dump-di.dist -> put it at bin/dump-di
        // configuration/bootstrap.php.dist -> put it at configuration/bootstrap.php
        // public/index.php.dist -> put it at public/index.php

        // overwrite composer.json
        // ask user for package name
    }
}

Add debug post install script

Add debug post install script


<?php

declare(strict_types=1);

namespace mcordingley\Regression\RegressionAlgorithm;

use mcordingley\Regression\Observations;

/**
 * GradientDescent
 *
 * Implements a stochastic gradient descent on the data, cycling through each
 * data vector and nudging the weights in the direction of the latest datum with
 * decreasing step sizes.
 */
final class GradientDescent implements RegressionAlgorithm
{
    private $gradient;

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

    public function regress(Observations $data): array
    {
        $dependentData = $data->getDependents();
        $independentData = $data->getIndependents();

        $observationCount = count($independentData);
        $explanatoryCount = count($independentData[0]);

        // Starting guess is that everything contributes equally.
        $oldCoefficients = null;
        $coefficients = array_fill(0, $explanatoryCount, 1.0);

        for ($iteration = 0; $coefficients !== $oldCoefficients; $iteration++) {
            $stepSize = 1000.0 / (1000.0 + $iteration);
            $observationIndex = $iteration % $observationCount;
            $oldCoefficients = $coefficients;

            for ($i = 0; $i < $explanatoryCount; $i++) {
                $coefficients[$j] += $stepSize * $this->gradient->loss($coefficients, $independentData[$observationIndex], $dependentData[$observationIndex], $i);
            }
        }

        return $coefficients;
    }
}

Implement gradient descent over an arbitrary loss function.


<?php

class SassmeisterTest extends TestCaseBase
{
    public function testGist()
    {
        $this->assertEmbed(
            'http://sassmeister.com/gist/1122e441f0434ec6eb2a',
            [
                'title' => 'SassMeister | The Sass Playground!',
                'imageWidth' => 240,
                'imageHeight' => 240,
                'type' => 'rich',
                'providerName' => 'sassmeister',
            ]
        );
    }
}

Add test for Sassmeister adapter

Add test for Sassmeister adapter


<?php

use Galahad\LaravelAddressing\ServiceProvider;
use Illuminate\Validation\Factory;
use Orchestra\Testbench\TestCase;

/**
 * Class TranslationTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class TranslationTest extends TestCase
{
    /**
     * @var Factory
     */
    protected $validator;

    public function setUp()
    {
        parent::setUp();
        $this->validator = $this->app['validator'];
    }

    protected function getPackageProviders($app)
    {
        return [ServiceProvider::class];
    }

    public function testENMessages()
    {
        $this->app->setLocale('en');
        $validator = $this->validator->make(
            ['country' => 'ZZ'],
            ['country' => 'country_code']
        );
        if ($validator->fails()) {
            $messages = $validator->errors()->get('country');
            $first = array_shift($messages);
            $this->assertEquals($first, 'The country has not a valid country code.');
        }
    }

    public function testPT_BRMessages()
    {
        $this->app->setLocale('pt-br');
        $validator = $this->validator->make(
            ['country' => 'ZZ'],
            ['country' => 'country_code']
        );
        if ($validator->fails()) {
            $messages = $validator->errors()->get('country');
            $first = array_shift($messages);
            $this->assertEquals($first, 'O campo country não possui um código de país válido.');
        }
    }

    public function testENMessagesForAdministrativeAreaValidator()
    {
        $this->app->setLocale('en');
        $validator = $this->validator->make(
            ['country' => 'US', 'state' => 'COO'],
            ['country' => 'country_code', 'state' => 'administrative_area:country']
        );
        if ($validator->fails()) {
            $messages = $validator->errors()->get('state');
            $first = array_shift($messages);
            $this->assertEquals($first, 'The state has not a valid administrative area name.');
        }
    }
}

Add unit tests for translated validation messages in en and pt-br


<?php

/**
 * Temporary autoloader to ensure compatibility with old, non-PSR-2 compliant classes.
 *
 * @author Jaime Pérez Crespo <jaime.perez@uninett.no>
 * @package SimpleSAMLphp
 */

/**
 * Autoload function that looks for classes migrated to PSR-2.
 *
 * @param string $className Name of the class.
 */
function SAML2_autoload($className)
{
    // handle classes that have been renamed
    $renamed = array(
        'SAML2_Const' => 'SAML2_Constants',
    );
    $oldName = $className;
    if (array_key_exists($className, $renamed)) {
        $className = $renamed[$className];
    }

    $file = dirname(__FILE__).'/'.str_replace('_', '/', $className).'.php';
    if (file_exists($file)) {
        require_once($file);
        $newName = '\\'.str_replace('_', '\\', $className);
        class_alias($newName, $oldName);
    }

}

spl_autoload_register('SAML2_autoload');

Add an autoloader that allows using the old class names even after migrating to PSR-2. This makes it easier for projects using the library to migrate, as it can then be done incrementally.


<?php
/**
* 2014-08-27
* @name Project M Game Bridge
* @homepage http://projectmgame.com/en/
* @description Returns the newest articles.
* @maintainer corenting
*/
class ProjectMGameBridge extends BridgeAbstract{
  public function collectData(array $param){
    $html = '';
    $html = file_get_html('http://projectmgame.com/en/') or $this->returnError('Error while downloading the Project M homepage', 404);

    foreach($html->find('article') as $article) {
      $item = new \Item();
      $item->uri = 'http://projectmgame.com/en/'.$article->find('section div.info_block a',0)->href;
      $item->title = $article->find('h1 p',0)->innertext;

      $p_list = $article->find('section p');
      $content = '';
      foreach($p_list as $p)
      {
        $content .= $p->innertext;
      }
      $item->content = $content;

      // get publication date
      $str_date = $article->find('section div.info_block a',0)->innertext;
      $timestamp = strtotime($str_date);
      $item->timestamp = $timestamp;

      $this->items[] = $item;
    }
  }

  public function getName(){
    return 'Project M Game Bridge';
  }

  public function getURI(){
    return 'http://projectmgame.com/en/';
  }

  public function getCacheDuration(){
    return 10800;
  }
}

Add bridge for Project M

Add bridge for Project M


<?php

namespace LAG\AdminBundle\Configuration;

use JK\Configuration\Configuration;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MenuConfiguration extends Configuration
{
    /**
     * @var string
     */
    private $menuName;

    public function __construct(string $menuName)
    {
        $this->menuName = $menuName;

        parent::__construct();
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'items' => [],
                'attr' => [],
                'position' => null,
                'css_class' => 'list-group nav flex-column navbar-nav menu-'.$this->menuName,
                'item_css_class' => '',
                //list-group-item list-group-item-action',
                'link_css_class' => 'nav-link',
                'template' => '',
                'brand' => false,
            ])
            ->setAllowedValues('position', [
                'horizontal',
                'vertical',
                null
            ])
            ->setNormalizer('position', function (Options $options, $value) {
                if ('top' === $this->menuName && null === $value) {
                    $value = 'horizontal';
                }

                if ('left' === $this->menuName && null === $value) {
                    $value = 'vertical';
                }

                return $value;
            })
            ->setNormalizer('template', function (Options $options, $value) {
                // Define bootstrap navbar component template
                if ('horizontal' === $options->offsetGet('position')) {
                    $value = '@LAGAdmin/Menu/menu.horizontal.html.twig';

                }

                // Define bootstrap nav component template
                if ('vertical' === $options->offsetGet('position')) {
                    $value ='@LAGAdmin/Menu/menu.vertical.html.twig';
                }

                return $value;
            })
            ->setNormalizer('attr', function (Options $options, $value) {
                $position = $options->offsetGet('position');

                if (!key_exists('class', $value)) {
                    $value['class'] = '';
                }

                if ('horizontal' === $position) {
                    $value['class'] .= ' navbar navbar-expand-lg navbar-dark bg-dark fixed-top';
                }

                if ('vertical' === $position) {
                    $value['class'] .= ' list-group';
                }
                $value['class'] = trim($value['class']);

                return $value;
            })
            ->setNormalizer('item_css_class', function (Options $options, $value) {
                $position = $options->offsetGet('position');

                if (!$value) {
                    $value = '';
                }

                if ('horizontal' === $position) {
                    $value .= ' ';
                }

                if ('vertical' === $position) {
                    $value .= ' list-group-item list-group-item-action';
                }

                return trim($value);
            })
        ;
    }
}

Add a menu configuration to handle menu creation


<?php

namespace Illuminate\Auth;

trait Authenticatable
{
    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return $this->getKeyName();
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->{$this->getRememberTokenName()};
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
        $this->{$this->getRememberTokenName()} = $value;
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return 'remember_token';
    }
}

<?php

namespace Illuminate\Auth;

trait Authenticatable
{
    /**
     * Variable containing "remember me" column name.
     *
     * @var string
     */
    protected $remember_column = 'remember_token';

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return $this->getKeyName();
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        if (! empty($this->getRememberTokenName())) {
            return $this->{$this->getRememberTokenName()};
        }
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
        if (! empty($this->getRememberTokenName())) {
            $this->{$this->getRememberTokenName()} = $value;
        }
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return $this->remember_column;
    }
}

Fix 'remember_me' column not found error


<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * Create admin page. This file can be used to create the admin account right after the data base is set up.
 * This file should be removed once this is done.
 */

require_once 'app/config/SecurityConfig.php';

require_once 'app/helperClasses/database/DataBase.php';
require_once 'app/helperClasses/database/DataBaseException.php';

require_once 'app/models/user/User.php';

require_once 'app/helperClasses/random/Random.php';

// Generate password salt
$passwordSalt = Random::getGuid();

// Create new user
$user = new User();
$user->userId = 0;
$user->email = 'admin@stippers.be';
$user->firstName = 'admin';
$user->lastName = 'admin';
$user->street = 'Stippers street';
$user->houseNumber = '1';
$user->city = 'Stippers city';
$user->postalCode = '0000';
$user->country = 'Belgium';
$user->dateOfBirth = '23/03/1993';
$user->isAdmin = true;
$user->phone = '';
$user->passwordHash = hash_pbkdf2('sha256', 'Passw0rd', $passwordSalt, SecurityConfig::N_PASSWORD_HASH_ITERATIONS);

// Insert user in data base
$conn = DataBase::getConnection();
$commString = 'INSERT INTO stippers_users (user_id, email, first_name, last_name, password_hash, password_salt, phone, date_of_birth, street, house_number, city, postal_code, country) ' .
                    'VALUES (?, ?, ?, ?, ?, ?, ?, STR_TO_DATE(?, "%d/%m/%Y"), ?, ?, ?, ?, ?)';
$stmt = $conn->prepare($commString);
$stmt->bind_param('issssssssssss', $user->userId, $user->email, $user->firstName, $user->lastName, $user->passwordHash, $passwordSalt, $user->phone, $user->dateOfBirth, $user->street, $user->houseNumber, $user->city, $user->postalCode, $user->country);

$stmt->execute();
$conn->close();

Add file to create the admin account.

Add file to create the admin account.


<?php

namespace Yajra\Acl\Traits;

trait AuthorizesResources
{
    /**
     * Permission resource ability mapping.
     *
     * @var array
     */
    protected $resourceAbilityMap = [
        'index'   => 'lists',
        'create'  => 'create',
        'store'   => 'create',
        'show'    => 'view',
        'edit'    => 'update',
        'update'  => 'update',
        'destroy' => 'delete',
    ];

    /**
     * Controller specific ability map.
     *
     * @var array
     */
    protected $customAbilityMap = [];

    /**
     * Authorize a resource action based on the incoming request.
     *
     * @param  string $model
     * @param  string|null $parameter
     * @param  array $options
     * @return void
     */
    public function authorizeResource($model, $parameter = null, array $options = [])
    {
        $parameter = $parameter ?: strtolower(class_basename($model));

        foreach ($this->resourceAbilityMap() as $method => $ability) {
            $modelName = in_array($method, ['index', 'create', 'store']) ? $model : $parameter;

            $this->middleware("can:{$modelName}.{$ability}", $options)->only($method);
        }
    }

    /**
     * Get the map of resource methods to ability names.
     *
     * @return array
     */
    protected function resourceAbilityMap()
    {
        return array_merge($this->resourceAbilityMap, $this->customAbilityMap);
    }
}

Add trait to authorize resource in controller.


<?php
/**
 * This authproc filter enables the possibility to check which IP the client has.
 * If it is wanted, the IDP is able to disable 2FA for special clients.
 * For example a user, which is located in the local area network, does not need 2FA
 * @author Micha Preußer <micha.preusser@netknights.it>
 */

class sspmod_privacyIDEA_Auth_Process_checkClientIP extends SimpleSAML_Auth_ProcessingFilter {

	/**
     * range of excluded IPs
     * enter start and end IP
	 * @var array|mixed
	 */
    private $excludeClientIPs = array();

     public function __construct(array $config, $reserved)
     {
        SimpleSAML_Logger::info("Checking client ip for privacyIDEA");
        parent::__construct($config, $reserved);
        $cfg = SimpleSAML_Configuration::loadFromArray($config, 'privacyidea:checkClientIP');
        $this->excludeClientIPs = $cfg->getArray('excludeClientIPs', null);
     }

	public function process( &$state ) {
        $startIP = ip2long($this->excludeClientIPs[0]);
        $endIP = ip2long($this->excludeClientIPs[1]);
        $clientIP = ip2long($_SERVER['REMOTE_ADDR']);

        if ($clientIP >= $startIP && $clientIP <= $endIP) {
            $state['privacyIDEA']['enabled'][0] = false;
        }

	}

}

Check if client IP needs 2FA Here you can enter a range op IPs. If the client is in the range, it does not need 2FA


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

namespace Zend\Authentication;

interface AuthenticationServiceInterface
{
    /**
     * @return Result
     */
    public function authenticate();

    /**
     * Returns true if and only if an identity is available
     *
     * @return bool
     */
    public function hasIdentity();

    /**
     * Returns the authenticated identity or null if no identity is available
     *
     * @return mixed|null
     */
    public function getIdentity();

    /**
     * Clears the identity
     *
     * @return void
     */
    public function clearIdentity();
}

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

namespace Zend\Authentication;

interface AuthenticationServiceInterface
{
    /**
     * Authenticates and provides an authentication result
     *
     * @return Result
     */
    public function authenticate();

    /**
     * Returns true if and only if an identity is available
     *
     * @return bool
     */
    public function hasIdentity();

    /**
     * Returns the authenticated identity or null if no identity is available
     *
     * @return mixed|null
     */
    public function getIdentity();

    /**
     * Clears the identity
     *
     * @return void
     */
    public function clearIdentity();
}

Add docblock description to authenticate()


<?php namespace Illuminate\Support;

class ClassLoader {

	/**
	 * The registered directories.
	 *
	 * @var array
	 */
	protected static $directories = array();

	/**
	 * Indicates if a ClassLoader has been registered.
	 *
	 * @var bool
	 */
	protected static $registered = false;

	/**
	 * Load the given class file.
	 *
	 * @param  string  $class
	 * @return bool
	 */
	public static function load($class)
	{
		$class = static::normalizeClass($class);

		foreach (static::$directories as $directory)
		{
			if (file_exists($path = $directory.DIRECTORY_SEPARATOR.$class))
			{
				require_once $path;

				return true;
			}
		}

		return false;
	}

	/**
	 * Get the normal file name for a class.
	 *
	 * @param  string  $class
	 * @return string
	 */
	public static function normalizeClass($class)
	{
		if ($class[0] == '\\') $class = substr($class, 1);

		return str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $class).'.php';
	}

	/**
	 * Register the given class loader on the auto-loader stack.
	 *
	 * @return void
	 */
	public static function register()
	{
		if ( ! static::$registered)
		{
			static::$registered = spl_autoload_register(array('\Illuminate\Support\ClassLoader', 'load'));
		}
	}

	/**
	 * Add directories to the class loader.
	 *
	 * @param  string|array  $directories
	 * @return void
	 */
	public static function addDirectories($directories)
	{
		static::$directories = array_unique(array_merge(static::$directories, (array) $directories));
	}

	/**
	 * Remove directories from the class loader.
	 *
	 * @param  string|array  $directories
	 * @return void
	 */
	public static function removeDirectories($directories = null)
	{
		if (is_null($directories))
		{
			static::$directories = array();
		}
		else
		{
			static::$directories = array_diff(static::$directories, (array) $directories);
		}
	}

	/**
	 * Gets all the directories registered with the loader.
	 *
	 * @return array
	 */
	public static function getDirectories()
	{
		return static::$directories;
	}

}

Add the class loader to support for backwards compat.


<?php

echo generateRandomString(8)."\n";

function generateRandomString($length = 10) {
    return substr(str_shuffle("0123456789abcdefghjkmnopqrstuvwxyz"), 0, $length);
}

Create util to generate code

Create util to generate code


<?php
namespace Victoire\Bundle\CoreBundle\Twig\Extension;

use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Victoire\Bundle\PageBundle\Helper\PageHelper;

/**
 * class RoutingExtension
 */
class RoutingExtention extends RoutingExtension
{

    private $pageHelper;
    private $generator;

    public function __construct(PageHelper $pageHelper, UrlGeneratorInterface $generator)
    {
        $this->pageHelper = $pageHelper;
        $this->generator = $generator;
        parent::__construct($generator);
    }

    public function getPath($name, $parameters = array(), $relative = false)
    {
        if ($name == 'victoire_core_page_show_by_id') {
            $params = array('viewId' => $parameters['viewId']);
            unset($parameters['viewId']);
            if (!empty($parameters['entityId'])) {
                $params['entityId'] = $parameters['entityId'];
                unset($parameters['entityId']);
            }
            $page = $this->pageHelper->findPageByParameters($params);
            $parameters['url'] = $page->getUrl();

            return $this->generator->generate('victoire_core_page_show', $parameters);
        }

        return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
    }
}

<?php
namespace Victoire\Bundle\CoreBundle\Twig\Extension;

use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Victoire\Bundle\PageBundle\Helper\PageHelper;

/**
 * class RoutingExtension
 */
class RoutingExtention extends RoutingExtension
{

    private $pageHelper;
    private $generator;

    public function __construct(PageHelper $pageHelper, UrlGeneratorInterface $generator)
    {
        $this->pageHelper = $pageHelper;
        $this->generator = $generator;
        parent::__construct($generator);
    }

    public function getPath($name, $parameters = array(), $relative = false)
    {
        if ($name == 'victoire_core_page_show_by_id') {
            $params = array('viewId' => $parameters['viewId']);
            unset($parameters['viewId']);
            if (!empty($parameters['entityId'])) {
                $params['entityId'] = $parameters['entityId'];
                unset($parameters['entityId']);
            }
            $page = $this->pageHelper->findPageByParameters($params);
            $parameters['url'] = $page->getUrl();

            $name = 'victoire_core_page_show';
        }

        return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::ABSOLUTE_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
    }
}

Allow absolute path on twig getPath function


<?php

class JsonView extends ApiView {
    public function render($content) {
        header('Content-Type: application/json; charset=utf8');
        echo $this->buildOutput($content);
        return true;
    }

    /**
     *  Function to build output, can be used by JSON and JSONP
     */
    public function buildOutput ($content) {
        $content = $this->addCount($content);
        // need to work out which fields should have been numbers
        // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs)

        // Specify a list of fields to NOT convert to numbers
        $this->string_fields = array("stub", "track_name");

        $output = $this->numeric_check($content);
        $retval = json_encode($output);
        return $retval;
    }

    protected function numeric_check($data)
    {
        if (!is_array($data)) {
            return $this->scalarNumericCheck('', $data);
        }
        $output = array();
        foreach($data as $key => $value) {

            // recurse as needed
            if(is_array($value)) {
                $output[$key] = $this->numeric_check($value);
            } else {
                $output[$key] = $this->scalarNumericCheck($key, $value);
            }
        }
        return $output;
    }

    protected function scalarNumericCheck($key, $value)
    {
        if (is_numeric($value) && !in_array($key, $this->string_fields)) {
            return (float)$value;
        }
        return $value;
    }

}

<?php

class JsonView extends ApiView {
    public function render($content) {
        header('Content-Type: application/json; charset=utf8');
        echo $this->buildOutput($content);
        return true;
    }

    /**
     *  Function to build output, can be used by JSON and JSONP
     */
    public function buildOutput ($content) {
        $content = $this->addCount($content);
        // need to work out which fields should have been numbers
        // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs)

        // Specify a list of fields to NOT convert to numbers
        $this->string_fields = array("stub", "track_name", "comment");

        $output = $this->numeric_check($content);
        $retval = json_encode($output);
        return $retval;
    }

    protected function numeric_check($data)
    {
        if (!is_array($data)) {
            return $this->scalarNumericCheck('', $data);
        }
        $output = array();
        foreach($data as $key => $value) {

            // recurse as needed
            if(is_array($value)) {
                $output[$key] = $this->numeric_check($value);
            } else {
                $output[$key] = $this->scalarNumericCheck($key, $value);
            }
        }
        return $output;
    }

    protected function scalarNumericCheck($key, $value)
    {
        if (is_numeric($value) && !in_array($key, $this->string_fields)) {
            return (float)$value;
        }
        return $value;
    }

}

Add 'comment' field to list of non-numeric fields.


<?php

namespace OGetIt;

use OGetIt\CombatReport\OGetIt_CombatReport;

class OGetIt_Debug extends OGetIt {

	public function __construct() {}

	/**
	 * @param string $dataUrl
	 */
	public function getCombatReport($dataUrl) {

		$data = file_get_contents($dataUrl);
		$data = json_decode($data, true);

		return $data === false ? $data : OGetIt_CombatReport::createCombatReport($data['RESULT_DATA']);

	}

}

Debug class to allow fetching local files/urls


<?php
/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @contributor: stagprom <https://github.com/stagprom/>
 * @copyright Loic Blot 2014-2015
 */

namespace OCA\OcSms\Lib;

class CountryCodes {
	public static $codes = array(
		"Algeria" => "+213",
		"Belgium" => "+32",
		"Brazil" => "+55",
		"Canada" => "+1",
		"Egypt" => "+20",
		"France" => "+33",
		"Germany" => "+49",
		"Hong Kong" => "+852",
		"India" => "+91",
		"Italy" => "+39",
		"Japan" => "+81",
		"Mexico" => "+52",
		"Morocco" => "+212",
		"Norway" => "+47",
		"Poland" => "+48",
		"Russia" => "+7",
		"South Korea" => "+82",
		"South Sudan" => "+211",
		"Spain" => "+34",
		"Sweden" => "+46",
		"Tunisia" => "+216",
		"USA" => "+1",

	);
};

Add a basic countrycode mapper for future use to dedup phone intl/local prefix problems


<?php

namespace adrianclay\git\Pack;

use adrianclay\git\Repository;
use adrianclay\git\SHA;
use PHPUnit\Framework\TestCase;

class IndexTest extends TestCase
{
    private $repository;

    public function setUp(): void
    {
        parent::setUp();
        $path = __DIR__ . '/../../';
        $this->repository = new Repository( $path );
    }

    public function testCanGetAOffsetOfZeroPrefixedSha() {
        $sha = new SHA( "00" . "f5270dc9fcb8ec4c31e04334128a4a9f596470" );
        $object = $this->repository->getObject( $sha );
        $this->assertNotNull( $object );
    }
}

Add test for fetching an object which starts with 00

This is a special case where the fanout table does not get used.


<?php

use Fhaculty\Graph\Algorithm\Complete as AlgorithmComplete;
use Fhaculty\Graph\Graph;

class CompleteTest extends TestCase
{
    public function testGraphEmptyK0()
    {
        $graph = new Graph();

        $alg = new AlgorithmComplete($graph);

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

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

        $alg = new AlgorithmComplete($graph);

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

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

        $alg = new AlgorithmComplete($graph);

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

    public function testGraphSingleDirectedIsNotComplete()
    {
        // 1 -> 2
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($graph->createVertex(2));

        $alg = new AlgorithmComplete($graph);

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

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

        $alg = new AlgorithmComplete($graph);

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

Add tests with 100% coverage for Algorithm\Complete


<?php

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

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

        $alg = new AlgorithmEulerian($graph);

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

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

        $alg = new AlgorithmEulerian($graph);

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

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

        $alg = new AlgorithmEulerian($graph);

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

Add tests with 100% coverage for Algorithm\Eulerian


<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user_roles".
 *
 * @property integer $id
 * @property string $role_name
 * @property string $description
 *
 * @property Signuplinks[] $signuplinks
 * @property Supervisorprofile[] $supervisorprofiles
 * @property User[] $users
 */
class UserRoles extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_roles';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['role_name', 'description'], 'string', 'max' => 255],
            [['role_name'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'role_name' => 'Role Name',
            'description' => 'Description',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSignuplinks()
    {
        return $this->hasMany(Signuplinks::className(), ['role' => 'role_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSupervisorprofiles()
    {
        return $this->hasMany(Supervisorprofile::className(), ['role' => 'role_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUsers()
    {
        return $this->hasMany(User::className(), ['role' => 'role_name']);
    }
}

Add model class for user_roles table

Add model class for user_roles table


<?php

namespace App\Console\Commands\Report;

use App\Models\Collections\Artwork;

use League\Csv\Writer;
use Illuminate\Support\Facades\Storage;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportNoTerms extends BaseCommand
{

    protected $signature = 'report:no-terms';

    protected $description = "Report all artworks that have no Expore Further preferred terms set";

    public function handle()
    {

        $csv = Writer::createFromString('');

        $csv->insertOne([
            'artwork_id',
            'main_reference_number',
            'title',
            'classification_id',
            'style_id',
            'artist_id',
        ]);

        $response = file_get_contents(config('app.url') .'/api/v1/artworks/search?limit=500&query%5Bbool%5D%5Bmust_not%5D%5B%5D%5Bexists%5D%5Bfield%5D=style_id&query%5Bbool%5D%5Bmust_not%5D%5B%5D%5Bexists%5D%5Bfield%5D=classification_id&query%5Bbool%5D%5Bmust_not%5D%5B%5D%5Bexists%5D%5Bfield%5D=artist_id&fields=id,title,artist_id,classification_id,style_id,main_reference_number');

        foreach (json_decode($response)->data as $artwork)
        {

            $row = [
                'artwork_id' => $artwork->id,
                'main_reference_number' => $artwork->main_reference_number,
                'title' => $artwork->title,
                'classification_id' => $artwork->classification_id,
                'style_id' => $artwork->style_id,
                'artist_id' => $artwork->artist_id,
            ];

            $csv->insertOne($row);

        }

        Storage::put('artwork-no-terms.csv', $csv->getContent());

    }

}

Add command to create CSV of works with no style, classification or artist


<?php
/**
* SmartFile PHP SDK
*
* PHP version 5
*
* LICENSE: The MIT License (MIT)
*
* Copyright Copyright (c) 2012, SmartFile
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @category Web_Services
* @package SmartFile
* @author Ben Timby <btimby@gmail.com>
* @author Ryan Johnston <github@shopandlearn.net>
* @copyright 2012 SmartFile
* @license See LICENSE file
* @version GIT: $Id$
* @link http://pear.php.net/package/SmartFile
* @since File available since Release 2.2
*/

require_once '../Services/SmartFile/BasicClient.php';

// {{{ constants

/**
* These constants are needed to access the API.
*/
define("API_KEY", "api-key");
define("API_PWD", "api-path");

// }}}

// a quick test
$client = new Service_SmartFile_BasicClient(API_KEY, API_PWD);
$client->api_base_url= 'https://yoursite.smartfile.com/api/2';
/* Work around the issue here: https://github.com/smartfile/client-php/issues/4 */
$response = $client->doRequest('/path/data/your.file', 'get');
// Remove chunks in response
/* This is done in the api with the getBody method, but it is protected
  So you will need to do something in your code like: */
// $response = $client->getBody($response);
echo $response;
?>

Add an example for downloading a file.

Add an example for downloading a file.


<?php

/*
 * This file is part of VirtPHP.
 *
 * (c) Jordan Kasper <github @jakerella>
 *     Ben Ramsey <github @ramsey>
 *     Jacques Woodcock <github @jwoodcock>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Virtphp\Test\Util;

use Virtphp\TestCase;
use Virtphp\Util\ErrorHandler;

/**
 * ErrorHandler test case
 */
class ErrorHandlerTest extends TestCase
{
    /**
     * Test ErrorHandler handles notices
     */
    public function testErrorHandlerCaptureNotice()
    {
        $this->setExpectedException('\ErrorException', 'Undefined index: baz');

        ErrorHandler::register();

        $array = array('foo' => 'bar');
        $array['baz'];
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerCaptureWarning()
    {
        $this->setExpectedException('\ErrorException', 'array_merge');

        ErrorHandler::register();

        array_merge(array(), 'string');
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerRespectsAtOperator()
    {
        ErrorHandler::register();

        @trigger_error('test', E_USER_NOTICE);
    }

    /**
     * Test ErrorHandler includes xdebug.scream message
     */
    public function testErrorHandlerXdebugScream()
    {
        ini_set('xdebug.scream', 1);
        $this->setExpectedException('\ErrorException',
            "array_merge(): Argument #2 is not an array"
            . "\n\nWarning: You have xdebug.scream enabled, the warning above may be"
            . "\na legitimately suppressed error that you were not supposed to see."
        );

        ErrorHandler::register();

        array_merge(array(), 'string');
    }
}

Add full test coverage for ErrorHandler

Add full test coverage for ErrorHandler


<?php

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

namespace Nietonfir\RaygunBundle\Tests\Twig;

use Nietonfir\RaygunBundle\Twig\RaygunSetupExtension;

class RaygunSetupExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $reflection = new \ReflectionProperty('Nietonfir\RaygunBundle\Twig\RaygunSetupExtension', 'apiKey');
        $reflection->setAccessible(true);

        $apiKey = '1234567';
        $extension = new RaygunSetupExtension($apiKey);

        $this->assertInstanceof('\Twig_Extension', $extension);
        $this->assertInstanceof('\Twig_Extension_GlobalsInterface', $extension);
        $this->assertEquals('nietonfir_raygun_setup', $extension->getName());
        $this->assertEquals($apiKey, $reflection->getValue($extension));
    }

    public function testGlobals()
    {
        $apiKey = '1234567';
        $extension = new RaygunSetupExtension($apiKey);

        $this->assertEquals(array('raygun_api_key' => $apiKey), $extension->getGlobals());
    }
}

Add missing unit tests for the twig extension


<?php

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

/**
 * Class CreateFriendFriendshipGroupsTable
 */
class CreateFriendFriendshipGroupsTable extends Migration
{

    public function up() {

        Schema::create(config('friendships.tables.fr_groups_pivot'), function (Blueprint $table) {

            $table->integer('friendship_id')->unsigned();
            $table->morphs('friend');
            $table->integer('group_id')->unsigned();

            $table->foreign('friendship_id')
                ->references('id')
                ->on(config('friendships.tables.fr_pivot'))
                ->onDelete('cascade');

            $table->unique(['friendship_id', 'friend_id', 'friend_type', 'group_id'], 'unique');

        });

    }

    public function down() {
        Schema::dropIfExists(config('friendships.tables.fr_groups_pivot'));
    }

}

Create Migration for user's personal groups (acquaintances, family, etс.)


<?php

namespace RJ\FootballApp\App;

use DI\Bridge\Slim\App;
use DI\ContainerBuilder;
use RJ\FootballApp\Controller\UserController;

use function DI\object;
use function DI\get;

class Application extends App
{
    public function __construct()
    {
        parent::__construct();

        $this->initialize();
    }

    private function initialize()
    {
        $this->routes();
    }

    protected function configureContainer(ContainerBuilder $builder)
    {
        $builder->addDefinitions($this->configuration());
    }

    private function configuration()
    {
        return [
            'settings.displayErrorDetails' => true,
            //'foundHandler' => \DI\object(RequestResponse::class)
        ];
    }

    private function routes()
    {
        $this->get('/login', [UserController::class, 'login']);
        $this->get('/logout', [UserController::class, 'logout']);
    }
}

[DEV] Add base class for application start and configuration


<?php
/**
 * Nooku Platform - http://www.nooku.org/platform
 *
 * @copyright	Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		https://github.com/nooku/nooku-platform for the canonical source repository
 */

namespace Nooku\Library;

/**
 * Permissible Database Behavior
 *
 * - Requires an 'access' table column to define if the row is accessible by everyone or only be registered user.
 * - Requires an 'access_group' table column to define which user group(s) have access.
 * - Requires an 'access_role' table column to define which user role(s) have access.
 *
 * @author  Johan Janssens <https://github.com/johanjanssens>
 * @package Nooku\Library\Database
 */
class DatabaseBehaviorAccessible extends DatabaseBehaviorAbstract
{
    /**
     * Check if the row can be accessed
     *
     * @return  boolean  True on success, false otherwise
     */
    public function canAccess()
    {
        //Check if the user needs to be authentic to access
        if($this->hasProperty('access') && !empty($this->access))
        {
            if(!$this->getObject('user')->isAuthentic()) {
                return false;
            }
        }

        //Check if the user is in the group(s) to access
        if($this->hasProperty('access_group') && !empty($this->access_group))
        {
            $groups = $this->getObject('user')->getGroups();

            if(!in_array($this->access_group, $groups)) {
                return false;
            }
        }

        //Check if the user has the right role(s) to access
        if($this->hasProperty('access_role') && !empty($this->access_role))
        {
            if(!$this->getObject('user')->hasRole($this->access_role)) {
                return false;
            }
        }

        return true;
    }
}

Add DatabaseBehaviorAccessible to handle row access based on the active users group, role or authenticity.


<?php declare(strict_types=1);

namespace DoctrineMigrations;

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

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

        $this->addSql('ALTER TABLE additional_field CHANGE name name VARCHAR(255) NOT NULL, CHANGE applies_to applies_to VARCHAR(255) NOT NULL, CHANGE display_name display_name VARCHAR(255) NOT NULL, CHANGE type type VARCHAR(255) NOT NULL, CHANGE type_info type_info VARCHAR(255) DEFAULT NULL');
    }

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

        $this->addSql('ALTER TABLE additional_field CHANGE name name TINYTEXT NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE applies_to applies_to TINYTEXT NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE display_name display_name TINYTEXT NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE type type TINYTEXT NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE type_info type_info LONGTEXT NOT NULL COLLATE utf8mb4_unicode_ci');
    }
}

Add migration which changes the datatypes on the additional fields table and also makes the type info field nullable


<?php
/**
 * @author rugk
 * @copyright Copyright (c) 2015-2016 rugk
 * @license MIT
 */

$EOL="<br>\n";

// method1
$timeStart = microtime();

$ext = new ReflectionExtension('libsodium');
var_dump($ext->getVersion());

$timeEnd = microtime();
echo $EOL.$timeEnd-$timeStart.'s'.$EOL;

// method2
echo $EOL;
$timeStart = microtime();

var_dump(phpversion('libsodium'));

$timeEnd = microtime();
echo $EOL.$timeEnd-$timeStart.'s'.$EOL;

Add libsodium pecl debug script

Add libsodium pecl debug script


<?php

namespace JWX\JWE\KeyAlgorithm;

use JWX\JWE\KeyManagementAlgorithm;
use JWX\JWT\Parameter\AlgorithmParameter;
use JWX\JWK\RSA\RSAPublicKeyJWK;
use JWX\JWK\RSA\RSAPrivateKeyJWK;

/**
 * Key Encryption with RSAES-PKCS1-v1_5
 *
 * @link https://tools.ietf.org/html/rfc7518#section-4.2
 */
class RSAESPKCS1Algorithm implements KeyManagementAlgorithm
{
	/**
	 * Public key
	 *
	 * @var RSAPublicKeyJWK $_publicKey
	 */
	protected $_publicKey;

	/**
	 * Private key
	 *
	 * @var RSAPrivateKeyJWK $_privateKey
	 */
	protected $_privateKey;

	/**
	 * Constructor
	 *
	 * Use fromPublicKey and fromPrivateKey instead!
	 *
	 * @param RSAPublicKeyJWK $pub_key
	 * @param RSAPrivateKeyJWK $priv_key
	 */
	protected function __construct(RSAPublicKeyJWK $pub_key,
		RSAPrivateKeyJWK $priv_key = null) {
		$this->_publicKey = $pub_key;
		$this->_privateKey = $priv_key;
	}

	/**
	 * Initialize from public key
	 *
	 * @param RSAPublicKeyJWK $jwk
	 * @return self
	 */
	public static function fromPublicKey(RSAPublicKeyJWK $jwk) {
		return new self($jwk);
	}

	/**
	 * Initialize from private key
	 *
	 * @param RSAPrivateKeyJWK $jwk
	 * @return self
	 */
	public static function fromPrivateKey(RSAPrivateKeyJWK $jwk) {
		return new self($jwk->publicKey(), $jwk);
	}

	public function encrypt($cek) {
		$key = openssl_pkey_get_public($this->_publicKey->toPEM()->str());
		if (false === $key) {
			throw new \RuntimeException("Failed to load public key");
		}
		$result = openssl_public_encrypt($cek, $crypted, $key,
			OPENSSL_PKCS1_PADDING);
		if (!$result) {
			throw new \RuntimeException("openssl_public_encrypt() failed");
		}
		return $crypted;
	}

	public function decrypt($data) {
		if (!isset($this->_privateKey)) {
			throw new \LogicException("Private key not set");
		}
		$key = openssl_pkey_get_private($this->_privateKey->toPEM()->str());
		if (!$key) {
			throw new \RuntimeException("Failed to load private key");
		}
		$result = openssl_private_decrypt($data, $cek, $key,
			OPENSSL_PKCS1_PADDING);
		if (!$result) {
			throw new \RuntimeException("openssl_private_decrypt() failed");
		}
		return $cek;
	}

	public function algorithmParamValue() {
		return AlgorithmParameter::ALGO_RSA1_5;
	}
}

Add RSA key encryption algorithm

Add RSA key encryption algorithm


<?php

use Phinx\Migration\AbstractMigration;

class Youkok3005 extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $elementTable = $this->table('element');
        $elementTable
            ->removeColumn('owner')
            ->removeColumn('mime_type')
            ->removeColumn('exam')
            ->save();

        $this->dropTable('cache');
        $this->dropTable('contributor');

        $downloadTable = $this->table('download');
        $downloadTable
            ->removeColumn('session')
            ->save();
    }
}

Add migration to delete old data

Add migration to delete old data


<?php

namespace MCordingley\LaravelSapient\Test\Middleware;

use Illuminate\Http\Request;
use MCordingley\LaravelSapient\Test\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * @return Request
     */
    final protected static function createRequest(): Request
    {
        $parameters = '';
        $parsed = [];
        parse_str($parameters, $parsed);

        return Request::create('/foo', 'POST', $parsed, [], [], [], $parameters);
    }
}

Create base test case with test request factory helper.


<?php

use Mockery as m;
use Traktor\Traktor;

class TraktorTest extends \PHPUnit_Framework_TestCase
{

    public function tearDown()
    {
        m::close();
    }

    public function testSettingApiKey()
    {
        $t = new Traktor;
        $t->setApiKey('foobar');

        $this->assertSame('foobar', $t->getApiKey());
    }

    public function testGetRequest()
    {
        $response = json_encode(['foo' => 'bar']);

        $r = m::mock('GuzzleHttp\Message\ResponseInterface');
        $r->shouldReceive('json')->once();

        $c = m::mock('GuzzleHttp\Client');
        $c->shouldReceive('get')->once()->andReturn($r);

        $t = new Traktor;
        $t->setApiKey('foobar');

        $decoded = $t->get('foo.bar');

        $this->assertSame('bar', $decoded->foo);
    }

}

Add unit test for Traktor class.

Add unit test for Traktor class.