<?php
try {
	require ("config.inc.php");
	$db = new PDO("mysql:host=$mysql_server;dbname=$mysql_db;charset=utf8mb4", $mysql_user, $mysql_pass);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$rs = $db->prepare ( "SELECT * FROM `hoods`" );
	$rs->execute ();
} catch ( PDOException $e ) {
	exit($e);
}

$hoods = array();
while ( $result = $rs->fetch ( PDO::FETCH_ASSOC ) ) {
	$hood = array();
	$hood['id']   = intval($result['ID']);
	$hood['name'] = $result['name'];
	$hood['net']  = $result['net'];
	if ($result ['lat'] > 0 && $result ['lon'] > 0) {
		$hood['lat'] = floatval($result['lat']);
		$hood['lon'] = floatval($result['lon']);
	}
	array_push($hoods, $hood);
}

header("Content-Type: application/json");
echo json_encode($hoods, JSON_PRETTY_PRINT);
?>

Add Hood Listing page to keyserver

Add Hood Listing page to keyserver

This will allow monitoring (and other tools) to
maintain a recent list of hoods.

Signed-off-by: Dominik Heidler <aeacd46bb4fd3f59504c7762d9af6bd04f20aa1f@heidler.eu>
Tested-by: Tim Niemeyer <f05b1b469e3796a343710ad6cdd19e106f552175@mastersword.de>


<?php
/**
 *
 * @param array &$hookinfo  hookinfo
 */
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	try {
		$config = SimpleSAML_Configuration::getInstance();
		$consentconfig = $config->copyFromBase('consentSimpleAdminConfig', 'module_consentSimpleAdmin.php');

		// Parse consent config
		$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));

		// Get all consents for user
		$stats = $consent_storage->getStatistics();

		$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.';

	} catch (Exception $e) {
		$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
	}

}
?>

Add sanity check to check if database connection is OK.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@1281 44740490-163a-0410-bde0-09ae8108e29a


<?php
if (!defined('BASEPATH')) {
     exit('No direct script access allowed');
}
#
#  Copyright 2003-2015 Opmantek Limited (www.opmantek.com)
#
#  ALL CODE MODIFICATIONS MUST BE SENT TO CODE@OPMANTEK.COM
#
#  This file is part of Open-AudIT.
#
#  Open-AudIT is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Open-AudIT is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with Open-AudIT (most likely in a file named LICENSE).
#  If not, see <http://www.gnu.org/licenses/>
#
#  For further information on Open-AudIT or for a license other than AGPL please see
#  www.opmantek.com or email contact@opmantek.com
#
# *****************************************************************************

/*
* @category  Helper
* @package   Open-AudIT
* @author    Mark Unwin <marku@opmantek.com>
* @copyright 2014 Opmantek
* @license   http://www.gnu.org/licenses/agpl-3.0.html aGPL v3
* @version   3.3.0
* @link      http://www.open-audit.org
 */

# Vendor Cambium

$get_oid_details = function ($ip, $credentials, $oid) {
    $details = new stdClass();
    $details->model =  my_snmp_get($ip, $credentials, "1.3.6.1.4.1.2281.10.1.2.10.1.1.2.127");
    $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.2281.10.1.2.10.1.1.6.127");
    return($details);
};

Add SNMP serial retrieval for 2281, Cambium devices.


<?php
class Webenq_Form_Questionnaire_AddTest extends Webenq_Test_Form
{
    public function testTitleIsRequired()
    {
        $this->assertFalse($this->_form->isValid(array()));
        $this->assertTrue($this->hasErrors($this->_form->title));
    }
}

Test toegevoegd om te controleren of titel verplicht is bij aanmaken questionnaire


<?php
namespace CouchDB\Tests\Events;

use CouchDB\Tests\TestCase;
use CouchDB\Events\EventArgs;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class EventArgsTest extends TestCase
{
    public function testGetInvoker()
    {
        $invoker = new Dummy();
        $args = new EventArgs($invoker);
        $this->assertEquals($invoker, $args->getInvoker());
        $this->assertEquals('bar', $args->getInvoker()->foo);
        $invoker->foo = 'foobar';
        $this->assertEquals('foobar', $args->getInvoker()->foo);
    }

    public function testGetData()
    {
        $data = 'foo';
        $args = new EventArgs(new Dummy(), $data);
        $this->assertEquals('foo', $args->getData());
    }
}

class Dummy
{
    public $foo = 'bar';
}

Add unit test for event args

Add unit test for event args


<?php namespace Leean\Acf;

/**
 * Class that carries the filters and some util function aroudn this,
 *
 * @since 0.4.0
 */
class Filter {
	const DEFAULT_TRANSFORMS = 'ln_acf_apply_default_transforms';
	const FIELD = 'ln_acf_field';

	public static function parse_suffix( $suffix = '' ) {
		$suffix = strtolower( $suffix );
		$suffix = str_replace( [ '-', '/', '.' ], '_', $suffix );
		return trim( $suffix, ' _' );
	}

	public static function create_name( $base = '', $suffix = '' ) {
		if ( $suffix ) {
			return sprintf( '%s_%s', $base, self::parse_suffix( $suffix ) );
		} else {
			return $base;
		}
	}
}

Add class to generate and carry the filters


<?php

namespace Unicodeveloper\Http\Middleware;

use Closure;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;

class SessionTimeout {

    /**
     * [$session description]
     * @var [type]
     */
    protected $session;

    /**
     * Time for user to remain active, set to 900secs( 15minutes )
     * @var timeout
     */
    protected $timeout = 900;

    public function __construct(Store $session){
        $this->sessiontimeout = $session;
        $this->setConfigOptions();
    }

    private function setConfigOptions()
    {
        $this->lifetime    = Config::get('session.lifetime');
        $this->labelInfo   = Config::get('timeout.labelInfo');
        $this->redirectUrl = Config::get('timeout.redirectUrl');
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(! $this->session->has('lastActivityTime'))
        {
            $this->session->put('lastActivityTime', time());
        }
        else if( time() - $this->session->get('lastActivityTime') > $this->getTimeOut())
        {
            $this->session->forget('lastActivityTime');
            Auth::logout();

            return redirect($this->redirectUrl)->with([ $this->labelInfo => 'You have been inactive for '. $this->timeout/60 .' minutes ago.']);
        }

        $this->session->put('lastActivityTime',time());
        return $next($request);
    }

    /**
     *  Get timeout from laravel default's, if it's not set/empty, set timeout to 15 minutes
     * @return int
     */
    private function getTimeOut()
    {
        return  ($this->lifetime) ?: $this->timeout;
    }

}

[laravel-sessiontimeout] Add Middleware to properly deal with session timeout


<?php

namespace Alchemy\Zippy\Tests\Resource;

use Alchemy\Zippy\Tests\TestCase;
use Alchemy\Zippy\Resource\TeleporterContainer;

class TeleporterContainerTest extends TestCase
{
    /**
     * @covers Alchemy\Zippy\Resource\TeleporterContainer::fromResource
     * @dataProvider provideResourceData
     */
    public function testFromResource($resource, $classname)
    {
        $container = TeleporterContainer::load();

        $this->assertInstanceOf($classname, $container->fromResource($resource));
    }
    /**
     * @covers Alchemy\Zippy\Resource\TeleporterContainer::fromResource
     * @expectedException Alchemy\Zippy\Exception\InvalidArgumentException
     */
    public function testFromResourceThatFails()
    {
        $container = TeleporterContainer::load();
        $container->fromResource($this->createResource(array()));
    }

    public function provideResourceData()
    {
        return array(
            array($this->createResource(__FILE__), 'Alchemy\Zippy\Resource\Teleporter\LocalTeleporter'),
            array($this->createResource(fopen(__FILE__, 'rb')), 'Alchemy\Zippy\Resource\Teleporter\StreamTeleporter'),
            array($this->createResource('ftp://192.168.1.1/images/elephant.png'), 'Alchemy\Zippy\Resource\Teleporter\StreamTeleporter'),
            array($this->createResource('http://www.google.com/+/business/images/plus-badge.png'), 'Alchemy\Zippy\Resource\Teleporter\GuzzleTeleporter'),
        );
    }

    private function createResource($data)
    {
        $resource = $this->getMockBuilder('Alchemy\Zippy\Resource\Resource')
            ->disableOriginalConstructor()
            ->getMock();

        $resource->expects($this->any())
            ->method('getOriginal')
            ->will($this->returnValue($data));

        return $resource;
    }

    /**
     * @covers Alchemy\Zippy\Resource\TeleporterContainer::load
     */
    public function testLoad()
    {
        $container = TeleporterContainer::load();

        $this->assertInstanceOf('Alchemy\Zippy\Resource\TeleporterContainer', $container);

        $this->assertInstanceOf('Alchemy\Zippy\Resource\Teleporter\GuzzleTeleporter', $container['guzzle-teleporter']);
        $this->assertInstanceOf('Alchemy\Zippy\Resource\Teleporter\StreamTeleporter', $container['stream-teleporter']);
        $this->assertInstanceOf('Alchemy\Zippy\Resource\Teleporter\LocalTeleporter', $container['local-teleporter']);
    }
}

Add unit tests for TeleporterContainer

Add unit tests for TeleporterContainer


<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Core\Data\Stack\Attribute;

class Date extends Date\__Parent
{

    static $mysql_format = 'Y-m-d H:i:s';
    static $mysql_format_regex = '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/';

    /*************************************************************************
    PUBLIC USER METHODS
     *************************************************************************/
    public function get()
    {
        return \DateTime::createFromFormat($this->mysql_format, $this->seed);
    }

    public function set($value)
    {
        if (static::isValid($value)) {
            $this->seed = $value;
        } else if (is_a($value, 'DateTime')) {
            $this->seed = $value->format($this->mysql_format);
        }
    }

    public function setNow()
    {
        $this->seed = (new \DateTime)->format($this->mysql_format);
    }

    public static function isValid($value)
    {
        if (is_string($value)) {
            if (preg_match(static::mysql_format_regex, $value, $matches)) {
                if (checkdate($matches[2], $matches[3], $matches[1])) {
                    return TRUE;
                }
            }
        }
    }

    /*************************************************************************
    DEBUG METHODS
     *************************************************************************/
    public function __toString()
    {
        return '' . $this->getSeed();
    }
}

Allow to set redirection after logout

Allow to set redirection after logout


<?php

use \PHPUnit\Framework\TestCase;
use \AdobeConnectClient\Helpers\HeaderParse;

class HeaderParseTest extends TestCase
{

    protected $cookieName = 'BREEZESESSION';
    protected $cookieValue = 'na9breezx3385yw9ymhhzb5p';
    protected $headerLine = '';

    protected function setUp()
    {
        parent::setUp();
        $this->headerLine = "{$this->cookieName}={$this->cookieValue};HttpOnly;domain=.adobeconnect.com;secure;path=/";
    }

    public function testHeaderParseString()
    {
        $parsed = HeaderParse::parse($this->headerLine);
        $this->assertEquals($this->cookieValue, $parsed[0][$this->cookieName]);
    }

    public function testHeaderParseArray()
    {
        $parsed = HeaderParse::parse([$this->headerLine]);
        $this->assertEquals($this->cookieValue, $parsed[0][$this->cookieName]);
    }

    public function testHeaderParseArrayComma()
    {
        $parsed = HeaderParse::parse(
            [
                "{$this->cookieName}={$this->cookieValue},HttpOnly,domain=.adobeconnect.com,secure,path=/,t=a;b;c"
            ]
        );
        $this->assertEquals($this->cookieValue, $parsed[0][$this->cookieName]);
    }
}

Create test for HeaderParse helper

Create test for HeaderParse helper


<?php

// src/AppBundle/Command/CreateUserCommand.php

namespace HCH\DemoBundle\Command;

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

class CreateErrorCodeCommand extends Command {

  protected function configure() {
    $this
            // the name of the command (the part after "bin/console")
            ->setName('app:create-error-code')

            // the short description shown while running "php bin/console list"
            ->setDescription('Create code error file.')

            // the full command description shown when running the command with
            // the "--help" option
            ->setHelp("This command allows you to create code error file")
    ;
  }

  protected function execute(InputInterface $input, OutputInterface $output) {

    $content = "; this is an INI file \n [parameters] \n \n ;code 500 \n 501 = An intenal error has occured";
    $fp = fopen(__DIR__ . '../../../../../app/config/errors_code.ini', "wb");
    fwrite($fp, $content);
    fclose($fp);

  }

}

Add Command to create the errors_code file


<?php
/*
 * AJAX endpoint to check if a site is using CloudFlare
 */

// Load all of net/http's classes. Composer would be overkill for such a small tool.
require 'includes/net-http/src/Net/Http.php';
require 'includes/net-http/src/Net/Http/Client.php';
require 'includes/net-http/src/Net/Http/Exception.php';
require 'includes/net-http/src/Net/Http/ProtocolError.php';
require 'includes/net-http/src/Net/Http/ClientError.php';
require 'includes/net-http/src/Net/Http/NetworkError.php';
require 'includes/net-http/src/Net/Http/Request.php';
require 'includes/net-http/src/Net/Http/Response.php';
require 'includes/net-http/src/Net/Http/ServerError.php';

function cleanURL($url) {
    // Remove http(s) at beginning (will be readded later)
    if (substr($url, 0, strlen('http://')) == 'http://') {
        $url = substr($url, strlen('http://'));
    } elseif (substr($url, 0, strlen('https://')) == 'https://') {
        $url = substr($url, strlen('https://'));
    }

    // Remove path after URL, if exists
    if (strpos($url, '/')) {
        $url = substr($url, 0, strpos($url, '/'));
    }

    // Re-add protocol to URL
    $url = 'http://' . $url; // no ssl is required for this check

    return $url;
}

function checkSite($url) {
    $checkURL = $url . '/cdn-cgi/trace';

    // Make request to confirm
    try {
        $request = new Net_Http_Client();
        $request->setVerifyPeer(false); // verifying ssl is not really required here
        $request->get($checkURL);

        if ($request->getStatus() != 200) {
            return false; // didn't return a successful response to debug cdn url - not on CloudFlare
        } elseif ($request->getHeader('Server') != 'cloudflare-nginx') {
            return false; // doesn't have the CloudFlare server field set
        }

        // All tests passed!
        return true;
    } catch (Exception $e) {
        // Some sort of problem occurred!
        die(json_encode(array(
            'status' => false,
            'message' => 'Couldn\'t connect to target!'
        )));
    }
}

// Response comes in JSON
header('Content-Type: application/json');

if (!isset($_GET['url'])) {
    // Missing URL argument
    die(json_encode(array(
        'status' => false,
        'message' => 'Invalid request'
    )));
}

$onCloudflare = !!checkSite( cleanURL($_GET['url']) );

echo json_encode(array(
    'status' => true,
    'on_cloudflare' => $onCloudflare
));

Add AJAX endpoint for getting a sites CloudFlare status


<?php

namespace ProcessWire\GraphQL\Field\Page\Fieldtype;

use ProcessWire\GraphQL\Field\Page\Fieldtype\AbstractFieldtype;
use ProcessWire\Page;

class FieldtypeThirdParty extends AbstractFieldtype {

	public function __construct($class, $field)
	{
		$this->class = $class;
		parent::__construct($field);
	}

	public function getName()
	{
		return $this->class::getName();
	}

	public function getDefaultType()
	{
		$this->class::getType();
	}

	public function getInputfieldType($type = null)
	{
		return $this->class::getInputType();
	}

	public function setValue(Page $page, $value)
	{
		return $this->class::setValue($page, $this->field, $value);
	}

}

Create third party fieldtype supporter class.


<?php

use Fhaculty\Graph\Algorithm\TopologicalSort;
use Fhaculty\Graph\Exception\UnexpectedValueException;
use Fhaculty\Graph\Edge\Base as Edge;
use Fhaculty\Graph\Graph;

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

        $alg = new TopologicalSort($graph);

        $this->assertSame(array(), $alg->getVertices());
    }

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

        $alg = new TopologicalSort($graph);

        $this->assertSame(array(1 => $graph->getVertex(1), 2 => $graph->getVertex(2)), $alg->getVertices());
    }

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

        $alg = new TopologicalSort($graph);

        $this->assertSame(array(1 => $graph->getVertex(1), 2 => $graph->getVertex(2)), $alg->getVertices());
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testFailUndirected()
    {
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));

        $alg = new TopologicalSort($graph);
        $alg->getVertices();
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testFailLoop()
    {
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($graph->getVertex(1));

        $alg = new TopologicalSort($graph);
        $alg->getVertices();
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testFailCycle()
    {
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($graph->createVertex(2));
        $graph->getVertex(2)->createEdgeTo($graph->getVertex(1));

        $alg = new TopologicalSort($graph);
        $alg->getVertices();
    }
}

Add basic unit tests for TopologicalSort


<?php

$rowList = CM_Db_Db::select('cm_log', '*')->fetchAll();
foreach ($rowList as $row) {
    $metaInfo = @unserialize($row['metaInfo']);

    if (is_array($metaInfo)) {
        $metaInfo = Functional\map($metaInfo, function ($value) {
            return CM_Util::varDump($value, ['recursive' => true]);
        });
    } else {
        $metaInfo = null;
    }

    CM_Db_Db::update('cm_log', ['metaInfo' => serialize($metaInfo)], ['id' => $row['id']]);
}

Add migration for existing log metaInfo entries


<?php

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

class m141121_115523_update_table_phpbb_users extends Migration
{
    private $_table     = 'phpbb_users';
    private $_column    = 'yii_password';

    public function up()
    {
        $this->addColumn($this->_table, $this->_column, Schema::TYPE_STRING . ' NOT NULL');
    }

    public function down()
    {
        $this->dropColumn($this->_table, $this->_column);
    }
}

Add migration for phpbb_users table

Add migration for phpbb_users table


<?php
require_once 'portabilityLayer.php';

if (!sys_get_temp_dir()) {
    echo "FAIL: No temp dir was returned.\n";
    exit();
}

$tmpFile = sys_get_temp_dir() . "/" . $_GET['filename'];

$stat = stat($tmpFile);
if (!$stat) {
    echo "FAIL: stat() call failed.\n";
    exit();
}

$mtime = $stat['mtime'] + 1;

if (!touch($tmpFile, $mtime)) {
    echo "FAIL: touch() call failed.\n";
}
?>

<?php
require_once 'portabilityLayer.php';

if (!sys_get_temp_dir()) {
    echo "FAIL: No temp dir was returned.\n";
    exit();
}

$tmpFile = sys_get_temp_dir() . "/" . $_GET['filename'];

$stat = stat($tmpFile);
if (!$stat) {
    echo "FAIL: stat() call failed.\n";
    exit();
}

$mtime = $stat['mtime'] + 2;

if (!touch($tmpFile, $mtime)) {
    echo "FAIL: touch() call failed.\n";
}
?>

Advance mtime by two seconds when touching a temporary file.

In send-sliced-dragged-file.html layout test, an unstable file is
simulated by touching the file being uploaded and advancing its mtime by
one second. An error of around one second may be lost in rounding errors
due to lossy conversions of timestamps between Blink and Chrome. Advance
the mtime by 2 seconds to compensate.

BUG=426465

Review URL: https://codereview.chromium.org/895173002

git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@189515 bbb929c8-8fbe-4397-9dbb-9b2b20218538


<?php namespace Flarum\Support;

use Illuminate\Contracts\Bus\Dispatcher;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Response;

abstract class HtmlAction extends Action
{
    public function handle(Request $request, $routeParams = [])
    {
        $view = $this->render($request, $routeParams);

        $response = new Response();
        $response->getBody()->write($view->render());
        return $response;
    }

    /**
     * @param Request $request
     * @param array $routeParams
     * @return \Illuminate\Contracts\View\View
     */
    abstract protected function render(Request $request, $routeParams = []);
}

Add another abstract action base class for dealing with returned views


<?php

namespace Gh\SimpleShopBundle\Command;

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

class ImportPriceCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('import:price')
            ->setDescription('Import xml price from root of project')
            ->addArgument('name', InputArgument::OPTIONAL, 'The name of price from root of project', 'price.xml')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        $progress = $this->getHelperSet()->get('progress');
        $importer = $this->getContainer()->get('gh.simple_shop.import_price');

        $importer->importPriceFile($name);
        $count = $importer->getNodesCount();

        $progress->start($output, $count+1);

        for ($i=0; $i < $count; $i++) {
            $importer->importNode($i);
            $importer->nextNode();

            $progress->advance();
        }

        $importer->flush();
        $progress->advance();

        $progress->finish();

        $output->writeln('Price is imported successfully!');
    }
}

Add command line sevice for import price


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiWebfontsService.php';

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

// Visit https://code.google.com/apis/console?api=webfonts
// to generate your developer key.
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiWebfontsService($client);
$fonts = $service->webfonts->listWebfonts();
print "
Fonts

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

Add a sample application for the webfonts API.


<?php
namespace Tests\Extensions\Gedmo\Timestampable;

use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
use Gedmo\Timestampable\Mapping\Driver\Fluent as Timestampable;
use LaravelDoctrine\Fluent\Builders\Builder;
use LaravelDoctrine\Fluent\Builders\Field;
use LaravelDoctrine\Fluent\Extensions\ExtensibleClassMetadata;
use LaravelDoctrine\Fluent\Extensions\Gedmo\AbstractTrackingExtension;
use LaravelDoctrine\Fluent\Extensions\Gedmo\Timestampable\Extension;
use PHPUnit_Framework_TestCase;
use Tests\Extensions\Gedmo\TrackingExtensions;

class ExtensionTest extends PHPUnit_Framework_TestCase
{
    use TrackingExtensions;

    /**
     * @var Extension
     */
    private $extension;

    protected function setUp()
    {
        $this->fieldName     = 'ip';
        $this->classMetadata = new ExtensibleClassMetadata('foo');
        $this->extension     = new Extension($this->classMetadata, $this->fieldName);
    }

    public function test_it_should_add_itself_as_a_field_macro()
    {
        Extension::enable();

        $field = Field::make(new ClassMetadataBuilder(new ExtensibleClassMetadata('Foo')), 'string', $this->fieldName);

        $this->assertInstanceOf(
            Extension::class,
            call_user_func([$field, Extension::MACRO_METHOD])
        );

        $builder = new Builder($cmb = new ClassMetadataBuilder(new ExtensibleClassMetadata('Foo')));

        $this->assertNull(
            call_user_func([$builder, 'timestamps'])
        );
    }

    /**
     * @return AbstractTrackingExtension
     */
    protected function getExtension()
    {
        return $this->extension;
    }

    /**
     * @return string
     */
    protected function getExtensionName()
    {
        return Timestampable::EXTENSION_NAME;
    }
}

Add test for timestampable extension

Add test for timestampable extension


<?php

namespace Swarrot\Processor\RPC;

use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTestCase;
use Swarrot\Broker\Message;

class RpcClientProcessorTest extends ProphecyTestCase
{
    public function test_it_is_initializable_without_a_logger()
    {
        $processor = new RpcClientProcessor();
        $this->assertInstanceOf('Swarrot\\Processor\\RPC\\RpcClientProcessor', $processor);
    }

    public function test_it_is_initializable_with_a_logger()
    {
        $logger = $this->prophesize('Psr\\Log\\LoggerInterface');

        $processor = new RpcClientProcessor(null, $logger->reveal());
        $this->assertInstanceOf('Swarrot\\Processor\\RPC\\RpcClientProcessor', $processor);
    }

    public function test_it_is_initializable_with_a_processor()
    {
        $processor = $this->prophesize('Swarrot\\Processor\\ProcessorInterface');

        $processor = new RpcClientProcessor($processor->reveal());
        $this->assertInstanceOf('Swarrot\\Processor\\RPC\\RpcClientProcessor', $processor);
    }

    public function test_it_is_initializable_with_a_processor_and_a_logger()
    {
        $processor = $this->prophesize('Swarrot\\Processor\\ProcessorInterface');
        $logger = $this->prophesize('Psr\\Log\\LoggerInterface');

        $processor = new RpcClientProcessor($processor->reveal(), $logger->reveal());
        $this->assertInstanceOf('Swarrot\\Processor\\RPC\\RpcClientProcessor', $processor);
    }

    public function test_it_should_sleep_if_no_correlation_id_set()
    {
        $processor = new RpcClientProcessor;
        $this->assertNull($processor->process(new Message, []));
    }

    public function test_it_should_sleep_if_invalid_correlation_id()
    {
        $processor = new RpcClientProcessor;
        $message = new Message(null, ['correlation_id' => 1]);

        $this->assertNull($processor->process($message, ['rpc_client_correlation_id' => 0]));
        $this->assertTrue($processor->sleep([]));
    }

    public function test_it_should_stop_if_correct_correlation_id()
    {
        $processor = new RpcClientProcessor;
        $message = new Message(null, ['correlation_id' => 1]);

        $this->assertNull($processor->process($message, ['rpc_client_correlation_id' => 1]));
        $this->assertFalse($processor->sleep([]));
    }

    public function test_it_should_let_the_nested_processor_act_and_stop_if_correct_correlation_id()
    {
        $message = new Message(null, ['correlation_id' => 1]);

        $processor = $this->prophesize('Swarrot\\Processor\\ProcessorInterface');
        $processor->process($message, ['rpc_client_correlation_id' => 1])->willReturn(true)->shouldBeCalled();
        $processor = new RpcClientProcessor($processor->reveal());

        $this->assertTrue($processor->process($message, ['rpc_client_correlation_id' => 1]));
        $this->assertFalse($processor->sleep([]));
    }
}

[RPC] Add some tests for the RPC Client processor


<?php

namespace mcordingley\Regression\Tests\Algorithm\GradientDescent\Schedule;

use mcordingley\Regression\Algorithm\GradientDescent\Schedule\Fixed;
use PHPUnit_Framework_TestCase;

class FixedTest extends PHPUnit_Framework_TestCase
{
    public function testStep()
    {
        $schedule = new Fixed(1.0);
        $schedule->update([1.0]);
        static::assertEquals(1.0, $schedule->step(0));
    }
}

Test the fixed gradient schedule.

Test the fixed gradient schedule.


<?php

namespace Backend\Modules\Tags\Tests\Engine;

use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Tags\Engine\Model;
use Common\WebTestCase;

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

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

        $client = self::createClient();
        $this->loadFixtures($client);
    }
}

Add class to test backend tags model

Add class to test backend tags model


<?php

namespace ZendTest\Code\TestAsset;

class NullableReturnTypeHintedClass
{
    public function arrayReturn() : ?array
    {
    }

    public function callableReturn() : ?callable
    {
    }

    public function intReturn() : ?int
    {
    }

    public function floatReturn() : ?float
    {
    }

    public function stringReturn() : ?string
    {
    }

    public function boolReturn() : ?bool
    {
    }

    public function selfReturn() : ?self
    {
    }

    public function classReturn() : ?ReturnTypeHintedClass
    {
    }

    public function otherClassReturn() : ?InternalHintsClass
    {
    }
}

Test asset: class with nullable return types


<?php

namespace BlueChip\Security\Tests\Integration\Cases\Modules\Hardening;

use BlueChip\Security\Modules\IpBlacklist;
use BlueChip\Security\Tests\Integration\TestCase;

class BouncerTest extends TestCase
{
    /**
     * Ensure that blocking access results in wp_die() being called with proper response code.
     */
    public function testBlockAccessTemporarily()
    {
        try {
            IpBlacklist\Bouncer::blockAccessTemporarily();
        } catch (\WPDieException $exception) {
            $this->assertSame(503, $exception->getCode());
        }
    }
}

Add simple test for Bouncer::blockAccessTemporarily() method


<?php
/**
 * @copyright Copyright (C) 2015-2018 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 * @author ShingoMisawa <33051481+shngmsw@users.noreply.github.com>
 */

declare(strict_types=1);

use app\components\db\Migration;
use yii\db\Query;

class m181106_083644_fix_jetsweeper_special extends Migration
{
    public function safeUp()
    {
        $this->update(
            'weapon2',
            ['special_id' => $this->getSpecialId('missile')],
            ['key' => 'jetsweeper']
        );
    }

    public function safeDown()
    {
        $this->update(
            'weapon2',
            ['special_id' => $this->getSpecialId('jetpack')],
            ['key' => 'jetsweeper']
        );
    }

    private function getSpecialId(string $key): int
    {
        $query = (new Query())
            ->select(['id'])
            ->from('special2')
            ->where(['key' => $key])
            ->limit(1);

        if (!$value = $query->scalar()) {
            throw new \Exception("Unknown special: {$key}");
        }

        return (int)$value;
    }
}

Fix Jet Squelcher's special weapon

Fix Jet Squelcher's special weapon

fix #377, #378

Signed-off-by: AIZAWA Hina <07c779d48779c322a7c5324109202f9012f7aebf@bouhime.com>


<?php

use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

final class HeartbeatController extends WebTestCase
{
    /**
     * @var Client
     */
    private $client;

    public function setUp()
    {
        $this->client = static::createClient();
    }

    /**
     * @test
     * @group Api
     */
    public function engineblock_has_a_heartbeat()
    {
        $this->client->request('GET', 'https://engine-api.vm.openconext.org/');
        $this->assertStatusCode(200, $this->client);
    }
}

Add heartbeat test using LiipFunctionalTestBundle


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\CommandHandling;

use Broadway\CommandHandling\CommandBusInterface;
use Broadway\CommandHandling\CommandHandlerInterface;
use Broadway\Domain\Metadata;

class SimpleContextAwareCommandBus implements CommandBusInterface, ContextAwareInterface
{
    /**
     * @var Metadata
     */
    protected $context;

    /**
     * @var CommandHandlerInterface
     */
    private $commandHandlers = array();

    public function setContext(Metadata $context = null)
    {
        $this->context = $context;
    }

    /**
     * {@inheritDoc}
     */
    public function subscribe(CommandHandlerInterface $handler)
    {
        $this->commandHandlers[] = $handler;
    }

    /**
     * {@inheritDoc}
     */
    public function dispatch($command)
    {
        /** @var CommandHandlerInterface|ContextAwareInterface $handler */
        foreach ($this->commandHandlers as $handler) {
            if ($handler instanceof ContextAwareInterface) {
                $handler->setContext($this->context);
            }
            $handler->handle($command);
        }
    }
}

Add a simple context-aware command bus

Add a simple context-aware command bus


<?php

namespace RcmMessage\Api;

use RcmMessage\Entity\MessageInterface;

/**
 * @author James Jervis - https://github.com/jerv13
 */
class PrepareMessageForDisplayMessageParams implements PrepareMessageForDisplay
{
    const PROPERTY_MESSAGE_PARAMS = 'message-params';

    /**
     * @param MessageInterface $message
     * @param array            $options
     *
     * @return MessageInterface
     */
    public function __invoke(
        MessageInterface $message,
        array $options = []
    ): MessageInterface {
        $properties = $message->getProperties();

        $messageParams = [];

        if (array_key_exists(self::PROPERTY_MESSAGE_PARAMS, $properties)) {
            $messageParams = (array)$properties[self::PROPERTY_MESSAGE_PARAMS];
        }

        $subject = $message->getSubject();
        $messageStr = $message->getMessage();

        foreach ($messageParams as $param => $messageParam) {
            $subject = str_replace(
                '{' . $param . '}',
                $messageParam,
                $subject
            );

            $messageStr = str_replace(
                '{' . $param . '}',
                $messageParam,
                $messageStr
            );
        }

        $message->setSubject(
            $subject
        );

        $message->setMessage(
            $messageStr
        );

        return $message;
    }
}

Update for PSR and abstract parts

Update for PSR and abstract parts


<?php
/*
 *	Made by Samerton
 *  https://github.com/samerton
 *  NamelessMC version 2.0.0-pr3
 *  License: MIT
 *
 *  Translated by brzezinsky
 *
 *  Polish Language - Plik językowy dla szablonu domyślnego dla NamelessMC
 *  English Language - Language file for default themes for NamelessMC
 */

// Which version of NamelessMC is this language file updated to?
$language_version = '2.0.0-pr5';

$language = array(
	'default_theme_title' => 'Domyślny motyw',
	'theme' => 'Motyw',
	'navbar_style' => 'Styl paska nawigacyji',
	'navbar_colour' => 'Kolor paska nawigacyji'
);

Add DefaultThemes Polish translation, credit brzezinsky


<?php
/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */

namespace VinceT\AdminBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;
use VinceT\AdminBundle\Menu\MenuItem;

/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */
class DumpMenuCommand extends ContainerAwareCommand
{
    /**
     * configure command
     *
     * @return null
     */
    protected function configure()
    {
        parent::configure();
        $this
            ->setName('vincet:admin:dump-menu')
            ->setDescription('Dump the admin menu')
            ->setHelp(
<<<EOF
The <info>vincet:admin:dump-menu</info> command dumps the admin menu.
EOF
            );
    }

    /**
     * execute command
     *
     * @param InputInterface  $input  InputInterface instance
     * @param OutputInterface $output OutputInterface instance
     *
     * @return null
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $menuBuilder = $this->getContainer()->get('vince_t.admin.menu.builder');

        $menu = $menuBuilder->createMainMenu(new Request());

        $this->_printMenu($output, $menu);
    }

    /**
     * [_printMenu description]
     *
     * @param OutputInterface $output [description]
     * @param MenuItem        $menu   [description]
     * @param integer         $depth  [description]
     *
     * @return [type]
     */
    private function _printMenu(OutputInterface $output, MenuItem $menu, $depth = 0)
    {
        $prefix = '';
        if ( $depth != 0 ) {
            $prefix = '|->';
            if ( $depth > 1 ) {
                $prefix = str_repeat('    ', $depth - 1).$prefix;
            }
        }
        $line = sprintf(
            '%s <info>%s</info> : <comment>%s</comment>',
            $prefix,
            $menu->getName(),
            $menu->getUri()
        );
        $output->writeln($line);
        foreach ($menu->getChildren() as $child) {
            $this->_printMenu($output, $child, $depth+1);
        }
    }
}

Add command to dump the admin menu

Add command to dump the admin menu


<?php
namespace Intellias\TestBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class ExceptionListener
{
    protected $templating;
    protected $kernel;

    public function __construct(EngineInterface $templating, $kernel)
    {
        $this->templating = $templating;
        $this->kernel = $kernel;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ('prod' == $this->kernel->getEnvironment()){
            $exception = $event->getException();
            $response = new Response();
            $response->setContent(
                $this->templating->render(
                    '::exception.html.twig',
                    array('exception' => $exception)
                )
            );
            if ($exception instanceof HttpExceptionInterface) {
                $response->setStatusCode($exception->getStatusCode());
                $response->headers->replace($exception->getHeaders());
            } else {
                $response->setStatusCode(500);
            }
            $event->setResponse($response);
        }
    }
}

Deploy source code on git server

Deploy source code on git server


<?php
namespace PhpBrew\Command;

use PhpBrew\Config;
use PhpBrew\Utils;

class EnvCommand extends \CLIFramework\Command
{
    public function brief()
    {
        return 'Export environment variables';
    }

    public function execute($buildName = NULL)
    {
        // get current version
        if (!$buildName) {
            $buildName = getenv('PHPBREW_PHP');
        }

        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $home = Config::getPhpbrewHome();
        $lookup = getenv('PHPBREW_LOOKUP_PREFIX');

        $this->logger->writeln("export PHPBREW_ROOT=$root");
        $this->logger->writeln("export PHPBREW_HOME=$home");
        $this->logger->writeln("export PHPBREW_LOOKUP_PREFIX=$lookup");

        if ($buildName !== false) {
            // checking php version existence
            $targetPhpBinPath = Config::getVersionBinPath($buildName);
            if (is_dir($targetPhpBinPath)) {
                echo 'export PHPBREW_PHP=' . $buildName . "\n";
                echo 'export PHPBREW_PATH=' . ($buildName ? Config::getVersionBinPath($buildName) : '') . "\n";
            }
        }

    }
}

<?php
namespace PhpBrew\Command;

use PhpBrew\Config;
use PhpBrew\Utils;

class EnvCommand extends \CLIFramework\Command
{
    public function brief()
    {
        return 'Export environment variables';
    }

    public function execute($buildName = NULL)
    {
        // get current version
        if (!$buildName) {
            $buildName = getenv('PHPBREW_PHP');
        }

        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $home = Config::getPhpbrewHome();
        $lookup = getenv('PHPBREW_LOOKUP_PREFIX');

        $this->logger->writeln("export PHPBREW_ROOT=$root");
        $this->logger->writeln("export PHPBREW_HOME=$home");
        $this->logger->writeln("export PHPBREW_LOOKUP_PREFIX=$lookup");

        if ($buildName !== false) {
            // checking php version existence
            $targetPhpBinPath = Config::getVersionBinPath($buildName);
            if (is_dir($targetPhpBinPath)) {
                echo 'export PHPBREW_PHP=' . $buildName . "\n";
                echo 'export PHPBREW_PATH=' . ($buildName ? Config::getVersionBinPath($buildName) : '') . "\n";
            }
        }
        $this->logger->writeln('# Run this command to configure your shell:');
        $this->logger->writeln('# # eval "$(phpbrew env)"');
    }
}

Add help message comment to env command

Add help message comment to env command


<?php
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
 *
 * 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.
 */

namespace Entities;

use Nestor\Entities\ExecutionTypes;
use \TestCase;

class ExecutionTypesTest extends TestCase
{

    public function setUp() {
        parent::setUp();
        $this->createApplication();
    }

    public function testClassAttributes() {
        $fillable = ['name', 'description'];
        $hidden = [];

        $executionType = new ExecutionTypes();
        $this->assertEquals($fillable, $executionType->getFillable());

        $this->assertEquals($hidden, $executionType->getHidden());
    }
}

Test for execution types entity

Test for execution types entity


<?php
	#
	# $Id: category-listing.php,v 1.1.2.1 2006-08-02 17:45:09 dan Exp $
	#
	# Copyright (c) 2006 DVL Software Limited
	#

// base class for listing the categories
class Categories {

	var $category_id;

	var $result;

	function Categories($dbh) {
		$this->dbh	= $dbh;
	}

	function GetAllCategoriesOnWatchLists($UserID) {
		$sql = "
   SELECT distinct C.id AS category_id
     FROM watch_list WL, watch_list_element WLE, categories C
    WHERE WL.user_id     = $UserID
      AND WL.id          = WLE.watch_list_id
      AND WLE.element_id = C.element_id";

#		echo "
sql = '$sql'

";

		$this->result = pg_query($this->dbh, $sql);
		if ($this->result) {
			$numrows = pg_numrows($this->result);
		} else {
			$numrows = 0;
		}

        return $numrows;
	}

	function FetchNth($N) {
		#
		# call GetAllCategoriesOnWatchLists first.
		# then call this function N times, where N is the number
		# returned by GetAllCategoriesOnWatchLists.
		#

		$myrow = pg_fetch_array($this->result, $N);

		$this->category_id = $myrow['category_id'];
	}
}
?>

Add a method for grapping the categories on your watch list

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3736 46e82423-29d8-e211-989e-002590a4cdd4


<?php

namespace Mapbender\CoreBundle\Command;

use Mapbender\CoreBundle\Asset\ApplicationAssetCache;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 *
 * @author Christian Wygoda
 * @deprecated should be removed in release/3.0.6
 */
class DumpMapbenderAssetsCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setDescription('Dump all Mapbender application assets.')
            ->setHelp(<<<EOT
The <info>mapbender:assets:dump</info> dumps all Mapbender application assets.
EOT
            )
            ->setName('mapbender:assets:dump');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $mapbender = $this->getContainer()->get('mapbender');
        $extraProviders = array(
            'Mapbender\CoreBundle\Component\Application',
            'Mapbender\WmsBundle\Entity\WmsInstance',
        );
        $assetProviders = array_merge(
            $mapbender->getElements(),
            $mapbender->getTemplates(),
            $mapbender->getLayers(),
            $extraProviders);

        $assets = array();
        foreach($assetProviders as $provider) {
            $providerAssets = array();
            foreach($provider::listAssets() as $type => $files) {
                if($type === 'trans') {
                    continue;
                }

                $providerAssets[$type] = array();
                foreach($files as $file) {
                    $reference = $this->getReference($provider, $file);
                    $providerAssets[$type][] = $reference;
                }
            }
            $assets = array_merge_recursive($assets, $providerAssets);
        }
        $assets = array_map(function(&$items) {
            return array_unique($items);
        }, $assets);

        foreach($assets as $type => $items) {
            $output->writeln(sprintf('Considering %d assets of type %s...', count($items), $type));
            $cache = new ApplicationAssetCache($this->getContainer(), $items, $type, true);
            $assets = $cache->fill();
        }
    }

    /**
     * Build an Assetic reference path from a given objects bundle name(space)
     * and the filename/path within that bundles Resources/public folder.
     *
     * @todo     : This is duplicated from Component\Application
     *
     * @param        $class
     * @param string $file
     * @return string
     * @internal param object $object
     */
    private function getReference($class, $file)
    {
        // If it starts with an @ we assume it's already an assetic reference
        if ($file[0] !== '@') {
            $namespaces = explode('\\', $class);
            $bundle = sprintf('%s%s', $namespaces[0], $namespaces[1]);
            return sprintf('@%s/Resources/public/%s', $bundle, $file);
        } else {
            return $file;
        }
    }
}

Add deprecation comment to "generate:*" commands


<?php

namespace OpenDominion\Tests\Unit\Calculators\Networth;

use Mockery as m;
use OpenDominion\Calculators\Networth\UnitNetworthCalculator;
use OpenDominion\Models\Unit;
use OpenDominion\Tests\BaseTestCase;

class UnitNetworthCalculatorTest extends BaseTestCase
{
    public function testCalculateMethod()
    {
        $unit1 = m::mock(Unit::class);
        $unit2 = m::mock(Unit::class);
        $unit3 = m::mock(Unit::class);
        $unit4 = m::mock(Unit::class);

        $unitNetworthCalculator = new UnitNetworthCalculator();

        $unit1->shouldReceive('getAttribute')->with('slot')->andReturn(1);
        $unit2->shouldReceive('getAttribute')->with('slot')->andReturn(2);
        $unit3->shouldReceive('getAttribute')->with('slot')->andReturn(3);
        $unit3->shouldReceive('getAttribute')->with('power_offense')->times(3)->andReturn(2);
        $unit3->shouldReceive('getAttribute')->with('power_defense')->times(3)->andReturn(6);
        $unit4->shouldReceive('getAttribute')->with('slot')->andReturn(4);
        $unit4->shouldReceive('getAttribute')->with('power_offense')->times(3)->andReturn(6);
        $unit4->shouldReceive('getAttribute')->with('power_defense')->times(3)->andReturn(3);

        $this->assertEquals(5, $unitNetworthCalculator->calculate($unit1));
        $this->assertEquals(5, $unitNetworthCalculator->calculate($unit2));
        $this->assertEquals(11.7, $unitNetworthCalculator->calculate($unit3));
        $this->assertEquals(12.15, $unitNetworthCalculator->calculate($unit4));
    }
}

Add unit networth calculator test

Add unit networth calculator test


<?php

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

namespace Rocketeer\Services\Config\Files;

use Rocketeer\TestCases\RocketeerTestCase;
use Symfony\Component\Finder\Finder;

class ConfigurationLoaderTest extends RocketeerTestCase
{
    public function testCanCacheConfigurationAndInvalidateIt()
    {
        $folder = $this->replicateConfiguration();
        $filepath = $folder.'/config.php';
        $originalContents = file_get_contents($filepath);

        // Check that we can cache configuration
        $config = $this->configurationLoader->getConfiguration();
        $this->assertEquals('{application_name}', $config['config']['application_name']);
        touch($filepath, time() - 5);
        $this->assertTrue($this->configurationLoader->getCache()->isFresh());

        // Check that we can invalidate it
        file_put_contents($filepath, str_replace('{application_name}', 'foobar', $originalContents));
        $this->assertFalse($this->configurationLoader->getCache()->isFresh());

        $config = $this->configurationLoader->getConfiguration();
        touch($filepath, time() - 5);
        $this->assertTrue($this->configurationLoader->getCache()->isFresh());
        $this->assertEquals('foobar', $config['config']['application_name']);

        // Revert changes
        file_put_contents($filepath, $originalContents);
    }

    /**
     * Replicates the configuration onto the VFS.
     */
    protected function replicateConfiguration()
    {
        $folder = $this->configurationLoader->getFolders()[0];
        $this->files->createDir($folder);

        $files = (new Finder())->in($folder)->files();
        foreach ($files as $file) {
            $contents = file_get_contents($file->getPathname());
            $this->files->write($folder.'/'.$file->getBasename(), $contents);
        }

        $this->configurationLoader->setFolders([$folder]);
        $this->configurationLoader->getCache()->flush();

        return $folder;
    }
}

Add test for config cache

Add test for config cache


<?php
namespace Ayeo\Validator\Constraint;

class NoWhitespace extends AbstractConstraint
{
	public function run($value)
	{
		$parsed = preg_replace('/\s+/', '', $value);
		if ($parsed !== $value)
		{
			$this->addError('must_not_contains_whitespace');
		}
	}
}

Add new validator: No whitespace

Add new validator: No whitespace


<?php namespace Flarum\Assets;

class JsCompiler extends RevisionCompiler
{
    public function format($string)
    {
        return $string.';';
    }
}

<?php namespace Flarum\Assets;

class JsCompiler extends RevisionCompiler
{
    public function format($string)
    {
        return $string.";\n";
    }
}

Add newline in-between JS files, in case last line is a comment


<?php

namespace Monospice\SpicyRepositories\Laravel;

use Illuminate\Support\ServiceProvider;

/**
 * Binds the repository into the container
 *
 * @category Package
 * @package  Monospice\SpicyRepositories
 * @author   Cy Rossignol <cy@rossignols.me>
 * @license  See LICENSE file
 * @link     http://github.com/monospice/spicy-repositories
 */
abstract class EloquentRepositoryServiceProvider extends ServiceProvider
{
    /**
     * Return an associative array of repositories to bind into the service
     * container consisting of key/value pairs where the key is the fully
     * namespaced class name of the repository interface and the value is the
     * closure function that returns a new instance of the concrete repository
     *
     * Example:
     *
     *  protected function getRepositories() {
     *      return [
     *          'App\Repositories\Interfaces\UserRepository' => function() {
     *              return new \App\Repositories\UserRepository;
     *          },
     *          'App\Repositories\Interfaces\MessageRepository' => function() {
     *              return new \App\Repositories\MessageRepository;
     *          }
     *      ];
     *  }
     *
     * @return array The array of repository bindings
     */
    abstract protected function repositories();

    /**
     * Boot the service
     *
     * @return void
     */
    public function boot()
    {
        // nothing to do
    }

    /**
     * Bind the repository interfaces into the service container
     *
     * @return void
     */
    public function register()
    {
        $repositories = $this->repositories();

        foreach ($repositories as $interface => $instanceClosure) {
            $this->app->bind(
                $interface,
                function ($app) use ($instanceClosure) {
                    return $instanceClosure();
                }
            );
        }
    }
}

Create Eloquent Repository Service Provider for Laravel

Signed-off-by: Cy Rossignol <31ace4ad1831aae866cd7951a842ca3e38f21981@rossignols.me>


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\UtilsBundle\Tests\Functional\DependencyInjection;

use ONGR\AdminBundle\DependencyInjection\ONGRAdminExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

/**
 * This class holds tests for extension loader.
 */
class ONGRAdminExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test if admin user parameters are being loaded.
     */
    public function testAdminUser()
    {
        $config = [
            'admin_user' => [
                'categories' => [
                    'test_category1' => [
                        'name' => 'test_name1',
                        'description' => 'test_desc1',
                    ]
                ],
                'settings' => [
                    'test_category1' => [
                        'name' => 'test_name2',
                        'description' => 'test_desc2',
                        'category' => 'test_category1',
                    ]
                ]
            ]
        ];

        $extension = new ONGRAdminExtension();
        $container = new ContainerBuilder();
        $extension->load(['ongr-admin' => $config], $container);

        $this->assertTrue($container->hasParameter('ongr_admin.settings.categories'));
        $this->assertTrue($container->hasParameter('ongr_admin.settings.settings'));
    }

}

Add ONGR Admin Extension Test

Add ONGR Admin Extension Test


<?php
namespace pyd\testkit\web\elements\bootstrap;

/**
 * Bootstrap 3 list group element.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class ListGroup extends \pyd\testkit\web\Element
{
    public function initLocators()
    {
        parent::initLocators();
        $this->getLocator()->add('items', \WebDriverBy::className("list-group-item"));
    }

    /**
     * Find list group items.
     *
     * @return array of \pyd\testkit\web\base\Element
     */
    public function findItems()
    {
        return $this->findElements('items');
    }
}

Add web element class for bootstrap 3 list group


<?php

use Hubzero\Content\Migration\Base;

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

/**
 * Migration script for adding is_default column
 **/
class Migration20140217151012ComCourses extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableExists('#__courses_offering_sections'))
		{
			if (!$this->db->tableHasField('#__courses_offering_sections', 'is_default'))
			{
				$query = "ALTER TABLE `#__courses_offering_sections` ADD `is_default` TINYINT(2)  NOT NULL  DEFAULT '0' AFTER `offering_id`";

				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableExists('#__courses_offering_sections'))
		{
			if ($this->db->tableHasField('#__courses_offering_sections', 'is_default'))
			{
				$query = "ALTER TABLE `#__courses_offering_sections` DROP `is_default`;";

				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}
}

<?php

use Hubzero\Content\Migration\Base;

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

/**
 * Migration script for adding is_default column
 **/
class Migration20140217151012ComCourses extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableExists('#__courses_offering_sections'))
		{
			if (!$this->db->tableHasField('#__courses_offering_sections', 'is_default'))
			{
				$query = "ALTER TABLE `#__courses_offering_sections` ADD `is_default` TINYINT(2)  NOT NULL  DEFAULT '0' AFTER `offering_id`";

				$this->db->setQuery($query);
				$this->db->query();

				$query = "UPDATE `#__courses_offering_sections` SET `is_default`=1 WHERE `alias`='__default'";

				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableExists('#__courses_offering_sections'))
		{
			if ($this->db->tableHasField('#__courses_offering_sections', 'is_default'))
			{
				$query = "ALTER TABLE `#__courses_offering_sections` DROP `is_default`;";

				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}
}

[COM_COURSES] Mark default sections based on alias after is_default field is added


<?php

namespace Zoop\Shard\Test\ODMCore;

use Zoop\Shard\Manifest;
use Zoop\Shard\Test\BaseTest;
use Zoop\Shard\Test\ODMCore\TestAsset\Document\Album;

class MultipleConnectionTest extends BaseTest
{

    public function testMultipleConnections()
    {
        $manifest1 = new Manifest(
            [
                'models' => [
                    __NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document'
                ],
                'extension_configs' => [
                    'extension.odmcore'   => [
                        'default_db' => 'shard-phpunit-1'
                    ],
                ],
            ]
        );

        $manifest2 = new Manifest(
            [
                'models' => [
                    __NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document'
                ],
                'extension_configs' => [
                    'extension.odmcore'   => [
                        'default_db' => 'shard-phpunit-2'
                    ],
                ],
            ]
        );

        $documentManager1 = $manifest1->getServiceManager()->get('modelmanager');
        $documentManager2 = $manifest2->getServiceManager()->get('modelmanager');

        $album1 = new Album('Ivy and the big apples');
        $album2 = new Album('Guide to better living');

        $documentManager1->persist($album1);
        $documentManager2->persist($album2);

        $documentManager1->flush();
        $documentManager2->flush();

        $albums1 = $documentManager1->getRepository(get_class($album1))->findAll();
        $this->assertCount(1, $albums1);
        $this->assertEquals('Ivy and the big apples', $albums1[0]->getName());

        $albums2 = $documentManager2->getRepository(get_class($album2))->findAll();
        $this->assertCount(1, $albums2);
        $this->assertEquals('Guide to better living', $albums2[0]->getName());

        //cleanup
        foreach ($documentManager1->getConnection()->selectDatabase('shard-phpunit-1')->listCollections() as $collection) {
            $collection->remove(array(), array('safe' => true));
        }
        foreach ($documentManager2->getConnection()->selectDatabase('shard-phpunit-2')->listCollections() as $collection) {
            $collection->remove(array(), array('safe' => true));
        }
    }
}

Add test for multiple connections

Add test for multiple connections


<?php

/*
 * This file is part of PhuninNode.
 *
 ** (c) 2015 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WyriHaximus\PhuninNode\Tests;

use WyriHaximus\PhuninNode\EchoLogger;

/**
 * Class EchoLoggerTest
 * @package WyriHaximus\PhuninNode
 */
class EchoLoggerTest extends \PHPUnit_Framework_TestCase
{
    public function testLog()
    {
        $logger = new EchoLogger();
        ob_start();
        $logger->log('abc', 'def');
        $this->assertSame('[abc] def' . PHP_EOL, ob_get_clean());
    }
}

Test for the echo logger

Test for the echo logger


<?php
/**
 * This example will list the children of the CMIS root folder.
 * The list is created recursively but is limited to 5 items per level.
 */

require_once(__DIR__ . '/../vendor/autoload.php');
if (!is_file(__DIR__ . '/conf/Configuration.php')) {
    die("Please add your connection credentials to the file \"" . __DIR__ . "/conf/Configuration.php\".\n");
} else {
    require_once(__DIR__ . '/conf/Configuration.php');
}

$httpInvoker = new \GuzzleHttp\Client(
    array(
        'defaults' => array(
            'auth' => array(
                CMIS_BROWSER_USER,
                CMIS_BROWSER_PASSWORD
            )
        )
    )
);

$parameters = array(
    \Dkd\PhpCmis\SessionParameter::BINDING_TYPE => \Dkd\PhpCmis\Enum\BindingType::BROWSER,
    \Dkd\PhpCmis\SessionParameter::BROWSER_URL => CMIS_BROWSER_URL,
    \Dkd\PhpCmis\SessionParameter::BROWSER_SUCCINCT => false,
    \Dkd\PhpCmis\SessionParameter::HTTP_INVOKER_OBJECT => $httpInvoker,
);

$sessionFactory = new \Dkd\PhpCmis\SessionFactory();

// If no repository id is defined use the first repository
if (CMIS_REPOSITORY_ID === null) {
    $repositories = $sessionFactory->getRepositories($parameters);
    $parameters[\Dkd\PhpCmis\SessionParameter::REPOSITORY_ID] = $repositories[0]->getId();
} else {
    $parameters[\Dkd\PhpCmis\SessionParameter::REPOSITORY_ID] = CMIS_REPOSITORY_ID;
}

$session = $sessionFactory->createSession($parameters);

// Get the root folder of the repository
$rootFolder = $session->getRootFolder();

echo '+ [ROOT FOLDER]: ' . $rootFolder->getName() . "\n";

printFolderContent($rootFolder);

function printFolderContent(\Dkd\PhpCmis\Data\FolderInterface $folder, $levelIndention = ' ')
{
    $i = 0;
    foreach ($folder->getChildren() as $children) {
        echo $levelIndention;
        $i++;
        if ($i > 5) {
            echo "| ...\n";
            break;
        }

        if ($children instanceof \Dkd\PhpCmis\Data\FolderInterface) {
            echo '+ [FOLDER]: ' . $children->getName() . "\n";
            printFolderContent($children, $levelIndention . ' ');
        } elseif ($children instanceof \Dkd\PhpCmis\Data\DocumentInterface) {
            echo '- [DOCUMENT]: ' . $children->getName() . "\n";
        }
    }
}

Add example for folder and document listing

Summary:
An example how to get the children of a CMIS folder.
The examples creates an output that shows the tree structure
of the CMIS root folder.

Test Plan:
Add a example configuration file and run
`php examples/ListFoldersAndFiles.php`

This should give you an output like:
```
+ [ROOT FOLDER]: Company Home
 + [FOLDER]: My First Folder
   - [DOCUMENT]: My First Document
   - [DOCUMENT]: My Second Document
   + [FOLDER]: My First Sub-Folder
     - [DOCUMENT]: My First Sub-Folder Document
```

Reviewers: claus.due

Reviewed By: claus.due

Subscribers: dkd-dobberkau

Differential Revision: https://phabricator.dkd.de/D2020


<?php

namespace Tests;

class ExporterTest extends BaseTestCase
{
    /** @test */
    public function smoke_test()
    {
        $this->cleanLangsFolder();
        $this->createTestView("{{ __('name') }}");

        $this->artisan('translatable:export', ['lang' => 'bg,es'])
            ->expectsOutput('Translatable strings have been extracted and written to the bg.json file.')
            ->expectsOutput('Translatable strings have been extracted and written to the es.json file.')
            ->assertExitCode(0);

        $this->assertFileExists(resource_path('lang/bg.json'));

        $bg = file_get_contents(resource_path('lang/bg.json'));
        $es = file_get_contents(resource_path('lang/es.json'));

        $this->assertEquals(['name' => 'name'], json_decode($bg, true));
        $this->assertEquals(['name' => 'name'], json_decode($es, true));
    }
}

Add smoke test with basic assetions

Add smoke test with basic assetions


<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserControllerTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function test_login()
    {
        $user = factory(App\User::class)->create();

        $response = $this->call('POST', '/login', [
            'username' => $user['username'],
            'password' => 'secret',
        ]);

        $this->assertRedirectedTo('/');
        $this->assertSessionHas('user_logged_in', true);
    }
}

Create method to test login

Create method to test login


<?php

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

namespace App\Http\Controllers\FilteringAttributes;

use App\Models\Attributes\Property\LandRegistry;
use App\Models\Items\Property;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

/**
 * This is the property filtering attributes controller class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class PropertyFilteringAttrController extends Controller
{
    use GenericFilteringAttributesTrait;

    public function __construct()
    {
        self::$itemType = Property::class;
    }

    /**
     * Show a list of filtering attributes for properties.
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $districtId = (int) $request->input('district') ?: null;

        $data = [
            'generic'  => self::getGenericFilteringAttr($districtId),
            'property' => self::getPropertyFilteringAttr(),
        ];

        return response()->json($data, 200);
    }

    /**
     * Get property filtering attributes.
     *
     * @return array
     */
    private static function getPropertyFilteringAttr()
    {
        $propertyAttr = [
            'landRegistryTypes' => self::getLandRegistryTypes(),
        ];

        return $propertyAttr;
    }

    /**
     * Get land registry types.
     *
     * @return array|null
     */
    private static function getLandRegistryTypes()
    {
        return LandRegistry::assigned()->lists('name', 'id') ?: null;
    }
}

Add the property filtering attributes controller


<?php
/**
 * The template for pages with parent get involved archive pages.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package serve-first
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">

		<?php if ( have_posts() ) : ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php
					/* Include the Post-Format-specific template for the content.
					 * If you want to override this in a child theme, then include a file
					 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
					 */
					get_template_part( 'content', get_post_format() );
				?>

			<?php endwhile; ?>

			<?php serve_first_paging_nav(); ?>

		<?php else : ?>

			<?php get_template_part( 'content', 'none' ); ?>

		<?php endif; ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_sidebar('getinvolved'); ?>
<?php get_footer(); ?>

Add category page for President's Blog

Add category page for President's Blog


<?php

/*
 * This file is part of Respect/Validation.
 *
 * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
 *
 * For the full copyright and license information, please view the "LICENSE.md"
 * file that was distributed with this source code.
 */

namespace Respect\Validation\Rules;

/**
 * @group  rule
 * @covers Respect\Validation\Rules\Tld
 */
class TldTest extends \PHPUnit_Framework_TestCase
{
    public function providerForValidTld()
    {
        return array(
            array('com'),
            array('cafe'),
            array('democrat'),
            array('br'),
            array('us'),
            array('eu'),
        );
    }

    /**
     * @dataProvider providerForValidTld
     */
    public function testShouldValidateInputWhenItIsAValidTld($input)
    {
        $rule = new Tld();

        $this->assertTrue($rule->validate($input));
    }

    public function providerForInvalidTld()
    {
        return array(
            array('1'),
            array(1.0),
            array('wrongtld'),
            array(true),
        );
    }

    /**
     * @dataProvider providerForInvalidTld
     */
    public function testShouldInvalidateInputWhenItIsNotAValidTld($input)
    {
        $rule = new Tld();

        $this->assertFalse($rule->validate($input));
    }
}

Add unit tests for "Tld" rule

Add unit tests for "Tld" rule


<?php namespace Larapress\Tests\Controllers;

use Config;
use Helpers;
use Larapress\Controllers\BaseController;
use Larapress\Tests\TestCase;
use Str;
use View;

class BaseControllerTest extends TestCase
{

    private $backend_route;

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

        $this->backend_route = Config::get('larapress.urls.backend');
    }

    /*
    |--------------------------------------------------------------------------
    | Constructor Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the constructor
    |
    */

    public function test_constructor_shares_important_data()
    {
        View::shouldReceive('share')->times(2);

        new BaseController;
    }

    /*
    |--------------------------------------------------------------------------
    | ControlPanelController@missingMethod Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the ControlPanelController@missingMethod method
    |
    */

    public function test_can_catch_404_errors()
    {
        $this->call('GET', $this->backend_route . '/' . Str::quickRandom(16));

        $this->assertResponseStatus(404);
    }

    public function test_can_set_the_correct_page_title()
    {
        Helpers::shouldReceive('setPageTitle')->with('404 Error')->once();
        View::share('title', 'foo'); // Prevent an for this test irrelevant ErrorException

        $controller = new BaseController;
        $controller->missingMethod(array());
    }

}

Add missing tests for the base controller


<?php

use Phinx\Migration\AbstractMigration;

class AddImageFulltextIndex extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('image', [ 'signed' => false ]);
      $table
        ->addIndex([ 'name', 'alt_text', 'caption' ], [ 'type' => 'fulltext' ])
        ->save();
    }
}

Add full-text index to image table

Add full-text index to image table


<?php
/**
 * Plugin Name: Restrict Content Pro - Restrict WooCommerce Shop Archive
 * Description: Restricts access to the WooCommerce shop archive, using the settings specified in the "Restrict this Content" metabox.
 * Version: 1.0
 * Author: Restrict Content Pro team
 * License: GPL2
 */

/**
 * Restricts access to the WooCommerce shop archive according to the settings specified in the metabox.
 * If the current user doesn't have access, they're redirected to the specified redirect URL in Restrict > Settings > Misc.
 *
 * @since 1.0
 * @return void
 */
function ag_rcp_redirect_woocommerce_shop() {
	if ( ! function_exists( 'is_shop' ) || ! is_shop() ) {
		return;
	}

	global $rcp_options;

	$shop_page_id = wc_get_page_id( 'shop' );
	$member       = new RCP_Member( get_current_user_id() );

	if ( $member->can_access( $shop_page_id ) ) {
		return;
	}

	if( isset( $rcp_options['redirect_from_premium'] ) ) {
		$redirect = get_permalink( $rcp_options['redirect_from_premium'] );
	} else {
		$redirect = home_url();
	}

	wp_redirect( $redirect ); exit;
}
add_action( 'template_redirect', 'ag_rcp_redirect_woocommerce_shop', 999 );

Add snippet for redirecting from WooCommerce shop archive.


<?php declare(strict_types=1);
namespace Wisembly\AmqpBundle\DependencyInjection\Compiler;

use PHPUnit\Framework\TestCase;

use Prophecy\Prophecy\ProphecyInterface;

use Symfony\Component\DependencyInjection\ContainerBuilder;

use Wisembly\AmqpBundle\BrokerInterface;
use Wisembly\AmqpBundle\DependencyInjection\WisemblyAmqpExtension;

class BrokerPassTest extends TestCase
{
    public function test_it_can_be_initialized()
    {
        $this->assertInstanceOf(BrokerPass::class, new BrokerPass);
    }

    public function test_valid_broker_is_used_as_alias_for_interface()
    {
        $container = $this->getContainerProphecy('foo');
        $container->setAlias(BrokerInterface::class, 'foo')->shouldBeCalled();

        $pass = new BrokerPass;
        $pass->process($container->reveal());
    }

    public function test_valid_broker_alias_is_used_as_alias_for_interface()
    {
        $container = $this->getContainerProphecy('baz');
        $container->setAlias(BrokerInterface::class, 'bar')->shouldBeCalled();
        $container->setAlias(BrokerInterface::class, 'baz')->shouldNotBeCalled();

        $pass = new BrokerPass;
        $pass->process($container->reveal());
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Invalid broker "qux". Expected one of those : [foo, bar, baz]
     */
    public function test_invalid_broker_triggers_exception()
    {
        $container = $this->getContainerProphecy('qux');
        $container->setAlias(BrokerInterface::class, 'qux')->shouldNotBeCalled();

        $pass = new BrokerPass;
        $pass->process($container->reveal());
    }

    private function getContainerProphecy(string $broker): ProphecyInterface
    {
        $services = [
            'foo' => [],
            'bar' => [
                ['alias' => 'baz'],
            ],
        ];

        $extension = $this->prophesize(WisemblyAmqpExtension::class);
        $extension->getConfig([])->willReturn(['broker' => $broker])->shouldBeCalled();

        $container = $this->prophesize(ContainerBuilder::class);
        $container->findTaggedServiceIds('wisembly.amqp.broker')->willReturn($services)->shouldBeCalled();
        $container->getExtensionConfig('wisembly_amqp')->willReturn([])->shouldBeCalled();
        $container->getExtension('wisembly_amqp')->willReturn($extension)->shouldBeCalled();

        return $container;
    }
}

Add tests for the broker pass

Add tests for the broker pass


<?php

  class ConvertNewLines {

  private $DatabaseHandle;

  public function __construct() {

    //
  }

  public function manageHooks() {

    global $Hook;

    if (isset($_GET["post_url"])) {

      if ($Hook->hasAction("post_body")) {

        $Hook->addAction(

          "post_body",

          $this,

          "singleConvertNewLines",

          $Hook->getCallback("post_body")
        );
      }
      else {

        $Hook->addAction(

          "post_body",

          $this,

          "singleConvertNewLines"
        );
      }
    }
    else {

      if ($Hook->hasAction("post_bodies")) {

        $Hook->addAction(

          "post_bodies",

          $this,

          "latestConvertNewLines",

          $Hook->getCallback("post_bodies")
        );
      }
      else {

        $Hook->addAction(

          "post_bodies",

          $this,

          "latestConvertNewLines"
        );
      }
    }
  }

  public function singleConvertNewLines($callback_content = "") {

    if ($callback_content == "") {

      $statement = "

        SELECT body
        FROM " . DB_PREF . "posts
        WHERE url = ?
      ";

      $query = $this->DatabaseHandle->prepare($statement);

      // Prevent SQL injections.
      $query->bindParam(1, $_GET["post_url"]);

      $query->execute();

      if (!$query || $query->rowCount() == 0) {

        // Query failed or post's body does not exist.
        return "Failure";
      }

      // Fetch the result as an object.
      $result = $query->fetch(PDO::FETCH_OBJ);

      return str_replace("\n", "
", $result->body);
    }
    else {

      return str_replace("\n", "
", $callback_content);
    }
  }

  public function latestConvertNewLines($callback_content = "") {

    if ($callback_content == "") {

      $statement = "

        SELECT body
        FROM " . DB_PREF . "tags
        WHERE title = 'posts_per_page'
      ";

      $query = $this->DatabaseHandle->query($statement);

      if (!$query || $query->rowCount() == 0) {

        // Query failed or post's body does not exist.
        return "Failure";
      }

      // Fetch the result as an object.
      $result = $query->fetch(PDO::FETCH_OBJ);

      $posts_per_page = $result->body;

      $statement = "

        SELECT body
        FROM " . DB_PREF . "posts
        ORDER BY id DESC
        LIMIT {$posts_per_page}
      ";

      $query = $this->DatabaseHandle->query($statement);

      if (!$query || $query->rowCount() == 0) {

        // Query failed or post's body does not exist.
        return "Failure";
      }

      $bodies = array();

      while ($result = $query->fetch(PDO::FETCH_OBJ)) {

        $bodies[] = str_replace("\n", "
", $result->body);
      }

      return $bodies;
    }
    else {

      return str_replace("\n", "
", $callback_content);
    }
  }

  public function setDatabaseHandle($handle) {

    $this->DatabaseHandle = $handle;
  }
}

?>

Convert new lines to HTML line breaks

Convert new lines to HTML line breaks

This extension converts new lines (\n) found within the bodies of posts
on individual post pages as well as the latest posts to HTML line
breaks (<br>).


<?php

// example call:
// php examples/macro-expand.php
//     "(defmacro when (condition a b c) (list 'if condition (list 'begin a b c)))"
//     "(when (> x 10) 1 2 3)"

namespace Igorw\Ilias;

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

if ($argc < 3) {
    echo "Usage: php examples/macro-expand.php MACROS CODE\n";
    exit(1);
}

list($_, $macros, $code) = $argv;

$program = new Program(
    new Lexer(),
    new Reader(),
    new FormTreeBuilder(),
    new Walker()
);

$env = Environment::standard();

$program->evaluate($env, $macros);

$expandedForms = expand($env, $code);
foreach ($expandedForms as $expanded) {
    echo encode($expanded->getAst())."\n";
}

function buildForms($code)
{
    $lexer = new Lexer();
    $reader = new Reader();
    $builder = new FormTreeBuilder();

    $tokens = $lexer->tokenize($code);
    $ast = $reader->parse($tokens);
    return $builder->parseAst($ast);
}

function expand(Environment $env, $code)
{
    $walker = new Walker();
    $forms = buildForms($code);

    return array_map(
        function ($form) use ($walker, $env) {
            return $walker->expand($env, $form);
        },
        $forms
    );
}

function encode(array $form)
{
    $encoder = new Encoder();
    return $encoder->encode([$form]);
}

Add example script for macro expansion

Add example script for macro expansion


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

namespace ZendTest\Console;

use Zend\Console\Request;

/**
 * @category   Zend
 * @package    Zend_Console
 * @subpackage UnitTests
 * @group      Zend_Console
 */
class RequestTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (ini_get('register_argc_argv') == false) {
            $this->markTestSkipped("Cannot Test Zend\\Console\\Getopt without 'register_argc_argv' ini option true.");
        }
    }

    public function testCanConstructRequestAndGetParams()
    {
        $_SERVER['argv'] = array('foo.php', 'foo' => 'baz', 'bar');
        $_ENV["FOO_VAR"] = "bar";

        $request = new Request();
        $params = $request->getParams();

        $this->assertEquals(2, count($params));
        $this->assertEquals($params->toArray(), array('foo' => 'baz', 'bar'));
        $this->assertEquals($request->getParam('foo'), 'baz');
        $this->assertEquals($request->getScriptName(), 'foo.php');
        $this->assertEquals(1, count($request->env()));
        $this->assertEquals($request->env()->get('FOO_VAR'), 'bar');
        $this->assertEquals($request->getEnv('FOO_VAR'), 'bar');
    }
}

Add test for console request

Add test for console request


<?php

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Migrations\Migration;

class AddTrainerRole extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        $role = Role::firstOrCreate(['name' => 'trainer']);
        $role->givePermissionTo('create-attendance');
        $role->givePermissionTo('read-teams-hidden');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Role::where('name', 'trainer')->first()->delete();
    }
}

Add migration to add trainer role

Add migration to add trainer role

Trainers can add attendance to hidden teams


<?php

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

class AddUniquePostIdHashToAttachmentsTable extends Migration
{
    public function up()
    {
        // Removing the duplicate lines
        $this->schema->getConnection()->unprepared('
            delete from attachments
            where id in (
                select a1.id
                from attachments a1, attachments a2
                where a1.id > a2.id
                and a1.post_id = a2.post_id
                and a1.href = a2.href
                and a1.category = a2.category
                and a1.rel = a2.rel)
        ');

        $this->schema->table('attachments', function(Blueprint $table) {
            $table->unique(['post_id', 'href', 'category', 'rel']);
        });

    }

    public function down()
    {
        $this->schema->table('attachments', function(Blueprint $table) {
            $table->dropUnique('attachments_post_id_href_category_rel_unique');
        });
    }
}

Add migration to remove and restrict duplicates in Posts Attachements


<?php

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

class AddUsernameIndexToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->index(['username', 'deleted_at']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropIndex(['username','deleted_at']);
        });
    }
}

Add index across username and deleted_at to improve large directory sync performance


<?php

use Illuminate\Support\Facades\File;

Route::group(array('before' => 'vextAuth'), function() {

    /*Route::any('/{all}', function($page) {
        if ( File::extension($page) === 'js' ) {
            header("Content-type: text/javascript");
        } else if ( File::extension($page) === 'css' ) {
            header("Content-type: text/css");
        }
        readfile("../app/views/extjs/$page");
        flush();
    })->where('all', '.*');*/

    //Route::get('login', 'Qlcorp\VextSecurity\UserController@showLogin');
    Route::controller('user', 'Qlcorp\VextSecurity\UserController');
    Route::controller('brand', 'Qlcorp\VextSecurity\BrandController');
    Route::controller('role', 'Qlcorp\VextSecurity\RoleController');
    Route::controller('departmentRole', 'Qlcorp\VextSecurity\DepartmentRoleController');
});

Route::group(array('before' => 'vextGuest'), function() {
    Route::controller('login', 'Qlcorp\VextSecurity\AuthController');
});

Load models via single request

Load models via single request


<?php
/**
 * Elgg Reported content admin page
 *
 * @package ElggReportedContent
 */

$options = array('type' => 'object', 'subtype' => 'informe',
                'limit' => 200
                );

$list = elgg_get_entities($options);

$informes = array();

echo "
";
foreach($list as $informe) {
/*
        $informe_pa      = get_entity($informe->meeting_pa);
        $group           = get_entity($informe->container_guid);
        $period_stamp    = $informe->informe_period_y . str_pad($informe->informe_period_m, 2, 0, STR_PAD_LEFT);
        $informe_period  = $informe->informe_period_y ."/".str_pad($informe->informe_period_m, 2, 0, STR_PAD_LEFT);
        $informe_guid    = $informe->guid;
        $informe_title   = $informe->title;
        $group_guid      = $group->getGUID();
        $group_name      = $group->name;
        $group_pa        = $informe_pa->name;
*/

	$i = array();
        $informe_pa = get_entity($informe->meeting_pa);
        $group      = get_entity($informe->container_guid);
        $i[] = $informe->informe_period_y . str_pad($informe->informe_period_m, 2, 0, STR_PAD_LEFT);
        $i[] = $informe->informe_period_y ."/".str_pad($informe->informe_period_m, 2, 0, STR_PAD_LEFT);
        $i[] = $informe->guid;
        $i[] = "getURL()}\">{$informe->title}";
        $i[] = $group->getGUID();
        $i[] = "getURL()}\">{$group->name}";
        if($informe_pa->name) {
	        $i[] = "getURL()}\">{$informe_pa->name}";
	} else {
	        $i[] = "SIN PA";
	}

	$informes[] = $i;
}

foreach($informes as $informe) {
	echo "
";
	echo "$informe[1]	";
	echo "$informe[2]	";
	echo "$informe[3]	";
	echo "$informe[4]	";
	echo "$informe[5]	";
	echo "$informe[6]	";
	echo "
";
}

echo "
";

Add informe stats under admin utilities

Add informe stats under admin utilities


<?php

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

class AddVerificationTokenColumnToUsersTable extends Migration {
    public function up() {
        Schema::table('users', function (Blueprint $table) {
            $table->string('verification_token', 100)->nullable()->before('remember_token');
        });
    }

    public function down() {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('verification_token');
        });
    }
}

Create migration for adding verification_token column to users table


<?php

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

namespace Surfnet\StepupRa\RaBundle\Controller;

use Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity;
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class RaaController extends Controller
{

    public function institutionConfigurationAction()
    {
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
        $token = $this->get('security.token_storage')->getToken();

        $logger = $this->get('logger');
        /** @var Identity $identity */
        $identity = $token->getUser();
        $institution = $identity->institution;

        $logger->notice(sprintf('Opening the institution configuration for "%s"', $institution));

        $configuration = $this->getInstitutionConfigurationOptionsService()
            ->getInstitutionConfigurationOptionsFor($institution);

        if (!$configuration) {
            $logger->warning(sprintf('Unable to find the institution configuration for "%s"', $institution));
            return $this->createNotFoundException('The institution configuration could not be found');
        }

        return $this->render(
            '@SurfnetStepupRaRa/InstitutionConfiguration/overview.html.twig',
            [
                'configuration' => (array)$configuration,
                'institution' => $institution,
            ]
        );
    }

    /**
     * @return InstitutionConfigurationOptionsService
     */
    private function getInstitutionConfigurationOptionsService()
    {
        return $this->get('ra.service.institution_configuration_options');
    }
}

Fix raa controller configuration action

Fix raa controller configuration action


<?php
namespace MssPhp\Bitmask;

class RoomDetails
{
    const BASIC_INFO = 4;
    const TITLE = 8;
    const ROOM_IMAGES = 32;
    const ROOM_FACILITIES_FILTER = 64;
    const ROOM_DESCRIPTION = 256;
    const ROOM_FACILITIES_DETAILS = 4096;
    const ROOM_FEATURES = 32768;
    const ROOM_NUMBERS = 65536;
}

Add bitmask for room details

Add bitmask for room details


<?php

namespace Bugsnag\Tests;

use InvalidArgumentException;
use PHPUnit\Framework\Assert as PhpUnitAssert;

/**
 * This class holds assertions that were removed/renamed/changed in various
 * PHPUnit versions, so that our test suite can be compatible with as many
 * versions as possible.
 */
final class Assert
{
    /**
     * A replacement for 'assertInternalType', which was removed in PHPUnit 9.
     *
     * @param string $type
     * @param mixed $value
     *
     * @return void
     */
    public static function isType($type, $value)
    {
        if (method_exists(PhpUnitAssert::class, 'assertInternalType')) {
            PhpUnitAssert::assertInternalType($type, $value);

            return;
        }

        $typeToAssertion = [
            'array' => [PhpUnitAssert::class, 'assertIsArray'],
            'bool' => [PhpUnitAssert::class, 'assertIsBool'],
            'callable' => [PhpUnitAssert::class, 'assertIsCallable'],
            'float' => [PhpUnitAssert::class, 'assertIsFloat'],
            'int' => [PhpUnitAssert::class, 'assertIsInt'],
            'iterable' => [PhpUnitAssert::class, 'assertIsIterable'],
            'numeric' => [PhpUnitAssert::class, 'assertIsNumeric'],
            'object' => [PhpUnitAssert::class, 'assertIsObject'],
            'resource' => [PhpUnitAssert::class, 'assertIsResource'],
            'scalar' => [PhpUnitAssert::class, 'assertIsScalar'],
            'string' => [PhpUnitAssert::class, 'assertIsString'],
        ];

        if (!isset($typeToAssertion[$type])) {
            throw new InvalidArgumentException("Unknown type '{$type}' given");
        }

        $typeToAssertion[$type]($value);
    }
}

Add a replacement for `assertInternalType`

This was removed in PHPUnit 9, but its replacements aren't available in
PHPUnit 4 (which we still support)

We have to do this with a new Assert class, rather than implementing it
in our TestCase class because otherwise we would need to exactly match
PHPUnit's method signature. This isn't possible because PHPUnit added
parameter and return types to their method, which we can't replicate
because of PHP 5 compatibility


<?php namespace bmwcarit\oauth;
/*
 * Copyright (C) 2015, BMW Car IT GmbH
 *
 * 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.
 */

use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

class JiraOAuthControllerProvider implements ControllerProviderInterface{
	protected $app;

	public function connect(Application $app) {
		$this->app = $app;
		$jira = $app['controllers_factory'];

		$jira->get('/connect/{redirect}',
				function(Request $request, $redirect) use($app) {

			$token = $app['jira.oauth.temp_credentials']($redirect);
			$app['session']->set('oauth', $token);

			return $app->redirect($app['jira.oauth.auth_url']);
		})
		->value('redirect', null)
		->bind('jira-connect');

		$jira->get('/callback', function($url, $verifier) use($app) {
			$tempToken = $app['session']->get('oauth');
			$app['jira.token'] = $tempToken;
			$app['jira.oauth_verifier'] = $verifier;

			$token = $app['jira.oauth.auth_credentials']($url);

			$app['session']->set('oauth', $token);

			return $app->redirect($url);
		})
		->convert('url', function($url, Request $request) {
			if (!$request->query->has('url')) {
				return $this->app['jira.default_redirect'];
			}

			$url = $request->get('url');
			try {
				return $this->app['url_generator']->generate($url);
			} catch (RouteNotFoundException $e) {
				return ('/' . $url);
			}
		})
		->convert('verifier', function($verifier, Request $request) {
			if (!$request->query->has('oauth_verifier')) {
				throw new \InvalidArgumentException(
								'There was no oauth verifier in the request');
			}

			return $request->get('oauth_verifier');
		})
		->bind('jira-callback');

		return $jira;
	}
}

Add silex controller for oauth routes

oauth: Add silex controller for oauth routes

The controller has two routes jira-connect and jira-callback. An
application can start the authentication process with jira calling the
jira-connect route.

The jira-connect route will trigger the temporary token request and will
then redirect to the JIRA OAuth page. After the user has logged in and
allowed the application to access JIRA it will redirect back to the
jira-callback route.

The jira-callback route will process the OAuth data from JIRA and create
an access token, which can be used for making REST API request in the
future. If this is successful the user will be redirected to a page of
the original application.