<?php
/**
 * digital-logsheets: A web-based application for tracking the playback of audio segments on a community radio station.
 * Copyright (C) 2015  Mike Dean
 * Copyright (C) 2015-2016  Evan Vassallo
 * Copyright (C) 2016  James Wang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

include("../../digital-logsheets-res/smarty/libs/Smarty.class.php");
include_once("../../digital-logsheets-res/php/database/connectToDatabase.php");
include_once("../../digital-logsheets-res/php/database/manageCategoryEntries.php");
require_once("../../digital-logsheets-res/php/objects/logsheetClasses.php");
require_once("../../digital-logsheets-res/php/select2-preparation.php");

$smarty = new Smarty;

//database interactions
try {
    //connect to database
    $db = connectToDatabase();

    $archive = new Archive($db);
    $episodesArchive = $archive->getArchive();

    //close database connection
    $db = NULL;

    $draftEpisodes = array();

    foreach($episodesArchive as $episode) {
        if ($episode->isDraft()) {
            $episodeArray = $episode->getObjectAsArray();
            $draftEpisodes[] = $episodeArray;
        }
    }

    $smarty->assign("drafts", $draftEpisodes);

    echo $smarty->fetch('../../digital-logsheets-res/templates/drafts.tpl');

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Add missing change to eadfe8d

Add missing change to eadfe8d


<?php

class Stripe_AuthenticationErrorTest extends Stripe_TestCase
{
  public function testInvalidCredentials()
  {
    Stripe::setApiKey('invalid');
    try {
      Stripe_Customer::create();
    } catch (Stripe_AuthenticationError $e) {
      $this->assertSame(401, $e->getHttpStatus());
    }
  }
}

Add PHPUnit tests for Stripe_AuthenticationError


<?php

class NotificationStructureTest extends MediaWikiTestCase {
	/**
	 * @coversNothing
	 * @dataProvider provideNotificationTypes
	 *
	 * @param string $type
	 * @param array $info
	 */
	public function testNotificationTypes( $type, array $info ) {
		if ( isset( $info['presentation-model'] ) ) {
			self::assertTrue( class_exists( $info['presentation-model'] ),
				"Presentation model class {$info['presentation-model']} for {$type} must exist"
			);
		}

		if ( isset( $info['user-locators'] ) ) {
			$locators = $info['user-locators'];
			$locator = reset( $locators );
			if ( is_array( $locator ) ) {
				$locator = reset( $locator );
			}
			self::assertTrue( is_callable( $locator ),
				'User locator ' . print_r( $locator, true ) . " for {$type} must be callable"
			);
		}
	}

	public function provideNotificationTypes() {
		global $wgEchoNotifications;

		$result = [];
		foreach ( $wgEchoNotifications as $type => $info ) {
			$result[] = [ $type, $info ];
		}

		return $result;
	}
}

Add a test to validate $wgEchoNotifications

Change-Id: I7c9f76f4222f692a2babf47618b869f4c963499f


<?php

namespace JPB\WpBehatExtension\Context;

use Behat\MinkExtension\Context\RawMinkContext;

class UserContext extends RawMinkContext {

	use Traits\UserContext;

}

Add a standalone user context

Add a standalone user context


<?php

/*
 * This file is part of the package bk2k/bootstrap-package.
 *
 * For the full copyright and license information, please read the
 * LICENSE file that was distributed with this source code.
 */

defined('TYPO3_MODE') || die();

/***************
 * Default TypoScript
 */
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
    'bootstrap_package',
    'Configuration/TypoScript',
    'Bootstrap Package'
);

<?php

/*
 * This file is part of the package bk2k/bootstrap-package.
 *
 * For the full copyright and license information, please read the
 * LICENSE file that was distributed with this source code.
 */

defined('TYPO3_MODE') || die();

/***************
 * Default TypoScript
 */
// @extensionScannerIgnoreLine
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
    'bootstrap_package',
    'Configuration/TypoScript',
    'Bootstrap Package'
);

[TASK] Remove correct addStaticFile function from extension scanner


<?php
/**
 * Kebab Framework
 *
 * LICENSE
 *
 * This source file is subject to the  Dual Licensing Model that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.kebab-project.com/licensing
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@lab2023.com so we can send you a copy immediately.
 *
 * @category   Kebab (kebab-reloaded)
 * @package    Kebab
 * @subpackage Library
 * @author     Onur Özgür ÖZKAN <onur.ozgur.ozkan@lab2023.com>
 * @copyright  Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com)
 * @license    http://www.kebab-project.com/cms/licensing
 * @version    1.5.0
 */

/**
 * Kebab_Security
 *
 * @category   Kebab (kebab-reloaded)
 * @package    Kebab
 * @subpackage Library
 * @author     Onur Özgür ÖZKAN <onur.ozgur.ozkan@lab2023.com>
 * @copyright  Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com)
 * @license    http://www.kebab-project.com/cms/licensing
 * @version    1.5.0
 */

final class Kebab_Security
{
    public static function createActivationKey($lenght = 15)
    {
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double)microtime()*1000000);
        $i = 0;
        $retVal = '' ;

        while ($i <= $lenght) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $retVal = $retVal . $tmp;
            $i++;
        }

        return $retVal;
    }
}

Add security class which generate activationKey and password


<?php

namespace Hodor\MessageQueue\Adapter\Amqp;

use PHPUnit_Framework_TestCase;

class ChannelTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::__construct
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::getAmqpChannel
     */
    public function testAmqpChannelPassedToConstructorIsTheSameRetrieved()
    {
        $amqp_channel = $this
            ->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
            ->disableOriginalConstructor()
            ->getMock();
        $channel = new Channel($amqp_channel, []);

        $this->assertSame($amqp_channel, $channel->getAmqpChannel());
    }

    /**
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::__construct
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::getQueueName
     */
    public function testQueueNamePassedToConstructorIsTheSameRetrieved()
    {
        $queue_name = uniqid();

        $amqp_channel = $this
            ->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
            ->disableOriginalConstructor()
            ->getMock();
        $channel = new Channel($amqp_channel, ['queue_name' => $queue_name]);

        $this->assertEquals($queue_name, $channel->getQueueName());
    }

    /**
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::__construct
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::getMaxMessagesPerConsume
     */
    public function testMaxMessagesPerConsumePassedToConstructorIsTheSameRetrieved()
    {
        $max_messages = rand(1, 100);

        $amqp_channel = $this
            ->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
            ->disableOriginalConstructor()
            ->getMock();
        $channel = new Channel($amqp_channel, ['max_messages_per_consume' => $max_messages]);

        $this->assertEquals($max_messages, $channel->getMaxMessagesPerConsume());
    }

    /**
     * __construct
     * @covers Hodor\MessageQueue\Adapter\Amqp\Channel::getMaxTimePerConsume
     */
    public function testMaxTimePerConsumePassedToConstructorIsTheSameRetrieved()
    {
        $max_time = rand(1, 100);

        $amqp_channel = $this
            ->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
            ->disableOriginalConstructor()
            ->getMock();
        $channel = new Channel($amqp_channel, ['max_time_per_consume' => $max_time]);

        $this->assertEquals($max_time, $channel->getMaxTimePerConsume());
    }
}

Add tests for Amqp Channel adapter

Add tests for Amqp Channel adapter


<?php namespace spec\CeesVanEgmond\Minify\Providers;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use org\bovigo\vfs\vfsStream;

class JavaScriptSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('CeesVanEgmond\Minify\Providers\JavaScript');
    }

    function it_adds_one_file()
    {
        vfsStream::setup('js',null, array(
            '1.js' => 'a',
        ));

        $this->add(VfsStream::url('js'));
        $this->shouldHaveCount(1);
    }

    function it_adds_multiple_files()
    {
        vfsStream::setup('root',null, array(
            '1.js' => 'a',
            '2.js' => 'b',
        ));

        $this->add(array(
            VfsStream::url('root/1.js'),
            VfsStream::url('root/2.js')
        ));

        $this->shouldHaveCount(2);
    }

    function it_adds_custom_attributes()
    {
        $this->tag('file', array('foobar' => 'baz', 'defer' => true))
            ->shouldReturn('<script src="file" foobar="baz" defer></script>' . PHP_EOL);
    }

    function it_adds_without_custom_attributes()
    {
      $this->tag('file', array())
            ->shouldReturn('<script src="file"></script>' . PHP_EOL);
    }

    function it_throws_exception_when_file_not_exists()
    {
        $this->shouldThrow('CeesVanEgmond\Minify\Exceptions\FileNotExistException')
            ->duringAdd('foobar');
    }

    function it_should_throw_exception_when_buildpath_not_exist()
    {
        $this->shouldThrow('CeesVanEgmond\Minify\Exceptions\DirNotExistException')
            ->duringMake('bar');
    }

    function it_should_throw_exception_when_buildpath_not_writable()
    {
        vfsStream::setup('js',0555, array());

        $this->shouldThrow('CeesVanEgmond\Minify\Exceptions\DirNotWritableException')
            ->duringMake(vfsStream::url('js'));
    }

    function it_minifies_multiple_files()
    {
        vfsStream::setup('root',null, array(
            'output' => array(),
            '1.js' => 'a',
            '2.js' => 'b',
        ));

        $this->add(vfsStream::url('root/1.js'));
        $this->add(vfsStream::url('root/2.js'));

        $this->make(vfsStream::url('root/output'));

        $this->getAppended()->shouldBe('ab');

        $output = md5('vfs://root/1.js-vfs://root/2.js');
        $filemtime = filemtime(vfsStream::url('root/1.js')) + filemtime(vfsStream::url('root/2.js'));
        $extension = '.js';

        $this->getFilename()->shouldBe($output . $filemtime . $extension);
    }
}

Create tests for the javascript

Create tests for the javascript


<?php namespace Flarum\Core\Groups;

use Flarum\Core\Model;
use Illuminate\Database\Eloquent\Builder;

/**
 * @todo document database columns with @property
 */
class Permission extends Model
{
    /**
     * {@inheritdoc}
     */
    protected $table = 'permissions';

    /**
     * Define the relationship with the group that this permission is for.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo('Flarum\Core\Groups\Group', 'group_id');
    }

    /**
     * Set the keys for a save update query.
     *
     * @param Builder $query
     * @return Builder
     */
    protected function setKeysForSaveQuery(Builder $query)
    {
        $query->where('group_id', $this->group_id)
              ->where('permission', $this->permission);

        return $query;
    }

    /**
     * Get a map of permissions to the group IDs that have them.
     *
     * @return array[]
     */
    public static function map()
    {
        $permissions = [];

        foreach (static::get() as $permission) {
            $permissions[$permission->permission][] = $permission->group_id;
        }

        return $permissions;
    }
}

<?php namespace Flarum\Core\Groups;

use Flarum\Core\Model;
use Illuminate\Database\Eloquent\Builder;

/**
 * @todo document database columns with @property
 */
class Permission extends Model
{
    /**
     * {@inheritdoc}
     */
    protected $table = 'permissions';

    /**
     * Define the relationship with the group that this permission is for.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo('Flarum\Core\Groups\Group', 'group_id');
    }

    /**
     * Set the keys for a save update query.
     *
     * @param Builder $query
     * @return Builder
     */
    protected function setKeysForSaveQuery(Builder $query)
    {
        $query->where('group_id', $this->group_id)
              ->where('permission', $this->permission);

        return $query;
    }

    /**
     * Get a map of permissions to the group IDs that have them.
     *
     * @return array[]
     */
    public static function map()
    {
        $permissions = [];

        foreach (static::get() as $permission) {
            $permissions[$permission->permission][] = (string) $permission->group_id;
        }

        return $permissions;
    }
}

Convert permission IDs into strings

Convert permission IDs into strings


<?php

namespace OpenConext\EngineBlock\Doctrine\Migrations;

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

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

        // Remove old liquibase tables: see f673f8a
        $this->addSql('DROP TABLE IF EXISTS DATABASECHANGELOG');
        $this->addSql('DROP TABLE IF EXISTS DATABASECHANGELOGLOCK');
    }

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

Drop old LiquiBase migration tables

Drop old LiquiBase migration tables

LiquiBase was removed in f673f8a, but on some environments the tables
were never removed. This migration removes the tables if they exist.


<?php
declare(strict_types=1);

namespace Onion\Framework\Hydrator;

/**
 * Hydrates and extracts objects using getters and setters
 */
trait MethodHydrator
{
    /**
     * Hydrates the object with the $data provided
     *
     * @param array $data Assoc array with param
     *
     * @return $this A hydrated copy of the object provided
     */
    public function hydrate(array $data)
    {
        $target = clone $this;
        foreach ($data as $name => $value) {
            // Transform underscored keys to camelCase
            $method = str_replace('_', '', ucfirst(ucwords($name, '_')));
            if (method_exists($target, 'set' . $method)) {
                $target->{'set' . $method}(...(array) $value);
            }
        }

        return $target;
    }

    /**
     * Extracts all data from the $object or extracts only
     * the provided $keys
     *
     * @param array  $keys List of keys with which to filter the extracted keys
     *
     * @return array The extracted data
     */
    public function extract(array $keys = []): array
    {
        $data = [];

        if ($keys === []) {
            $reflection = new \ReflectionObject($this);
            foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
                if (0 === strpos($method->getName(), 'get')) {
                    $data[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', substr($method->getName(), 3)))] =
                        $method->invoke($this);
                }
            }

            return $data;
        }

        foreach ($keys as $name) {
            if (method_exists($this, 'get' . ucfirst(str_replace('_', '', ucwords($name))))) {
                $data[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name))] = call_user_func([
                    $this,
                    'get' . str_replace('_', '', ucfirst(ucwords($name, '_')))
                ]);
            }
        }

        return $data;
    }
}

Add hydrator that (de)hydrates the object using getters/setters


<?php
namespace Laranix\Installer;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register providers.
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap app events.
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->commands([
                InstallLaranixCommand::class,
            ]);
        }
    }
}

Add new service provider to register install command


<?php
require_once '../includes/master.inc.php';

$db = Database::getDatabase();
$result = $db->getRows("select tags from search where 1=1");

$tags = array();

foreach($result as $row){
    $tmp = explode(';', $row['tags']);
    foreach($tmp as $tg){
        if(isset($tags[$tg]))
            $tags[$tg]++;
        else
            $tags[$tg] = 1;
    }
}

echo json_encode($tags);

?>

Add backend for tag cloud

Add backend for tag cloud


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name:  Ion Auth Lang - Chinese Traditional
*
* Author: Bo-Yi Wu
* 		  appleboy.tw@gmail.com
*         @taiwan
*
* Location: http://github.com/benedmunds/ion_auth/
*
* Created:  03.14.2011
*
* Description:  Chinese language file for Ion Auth messages and errors
*
*/

// Account Creation
$lang['account_creation_successful'] 	  	 = '帳號建立成功';
$lang['account_creation_unsuccessful'] 	 	 = '無法建立帳號';
$lang['account_creation_duplicate_email'] 	 = '電子郵件已被使用或不合法';
$lang['account_creation_duplicate_username'] 	 = '帳號已存在或不合法';

// Password
$lang['password_change_successful'] 	 	 = '密碼變更成功';
$lang['password_change_unsuccessful'] 	  	 = '密碼變更失敗';
$lang['forgot_password_successful'] 	 	 = '密碼已重設，請收取電子郵件';
$lang['forgot_password_unsuccessful'] 	 	 = '密碼重設失敗';

// Activation
$lang['activate_successful'] 		  	 = '帳號已啟動';
$lang['activate_unsuccessful'] 		 	 = '啟動帳號失敗';
$lang['deactivate_successful'] 		  	 = '帳號已關閉';
$lang['deactivate_unsuccessful'] 	  	 = '關閉帳號失敗';
$lang['activation_email_successful'] 	  	 = '已寄送啟動帳號電子郵件';
$lang['activation_email_unsuccessful']   	 = '啟動帳號電子郵件失敗';

// Login / Logout
$lang['login_successful'] 		  	 = '登入成功';
$lang['login_unsuccessful'] 		  	 = '登入失敗';
$lang['logout_successful'] 		 	 = '登出成功';

// Account Changes
$lang['update_successful'] 		 	 = '帳號資料更新成功';
$lang['update_unsuccessful'] 		 	 = '更新帳號資料失敗';
$lang['delete_successful'] 		 	 = '帳號已刪除';
$lang['delete_unsuccessful'] 		 	 = '刪除帳號失敗';

Add Chinese Traditional language file

Add Chinese Traditional language file


<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Column;

use Sorien\DataGridBundle\Grid\Action\RowAction;

class ActionsColumn extends Column
{
    private $rowActions;

    public function __construct($column, $title, array $rowActions = array())
    {
        $this->rowActions = $rowActions;
        parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
    }

    public function getRouteParameters($row, $action)
    {
        $actionParameters = $action->getRouteParameters();
        if(!empty($actionParameters)){
            $routeParameters = array();
            foreach ($actionParameters as $name => $parameter) {
                if(is_numeric($name)){
                    $routeParameters[$parameter] = $row->getField($parameter);
                } else {
                    $routeParameters[$name] = $parameter;
                }
            }
        }

        return array_merge(
            array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
            $routeParameters
        );
    }

    public function getRowActions()
    {
        return $this->rowActions;
    }

    public function setRowActions(array $rowActions) {
        $this->rowActions = $rowActions;
    }

    public function getType()
    {
        return 'actions';
    }
}

<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Column;

use Sorien\DataGridBundle\Grid\Action\RowAction;

class ActionsColumn extends Column
{
    private $rowActions;

    public function __construct($column, $title, array $rowActions = array())
    {
        $this->rowActions = $rowActions;
        parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
    }

    public function getRouteParameters($row, $action)
    {
        $actionParameters = $action->getRouteParameters();
        if(!empty($actionParameters)){
            $routeParameters = array();
            foreach ($actionParameters as $name => $parameter) {
                if(is_numeric($name)){
                    $routeParameters[$parameter] = $row->getField($parameter);
                } else {
                    $routeParameters[$name] = $parameter;
                }
            }
            return $routeParameters;
        }

        return array_merge(
            array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
            $action->getRouteParameters()
        );
    }

    public function getRowActions()
    {
        return $this->rowActions;
    }

    public function setRowActions(array $rowActions) {
        $this->rowActions = $rowActions;
    }

    public function getType()
    {
        return 'actions';
    }
}

Revert - Fix route parameters for a row action


<?php
require_once "lib/page/SpotPage_Abs.php";

class SpotPage_markallasread extends SpotPage_Abs {

	function render() {
		$_SESSION['last_visit'] = time();
		echo "<xml><return>ok</return></xml>";
	} # render()

} # SpotPage_markallasread

Mark all as read button toegevoegd.

Mark all as read button toegevoegd.


<?php

namespace Bernard;

/**
 * Builder of middleware. Takes any number of Callables and handles
 * them as factories returning a new invokable.
 *
 * @package Raven
 */
class Middleware
{
    protected $factories;

    /**
     * @param callable[] $factories
     */
    public function __construct(array $factories = array())
    {
        $this->factories = array();

        array_map(array($this, 'add'), $factories);
    }

    /**
     * @param callable $factory
     */
    public function add($factory)
    {
        Assert::assertCallable($factory);

        $this->factories[] = $factory;
    }

    /**
     * Creates the chain a returns the wrapped callable.
     *
     * @param callable $callable
     * @return callable
     */
    public function wrap($callable)
    {
        Assert::assertCallable($callable);

        $factories = $this->factories;

        array_reverse($factories);

        return array_reduce($factories, array($this, 'reduce'), $callable);
    }

    /**
     * Reduces the $factory and $callable into a single
     * $callable and effectively creating a chain.
     *
     * @param callable $callable
     * @param callable $factory
     */
    public function reduce($callable, $factory)
    {
        Assert::assertCallable($factory);
        Assert::assertCallable($callable);

        return $factory($callable);
    }
}

Add middleware class that knows how to create chain of command.


<?php namespace Illuminate\Pagination;

use Illuminate\Http\Request;
use Illuminate\View\Factory as ViewFactory;
use Symfony\Component\Translation\TranslatorInterface;

class Environment extends Factory {

	/**
	 * Create a new pagination factory.
	 *
	 * @param  \Symfony\Component\HttpFoundation\Request  $request
	 * @param  \Illuminate\View\Factory  $view
	 * @param  \Symfony\Component\Translation\TranslatorInterface  $trans
	 * @param  string  $pageName
	 * @return void
	 */
	public function __construct(Request $request, ViewFactory $view, TranslatorInterface $trans, $pageName = 'page')
	{
		parent::__construct($request, $view, $trans, $pageName);
	}

}

<?php namespace Illuminate\Pagination;

use Illuminate\Http\Request;
use Illuminate\View\Factory as ViewFactory;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * DEPRECATED: Please use Illuminate\Pagination\Factory instead!
 */
class Environment extends Factory {

	/**
	 * Create a new pagination factory.
	 *
	 * @param  \Symfony\Component\HttpFoundation\Request  $request
	 * @param  \Illuminate\View\Factory  $view
	 * @param  \Symfony\Component\Translation\TranslatorInterface  $trans
	 * @param  string  $pageName
	 * @return void
	 */
	public function __construct(Request $request, ViewFactory $view, TranslatorInterface $trans, $pageName = 'page')
	{
		parent::__construct($request, $view, $trans, $pageName);
	}

}

Add doc block for deprecation.

Add doc block for deprecation.


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Views;

use Codeception\Util\Stub;
use GrottoPress\Jentil\AbstractTestCase;
use GrottoPress\Jentil\AbstractTheme;
use GrottoPress\Jentil\Utilities\Utilities;
use GrottoPress\Jentil\Utilities\Page\Page;
use tad\FunctionMocker\FunctionMocker;

class AuthorTest extends AbstractTestCase
{
    public function testRun()
    {
        $add_action = FunctionMocker::replace('add_action');

        $author = new Author(Stub::makeEmpty(AbstractTheme::class));

        $author->run();

        $add_action->wasCalledOnce();

        $add_action->wasCalledWithOnce([
            'jentil_before_title',
            [$author, 'renderAvatar']
        ]);
    }

    /**
     * @dataProvider renderAvatarProvider
     */
    public function testRenderAvatar(string $page)
    {
        $get_avatar = FunctionMocker::replace('get_avatar');
        $get_query_var = FunctionMocker::replace('get_query_var', 'var');

        $jentil = Stub::makeEmpty(AbstractTheme::class, [
            'utilities' => Stub::makeEmpty(Utilities::class),
        ]);

        $jentil->utilities->page = Stub::makeEmpty(Page::class, [
            'is' => function (string $type) use ($page): bool {
                return ($page === $type);
            }
        ]);

        $author = new Author($jentil);

        $author->renderAvatar();

        if ('author' === $page) {
            $get_avatar->wasCalledOnce();
            $get_avatar->wasCalledWithOnce(['var', 60]);

            $get_query_var->wasCalledOnce();
            $get_query_var->wasCalledWithOnce(['author']);
        } else {
            $get_avatar->wasNotCalled();
            $get_query_var->wasNotCalled();
        }
    }

    public function renderAvatarProvider()
    {
        return [
            'page is author' => ['author'],
            'page is not author' => ['home'],
        ];
    }
}

Add tests for author view setup

Add tests for author view setup


<?php
include('_inc.php');

use Oppa\Database;

$cfg = [
    'agent'    => 'pgsql',
    'database' => [
        'host'     => 'localhost',  'name'     => 'test',
        'username' => 'test',       'password' => '********',
        'charset'  => 'utf8',       'timezone' => '+00:00',
    ],
    // 'map_result' => true,
    // 'map_result_bool' => true,
];

$db = new Database($cfg);
$db->connect();

$agent = $db->getLink()->getAgent();
// pre($agent);
// $agent->disconnect();
// pre($agent->getResource()->isValid());

$result = $agent->query("select * from users");
// $result = $agent->query("insert into users(name,old) values('foo',10),('ffo',11)");
// $result = $agent->query("delete from users where id > 3");
// pre($result);
// pre($agent->getResource());
// pre($result->getResult());
// pre($result->getId());
// pre($result->getIds());
// pre($result->getData());

Add test file for get*() methods.

Add test file for get*() methods.


<?php

namespace CommerceGuys\AuthNet\Tests\DataType;

use CommerceGuys\AuthNet\DataTypes\CreditCard;
use CommerceGuys\AuthNet\DataTypes\LineItem;
use CommerceGuys\AuthNet\DataTypes\TransactionRequest;

/**
 * Tests the transaction request
 */
class TransactionRequestTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Tests ::addPayment
     */
    public function testAddPayment()
    {
        $transactionRequest = new TransactionRequest([]);
        $transactionRequest->addPayment(new CreditCard([
            'cardNumber' => 'XXXX1111',
            'expirationDate' => '0122',
            'cardCode' => '123',
        ]));

        $array = $transactionRequest->toArray();
        $this->assertEquals([
            'cardNumber' => 'XXXX1111',
            'expirationDate' => '0122',
            'cardCode' => '123',
        ], $array['payment']['creditCard']);
    }

    public function testAddLineItem()
    {
        $transactionRequest = new TransactionRequest([]);
        $sampleLineItems = [
            new LineItem(['name' => 'test1', 'description' => 'testing']),
            new LineItem(['name' => 'test2', 'description' => 'testing']),
            new LineItem(['name' => 'test3', 'description' => 'testing']),
        ];
        foreach ($sampleLineItems as $sampleLineItem) {
            $transactionRequest->addLineItem($sampleLineItem);
        }

        $array = $transactionRequest->toArray();
        $this->assertCount(3, $array['lineItems']);
        $this->assertEquals([
            'lineItem' => [
                'name' => 'test1',
                'description' => 'testing',
            ]
        ], $array['lineItems'][0]);
        $this->assertEquals([
            'lineItem' => [
                'name' => 'test2',
                'description' => 'testing',
            ]
        ], $array['lineItems'][1]);
        $this->assertEquals([
            'lineItem' => [
                'name' => 'test3',
                'description' => 'testing',
            ]
        ], $array['lineItems'][2]);
    }

}

Add test coverage to addLineItem

Add test coverage to addLineItem


<?php

/*
 * Encog(tm) Core v3.3 - PHP Version
 * https://github.com/katrinaniolet/encog-php-core
 *
 * http://www.heatonresearch.com/encog/
 * https://github.com/encog/encog-java-core
 *
 * Copyright 2008-2014 Heaton Research, Inc.
 * PHP port by Katrina Niolet <katrina@kf5utn.net>
 *
 * 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.
 *
 * For more information on Heaton Research copyrights, licenses
 * and trademarks visit:
 * http://www.heatonresearch.com/copyright
 */
namespace Encog\Util\EngineArray;

function arrayCopy(array $src, array &$dst) {
	$dst = $src;
}

function arrayCopyMid(array $source, $sourcePos, array &$target, $targetPos, $length) {
	for($i=0;$i<$length;++$i) {
		$target[$i+$targetPos] = $source[$i+$sourcePos];
	}
}

Work toward getting the ADALINE network unit test to pass


<?php

use Clue\Redis\Server\Client;
use Clue\Redis\Server\Factory;
use Clue\Redis\Server\Server;
use Clue\Redis\Protocol\Model\ModelInterface;

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

$loop = React\EventLoop\Factory::create();
$factory = new Factory($loop);

$address = '127.0.0.1:1337';

$factory->createServer($address)->then(function(Server $server) use ($address) {
    echo 'server listening on ' . $address . '!' . PHP_EOL;

    $server->on('connection', function ($client) {
        echo 'client connected' . PHP_EOL;
    });

    $server->on('error', function ($error, $client) {
        echo 'ERROR: ' . $error->getMessage() . PHP_EOL;
    });

    $server->on('request', function (ModelInterface $request, Client $client) {
        echo $client->getRequestDebug($request) . PHP_EOL;
    });

    $server->on('disconnection', function ($client) {
        echo 'client disconnected' . PHP_EOL;
    });
});

$loop->run();

<?php

use Clue\Redis\Server\Client;
use Clue\Redis\Server\Factory;
use Clue\Redis\Server\Server;
use Clue\Redis\Protocol\Model\ModelInterface;

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

$loop = React\EventLoop\Factory::create();
$factory = new Factory($loop);

$address = '127.0.0.1:1337';
$debug = false;

$factory->createServer($address)->then(function(Server $server) use ($address, $debug) {
    echo 'server listening on ' . $address . '!' . PHP_EOL;

    echo 'you can now connect to this server via redis-cli, redis-benchmark or any other redis client' . PHP_EOL;

    if ($debug) {
        echo 'Debugging is turned on, this will significantly decrease performance' . PHP_EOL;

        $server->on('connection', function ($client) {
            echo 'client connected' . PHP_EOL;
        });

        $server->on('error', function ($error, $client) {
            echo 'ERROR: ' . $error->getMessage() . PHP_EOL;
        });

        $server->on('request', function (ModelInterface $request, Client $client) {
            echo $client->getRequestDebug($request) . PHP_EOL;
        });

        $server->on('disconnection', function ($client) {
            echo 'client disconnected' . PHP_EOL;
        });
    } else {
        echo 'Debugging is turned off, so you should not see any further output' . PHP_EOL;
    }
});

$loop->run();

Add $debug option (which now defaults to false)


<?php
/**
 * @package Neolao\Site\Helper\View
 */
namespace Neolao\Site\Helper\View;

use \Neolao\Logger;
use \Neolao\Site\Helper\View\AbstractHelper;
use \Neolao\Site\Request;
use \Neolao\Site;

/**
 * Helper to get the reverse URL of a route
 */
class RouteReverseHelper extends AbstractHelper
{
    /**
     * Get the reverse  URL of the specified route
     * (access point of the view helper)
     *
     * @param   string  $route      The route
     * @return  string              The reverse URL
     */
    public function main($route)
    {
        // Get the request instance
        $view = $this->getView();
        if ($view->site instanceof Site === false) {
            return 'error';
        }
        if ($view->site->request instanceof Request === false) {
            return '';
        }
        $request = $view->site->request;

        // Get the route name
        $routeArray = explode(',', $route);
        $routeName = array_shift($routeArray);
        $routeName = trim($routeName);

        // Get the parameters
        $parameters = [];
        if (count($routeArray) > 0) {
            foreach ($routeArray as $parameter) {
                list($key, $value) = explode(':', $parameter);
                $key = trim($key);
                $value = trim($value);
                $parameters[$key] = $value;
            }
        }

        // Get the reverse URL
        $url = $request->reverseRoute($routeName, $parameters);

        return $url;
    }

}

Add a view helper to get a reverse URL from a route


<?php

class Router {

    /**
     * Parse the URL query string and store the key->val pairs
     * into an array, then redirect
     */
    public function reroute() {
        $params = array();
        parse_str($_SERVER['QUERY_STRING'], $params);
        $this->_redirect($params);
    }

    /**
     * Redirect to the URL passed in the 'state' parameter
     * when we're redirected here from SoundCloud
     *
     * @param $params array array of URL query parameters
     */
    private function _redirect($params) {
        $url = urldecode($params['state']);
        header("Location: $url?" . $_SERVER['QUERY_STRING']);
    }

}

(new Router())->reroute();

Add soundcloud callback file for saas routing


<?php

/**
 * @copyright Eliel de Paula <dev@elieldepaula.com.br>
 * @license http://wpanel.org/license
 */

defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Migration_Targetmenu class.
 *
 * This class add target to the menu items.
 *
 * @author Eliel de Paula <dev@elieldepaula.com.br>
 */
class Migration_Targetmenu extends CI_Migration
{

    /**
     * New field
     * @var array[]
     */
    protected $fields = [
        'target' => [
            'type' => 'varchar',
            'constraint' => 10,
            'comment' => 'Link _target property.',
            'AFTER' => 'href',
            'default' => '_self',
            'null' => true
        ]
    ];

    /**
     * Run migration.
     */
    public function up()
    {
        $this->dbforge->add_column('menu_itens', $this->fields);
        $this->db->update('menu_itens', ['target' => '_self']);
    }

    /**
     * Rollback migration
     */
    public function down()
    {
        $this->dbforge->drop_column('menu_itens', 'target', TRUE);
    }

}

Add migration to add target file into menu_itens table.


<?php

use lithium\core\Libraries;
use lithium\action\Dispatcher;
use lithium\action\Response;

use li3_less\core\Less;

/**
 * Here we check, if there is a library called `li3_less`
 *
 * If that is the case, we can directly work with the
 * less files, that is much more flexible. To get this
 * up and running, you need to add li3_less as a library
 * and load it _before_ the li3_bootstrap library like this:
 *
 *     Libraries::add('li3_less');
 *     Libraries::add('li3_bootstrap');
 *
 */
if (is_null($config = Libraries::get('li3_less'))) {
	return; // what a pity - it is not.
}

define('LI3_BOOTSTRAP_PATH', dirname(__DIR__));

Dispatcher::applyFilter('run', function($self, $params, $chain) {

	if(!strstr($params['request']->url, '.css')) {
		return $chain->next($self, $params, $chain);
	}

	// look for a matching less file
	$basename = basename($params['request']->url);
	$less_path =  LI3_BOOTSTRAP_PATH.'/webroot/less';
	$less_file = str_replace('.css', '.less', "$less_path/$basename");
	if(!file_exists($less_file)) {
		return $chain->next($self, $params, $chain);
	}

	// found, so we parse this file
	$output = Less::file($less_file, array('cache' => true));
	return new Response(array(
		'body' => $output,
		'headers' => array('Content-type' => 'text/css')
	));
});

Apply filter for using .less files, needs li3_less


#!/usr/bin/env php
<?php
/* PHPUnit
 *
 * Copyright (c) 2002-2009, Sebastian Bergmann <sb@sebastian-bergmann.de>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   * Neither the name of Sebastian Bergmann nor the names of his
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 */

require 'PHPUnit/Util/FilterIterator.php';

$stub = <<<ENDSTUB
#!/usr/bin/env php
<?php
Phar::mapPhar('phpunit.phar');
require 'phar://phpunit.phar/TextUI/Command.php';
PHPUnit_TextUI_Command::main();
__HALT_COMPILER();
ENDSTUB;

$phar = new Phar('phpunit.phar', 0, 'phpunit.phar');
$phar->startBuffering();

$phar->buildFromIterator(
  new PHPUnit_Util_FilterIterator(
    new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator('PHPUnit')
    )
  ),
  dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PHPUnit'
);

$phar->setStub($stub);
$phar->stopBuffering();
?>

Add script to generate a PHP Archive (PHAR).


<?php

use App\Utils\RawMigration;

class AddNessusScanner extends RawMigration
{
    /**
     * @inheritdoc
     * @return string
     */
    public function getRawSqlMigration()
    {
        return <<<SQL
INSERT INTO `scanner_apps` (`name`, `description`, `created_at`, `updated_at`) VALUES
('nessus', 'Nessus Vulnerability Scanner', NOW(), NOW());
SQL;

    }
}

Add Nessus scanner to scanner_apps table


#!/usr/bin/env php
<?php

use Socket\Raw\Factory;

error_reporting(-1);

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

$factory = new Factory();
$socket = $factory->createClient('www.google.com:80');

echo 'Client connected to ' . $socket->getPeerName() . PHP_EOL . PHP_EOL;

$socket->write("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n");

var_dump($socket->read(8192));

$socket->close();

Add simple TCP/IP client example

Add simple TCP/IP client example


<?php

function __autoload($className) {
  echo $className;
  exit();
}

function test() {
  $xsl = new DomDocument();
  $xsl->loadXML('<?xml version="1.0" encoding="iso-8859-1" ?>
  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:php="http://php.net/xsl">
  <xsl:template match="/">
  <xsl:value-of select="php:function(\'TeSt::dateLang\')" />
  </xsl:template>
  </xsl:stylesheet>');
  $inputdom = new DomDocument();
  $inputdom->loadXML('<?xml version="1.0" encoding="iso-8859-1" ?>
  <today></today>');

  $proc = new XsltProcessor();
  $proc->registerPhpFunctions();
  $xsl = $proc->importStylesheet($xsl);
  $newdom = $proc->transformToDoc($inputdom);
}

test();

Add XSLT test on __autoload

Add XSLT test on __autoload


<?php
/**
 * @copyright Copyright (C) 2015-2019 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 */
declare(strict_types=1);

use app\components\db\Migration;

class m190529_131023_festpower_index extends Migration
{
    public function safeUp()
    {
        $this->execute(
            'CREATE INDEX {{battle2_festpower_diff}} ON {{battle2}} ' .
            '(ABS([[my_team_estimate_fest_power]] - [[his_team_estimate_fest_power]])) ' .
            'WHERE ((' . implode(') AND (', [
                '[[my_team_estimate_fest_power]] IS NOT NULL',
                '[[his_team_estimate_fest_power]] IS NOT NULL',
                '[[is_win]] IS NOT NULL',
                '[[period]] IS NOT NULL',
            ]) . '))'
        );
    }

    public function safeDown()
    {
        $this->execute('DROP INDEX {{battle2_festpower_diff}}');
    }
}

Create index for Splatfest power diff page


<?php

declare(strict_types=1);

namespace Keboola\Test\Common;

use Keboola\Test\StorageApiTestCase;

class JobsListTest extends StorageApiTestCase
{
    public function testJobsListing(): void
    {
        $jobs = $this->_client->listJobs();

        // the default limit is 20 jobs
        $this->assertLessThanOrEqual(20, count($jobs));

        // get only 5 jobs
        $fiveJobs = $this->_client->listJobs(["limit" => 5]);
        $this->assertLessThanOrEqual(5, count($fiveJobs));

        //if there are at least 2 jobs we can check the offset parameter
        if (count($fiveJobs) >= 2) {
            $firstJob = $fiveJobs[0];
            $secondJob = $fiveJobs[1];
            $offsetJobs = $this->_client->listJobs(["limit" => 5, "offset" => 1]);
            $this->assertNotEquals($firstJob, $offsetJobs[0]);
            $this->assertEquals($secondJob, $offsetJobs[0]);
        }
    }
}

Add test for jobs list limit and offset

Add test for jobs list limit and offset


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

use Illuminate\Database\Seeder;

/**
 * This is the portuguese municipalities table seeder class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class PtMunicipalitiesTableSeeder extends Seeder
{
    public function run()
    {
        $this->call('Municipalities\AngraDoHeroismo');
        $this->call('Municipalities\Aveiro');
        $this->call('Municipalities\Beja');
        $this->call('Municipalities\Braga');
        $this->call('Municipalities\Braganca');
        $this->call('Municipalities\CasteloBranco');
        $this->call('Municipalities\Coimbra');
        $this->call('Municipalities\Evora');
        $this->call('Municipalities\Faro');
        $this->call('Municipalities\Funchal');
        $this->call('Municipalities\Guarda');
        $this->call('Municipalities\Horta');
        $this->call('Municipalities\Leiria');
        $this->call('Municipalities\Lisboa');
        $this->call('Municipalities\PontaDelgada');
        $this->call('Municipalities\Portalegre');
        $this->call('Municipalities\Porto');
        $this->call('Municipalities\Santarem');
        $this->call('Municipalities\Setubal');
        $this->call('Municipalities\VianaDoCastelo');
        $this->call('Municipalities\VilaReal');
        $this->call('Municipalities\Viseu');
    }
}

Add the portuguese municipalities table seeder


<?php namespace Reshadman\EloquentFaster\Tests;

use Reshadman\EloquentFaster\RecursiveRequirer;

class RecursiveRequirerTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var RecursiveRequirer
     */
    protected $_object;

    public function setUp()
    {
        $this->_object = new RecursiveRequirer(__DIR__ . '/../src');
    }

    public function test_require_once_method()
    {
        iterator_to_array($this->_object->requireOnceAllFiles());
        $this->assertContains('Reshadman\EloquentFaster\FasterModel', $classes = get_declared_classes());
        $this->assertContains('Reshadman\EloquentFaster\EloquentCacheClearCommand', $classes);
    }

}

Add test for recursive requirer.

Add test for recursive requirer.


<?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\Char;

use Zend\Console\Prompt\Select;
use ZendTest\Console\TestAssets\ConsoleAdapter;

/**
 * @category   Zend
 * @package    Zend_Console
 * @subpackage UnitTests
 * @group      Zend_Console
 */
class SelectTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ConsoleAdapter
     */
    protected $adapter;

    public function setUp()
    {
        $this->adapter = new ConsoleAdapter();
        $this->adapter->stream = fopen('php://memory', 'w+');
    }

    public function tearDown()
    {
        fclose($this->adapter->stream);
    }

    public function testCanSelectOption()
    {
        fwrite($this->adapter->stream, "0");

        $select = new Select('Select an option :', array('foo', 'bar'));
        $select->setConsole($this->adapter);
        ob_start();
        $response = $select->show();
        $text = ob_get_clean();
        $this->assertTrue((bool) preg_match('#0\) foo#', $text));
        $this->assertTrue((bool) preg_match('#1\) bar#', $text));
        $this->assertEquals('0', $response);
    }

    public function testCanSelectOptionWithCustomIndex()
    {
        fwrite($this->adapter->stream, "2");

        $select = new Select('Select an option :', array('2' => 'foo', '6' => 'bar'));
        $select->setConsole($this->adapter);
        ob_start();
        $response = $select->show();
        $text = ob_get_clean();
        $this->assertTrue((bool) preg_match('#2\) foo#', $text));
        $this->assertTrue((bool) preg_match('#6\) bar#', $text));
        $this->assertEquals('2', $response);
    }
}

Add tests to cover prompt/select

Add tests to cover prompt/select


<?php

namespace KawaiiGherkinTest\Formatter;

use KawaiiGherkin\Formatter\FeatureDescription;

final class FeatureDescriptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FeatureDescription
     */
    private $formatter;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        $this->formatter = new FeatureDescription();
    }

    public function testCanFormatFeatureDescription()
    {
        $expected =<<<EOS
Feature: How to be a kawai person
    In order to be a kawai person
    As a non-kawai person
    I have to turn me a PHP programmer
EOS;

        $shortDescription = 'How to be a kawai person';
        $longDescription  = [
            '           In order to be a kawai person',
            'As a non-kawai person                  ',
            '                   I have to turn me a PHP programmer',
        ];

        self::assertSame($expected, $this->formatter->format($shortDescription, $longDescription));
    }
}

Add tests for feature description formatter


<?php defined('SYSPATH') or die ('No direct script access.');

/**
 * Another ACL
 *
 * @see			http://github.com/banks/aacl
 * @package		AACL
 * @uses		Auth
 * @uses		Jelly
 * @author		Paul Banks
 * @copyright	(c) Paul Banks 2010
 * @license		MIT
 */
class AACL extends AACL_Core
{
}

Create main AACL class extender

Create main AACL class extender


<?php
/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Clastic\NodeBundle\Node;

use Clastic\NodeBundle\Entity\Node;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
trait NodeReferenceTrait
{
    /**
     * @var Node
     */
    private $node;

    /**
     * @return Node
     */
    public function getNode()
    {
        return $this->node;
    }

    /**
     * @param Node $node
     */
    public function setNode(Node $node)
    {
        $this->node = $node;
    }
}

[Node] Add trait to simplify NodeReference Entities.


<?php

namespace App\Testing\Concerns;

use MessagePack\Packer;
use MessagePack\BufferUnpacker;
use PHPUnit\Framework\Assert as PHPUnit;

trait MessagePack
{
    /**
     * Assert that the response contains msgpack.
     *
     * @param  array|null  $data
     * @return $this
     */
    protected function shouldReturnMsgPack(array $data = null)
    {
        return $this->receiveMsgPack($data);
    }

    /**
     * Assert that the response contains msgpack.
     *
     * @param  array|null  $data
     * @return $this|null
     */
    protected function receiveMsgPack($data = null)
    {
        return $this->seeMsgPack($data);
    }

    /**
     * Assert that the response contains an exact msgpack array.
     *
     * @param  array  $data
     * @return $this
     */
    public function seeMsgPackEquals(array $data)
    {
        $packer = new Packer();

        try {
            $packed = $packer->pack($data);
            $hex = implode("", unpack("H*", $packed));

            if ((mb_strlen($hex) % 2) === 0) {
                $str = implode(" ", str_split($hex, 2));
            }

            PHPUnit::assertEquals($str, $this->response->getContent());

        } catch (\MessagePack\Exception\PackingFailedException $e) {

            PHPUnit::assertEquals(true, false);
        }

        return $this;
    }

    /**
     * Assert that the response contains msgpack.
     *
     * @param  array|null  $data
     * @return $this
     */
    public function seeMsgPack(array $data = null)
    {
        if (is_null($data)) {
            $data = $this->response->getData();

            PHPUnit::assertNotNull($data);

            return $this;
        }

        return $this->seeMsgPackEquals($data);
    }
}

Add message pack testing concerns Add message pack testing concerns.


<?php

namespace HCLabs\Bills\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class OpenAccountType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('service', 'entity', ['class' => 'HCLabs\Bills\Model\Service'])
                ->add('accountNumber', 'text')
                ->add('recurringCharge', 'number')
                ->add('dateOpened', 'datetime')
                ->add('billingPeriod', 'choice', [
                        'choices' => [
                            'P1M' => 'Monthly',
                            'P3M' => 'Quarterly'
                        ]
                    ]
                )
                ->add('Open', 'submit');
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
                'data_class' => 'HCLabs\Bills\Command\OpenAccountCommand',
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'hclabs_bills_open_account_type';
    }

}

Create form to open account

[Form] Create form to open account


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for rest Mimic library function.
 *
 * @since 0.1.0
 */
class RestFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\rest
	 */
	public function testDroppingLast2() {
		$collection = array(0, 1, 2, 3, 4, 5, 6);
		$expected = array(2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
		$actual = F\rest($collection, 2);
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\rest
	 */
	public function testDroppingLastNeg2() {
		$collection = array(0, 1, 2, 3, 4, 5, 6);
		$expected = array(2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
		$actual = F\rest($collection, -2);
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\rest
	 */
	public function testOverArrayCount() {
		$collection = array(0, 1, 2, 3, 4, 5);
		$expected = array();
		$actual = F\rest($collection, 7);
		$this->assertEquals($expected, $actual);
	}
}

Add rest function test suite.

Add rest function test suite.


<?php

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

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

use React\EventLoop\StreamSelectLoop as EventLoop;

$server = 'tcp://127.0.0.1:6379';
$loop = new EventLoop();

$parameters = new Predis\Connection\ConnectionParameters($server);
$connection = new Predis\Async\Connection\StreamConnection($parameters, $loop);
$profile    = Predis\Profile\ServerProfile::getDefault();

$connection->connect(function ($connection) use ($profile) {
    $ping = $profile->createCommand('ping');

    $connection->executeCommand($ping, function ($response, $connection) use ($profile) {
        $echo = $profile->createCommand('echo', array($response));

        $connection->executeCommand($echo, function ($response, $connection) {
            var_dump($response);

            $connection->disconnect();
        });
    });
});

$loop->run();

Add an example for directly using connection instances.


<?php
/**
 * Created by PhpStorm.
 * User: Catalin
 * Date: 03-Jun-17
 * Time: 18:09
 */

session_start();
$tutor_id = $_SESSION["tutor_id"];
echo $tutor_id;
include ("conectare_db.php");

/* verific poza de profil a utilizatorului */
$target_dir = "../../IMG/PROFILE/";
$info = pathinfo($_FILES['fileToUpload']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $_SESSION["username"].".".$ext;
$target_file = $target_dir . $newname;
$uploadOk = 1;
echo $target_file;

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        $_SESSION["mesaj_err"] = "Fisierul nu este fisier adevarat!";
        header('Location: ../FRONT/HTML/eroare_editare.html');
        exit;
    }
}

//accept doar fisiere de tipul .jpg, .jpeg sau .png
if($ext != "jpg" && $ext != "png" && $ext != "jpeg") {
    $_SESSION["ext"] = "Extensie:" . $ext;
    $_SESSION["mesaj_err"] = "Se accepta doar formatele JPG, PNG si JPEG.";
    header('Location: ../FRONT/HTML/eroare_editare.html');
    exit;
}

$sql = 'update TUTOR set LINK = :p_img WHERE tutor_id=:tutor_id';
$stid = oci_parse($connection, $sql);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    oci_bind_by_name($stid, ":p_img", $target_file);
    oci_bind_by_name($stid, ":tutor_id", $tutor_id);
    oci_execute($stid,OCI_COMMIT_ON_SUCCESS);
} else {
    $_SESSION["mesaj_err"] = "A aparut o eroare neasteptata... Poza nu a putut fi preluata.";
    header('Location: ../FRONT/HTML/eroare_editare.html');
    exit;
}
header('Location: ../FRONT/HTML/logged_tutor_frame.html');

Add picture change functionality for tutors


<?php

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

class ChangeStringToText extends Migration
{
    private $fields = [
        'agent_place_qualifiers' => [
            'title',
        ],
        'agent_roles' => [
            'title',
        ],
        'agent_types' => [
            'title',
        ],
        'agents' => [
            'title',
            'sort_title',
        ],
        'articles' => [
            'title',
        ],
        'artwork_date_qualifiers' => [
            'title',
        ],
        'artwork_place_qualifiers' => [
            'title',
        ],
        'artwork_types' => [
            'title',
        ],
        'artworks' => [
            'main_id',
            'copyright_notice',
        ],
        'catalogues' => [
            'title',
        ],
        'category_terms' => [
            'title',
        ],
        'digital_catalogs' => [
            'title',
            'web_url',
        ],
        'digital_publication_sections' => [
            'web_url',
            'author_display',
        ],
        'educator_resources' => [
            'title',
            'web_url',
        ],
        'event_programs' => [
            'title',
        ],
        'galleries' => [
            'title',
        ],
        'generic_pages' => [
            'title',
            'web_url',
        ],
        'highlights' => [
            'title',
        ],
        'interactive_features' => [
            'title',
        ],
        'issue_articles' => [
            'title',
        ],
        'issues' => [
            'title',
        ],
        'mobile_sounds' => [
            'web_url',
        ],
        'places' => [
            'title',
        ],
        'press_releases' => [
            'title',
            'web_url',
        ],
        'printed_catalogs' => [
            'title',
            'web_url',
        ],
        'publications' => [
            'site',
            'alias',
            'web_url',
        ],
        'sections' => [
            'web_url',
        ],
        'sites' => [
            'title',
            'web_url',
        ],
        'ticketed_event_types' => [
            'title',
            'category',
        ],
        'ticketed_events' => [
            'title',
            'resource_title',
        ],
        'tours' => [
            'title',
        ],
        'wait_times' => [
            'display',
        ],
        'web_artists' => [
            'title',
        ],
    ];

    public function up()
    {
        foreach ($this->fields as $tableName => $fieldNames) {
            Schema::table($tableName, function (Blueprint $table) use ($fieldNames) {
                foreach ($fieldNames as $fieldName) {
                    $table->text($fieldName)->change();
                }
            });
        }
    }

    public function down()
    {
        foreach ($this->fields as $tableName => $fieldNames) {
            Schema::table($tableName, function (Blueprint $table) use ($fieldNames) {
                foreach ($fieldNames as $fieldName) {
                    $table->string($fieldName)->change();
                }
            });
        }
    }
}

Change unbounded `string` columns to `text` [API-310]


<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OCP\User\Backend;

use OC\User\Backend;
use OCP\IUserBackend;
use OCP\UserInterface;

abstract class AbstractBackend implements IUserBackend, UserInterface {
	public function implementsActions($actions): bool {
		$implements = 0;

		if ($this instanceof ICreateUserBackend) {
			$implements |= Backend::CREATE_USER;
		}
		if ($this instanceof ISetPasswordBackend) {
			$implements |= Backend::SET_PASSWORD;
		}
		if ($this instanceof ICheckPasswordBackend) {
			$implements |= Backend::CHECK_PASSWORD;
		}
		if ($this instanceof IGetHomeBackend) {
			$implements |= Backend::GET_HOME;
		}
		if ($this instanceof IGetDisplayNameBackend) {
			$implements |= Backend::GET_DISPLAYNAME;
		}
		if ($this instanceof ISetDisplayNameBackend) {
			$implements |= Backend::SET_DISPLAYNAME;
		}
		if ($this instanceof IProvideAvatarBackend) {
			$implements |= Backend::PROVIDE_AVATAR;
		}
		if ($this instanceof ICountUsersBackend) {
			$implements |= Backend::COUNT_USERS;
		}

		return (bool)($actions & $implements);
	}
}

Add abstract bakend to still be backwards compatible with the old logic

Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>


<?php

namespace BOSH\Console\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use BOSH\Deployment\ManifestModel;
use Symfony\Component\Yaml\Yaml;

class BoshDirectorInitDeployCommand extends AbstractDirectorDeploymentCommand
{
    protected function configure()
    {
        parent::configure()
            ->setName('boshdirector:init:deploy')
            ->setDescription('Terminate an inception server')
            ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->execCommand(
            $input,
            $output,
            'bosh:recompile',
            [
                '--deployment' => 'bosh',
            ]
        );

        $destManifest = sprintf(
            '%s/compiled/%s/%s/bosh%s.yml',
            $input->getOption('basedir'),
            $input->getOption('director'),
            $input->getOption('deployment'),
            $input->getOption('component') ? ('-' . $input->getOption('component')) : ''
        );

        passthru(
            sprintf(
                'cd %s ; bosh-init deploy %s',
                dirname($destManifest),
                basename($destManifest)
            ),
            $return_var
        );

        return $return_var;
    }
}

Add command for bosh-init deploy

Add command for bosh-init deploy


<?php

namespace ActiveCollab\DateValue\Test;

use ActiveCollab\DateValue\DateValueInterface;
use ActiveCollab\DateValue\DateValue;
use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\DateValue\DateTimeValue;
use ReflectionClass;

/**
 * @package ActiveCollab\DateValue\Test
 */
class NowTest extends TestCase
{
    /**
     * Test if now uses current timestamp
     */
    public function testRealNow()
    {
        $this->assertEquals((new DateTimeValue())->format('Y-m-d H:i:s'), date('Y-m-d H:i:s'));
    }

    /**
     * Test if now can be overriden, for test purposes
     */
    public function testTestNow()
    {
        DateTimeValue::setTestNow(new DateTimeValue('2013-10-02 11:18:32'));

        $this->assertEquals((new DateTimeValue())->format('Y-m-d H:i:s'), date('2013-10-02 11:18:32'));
    }
}

Test setTestNow() method call on DateTimeValue


<?php

namespace AppBundle\API\Delete;

use AppBundle\Entity\Data\TraitFileUpload;
use AppBundle\Entity\User\FennecUser;
use AppBundle\Entity\User\Permissions;
use AppBundle\Entity\User\Project;
use AppBundle\Service\DBVersion;

/**
 * Web Service.
 * Delete TraitFile with given internal_id from the database (user has to be logged in and owner)
 */
class TraitFile
{
    const ERROR_NOT_LOGGED_IN = "Error. You are not logged in.";

    private $data_em;

    /**
     * Projects constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->data_em = $dbversion->getDataEntityManager();
    }

    /**
    * @inheritdoc
    */
    public function execute(FennecUser $user = null, $traitFileId)
    {
        $result = array('error' => null, 'success' => null);
        if ($user === null) {
            $result['error'] = TraitFile::ERROR_NOT_LOGGED_IN;
        } else {
            $traitFileEntry = $this->data_em->getRepository(TraitFileUpload::class)->findOneBy(array(
                'fennecUserId' => $user->getId(),
                'id' => $traitFileId
            ));
            if($traitFileEntry === null){
                $result['error'] = "This trait file entry does not exist or does not belong to this user ".$user->getId();
            } else {
                $deletionDate = new \DateTime();
                $traitFileEntry->setDeletionDate($deletionDate);
                foreach($traitFileEntry->getCategoricalTraitEntries() as $entry){
                    $entry->setDeletionDate($deletionDate);
                }
                foreach($traitFileEntry->getNumericalTraitEntries() as $entry){
                    $entry->setDeletionDate($deletionDate);
                }
                $this->data_em->flush();
                $result['success'] = "Deleted trait file with id ".$traitFileId." successfully";
            }
        }
        return $result;
    }
}

Add implementation for trait file deletion


<?php
require 'flourish/fLoader.php';
require 'classes/sLoader.php';
sLoader::best();

$exceptions = array(
  'sImage' => array('determineMimeType'),
  'sNumber' => array('ordinalNumberPrefixedCallback'),
  'sORMJSON' => array('JSONToValue', 'valueToJSON'),
  'sProcessException' => array('registerCallback'),
);

foreach (get_declared_classes() as $class_name) {
  $reflect = new ReflectionClass($class_name);
  $methods = $reflect->getMethods(ReflectionMethod::IS_STATIC);

  foreach ($methods as $method) {
    if (isset($exceptions[$class_name]) && in_array($method->name, $exceptions[$class_name])) {
      continue;
    }

    if ($class_name[0] == 's' && $method->isPublic() && !$reflect->hasConstant($method->name)) {
      print $class_name.' lacks constant: '.$method->name."\n";
    }
  }
}

Add script to verify constants for static methods are present


<?php
/**
 * This file is part of the Laravel Auditing package.
 *
 * @author     Antério Vieira <anteriovieira@gmail.com>
 * @author     Quetzy Garcia  <quetzyg@altek.org>
 * @author     Raphael França <raphaelfrancabsb@gmail.com>
 * @copyright  2015-2018
 *
 * For the full copyright and license information,
 * please view the LICENSE.md file that was distributed
 * with this source code.
 */

namespace OwenIt\Auditing\Resolvers;

use Illuminate\Support\Facades\Request;

class UserAgentResolver implements \OwenIt\Auditing\Contracts\UserAgentResolver
{
    /**
     * {@inheritdoc}
     */
    public static function resolve()
    {
        return Request::userAgent();
    }
}

<?php
/**
 * This file is part of the Laravel Auditing package.
 *
 * @author     Antério Vieira <anteriovieira@gmail.com>
 * @author     Quetzy Garcia  <quetzyg@altek.org>
 * @author     Raphael França <raphaelfrancabsb@gmail.com>
 * @copyright  2015-2018
 *
 * For the full copyright and license information,
 * please view the LICENSE.md file that was distributed
 * with this source code.
 */

namespace OwenIt\Auditing\Resolvers;

use Illuminate\Support\Facades\Request;

class UserAgentResolver implements \OwenIt\Auditing\Contracts\UserAgentResolver
{
    /**
     * {@inheritdoc}
     */
    public static function resolve()
    {
        return Request::header('User-Agent');
    }
}

Replace userAgent method call - fixes incompatibilty with Illuminate 5.2


<?php

use Mimic\Functional as F;

/**
 * Unit Test for collectionNumberOperation Mimic library function.
 *
 * @since 0.1.0
 */
class CollectionNumberOperationFuncTest extends PHPUnit_Framework_TestCase {

	public function dataProvider() {
		return array(
			array(1, 0, 1, true),
			array(1.25, 0, 1.25, true),
			array('1', 0, '1', true),
			array('1.25', 0, '1.25', true),
			array('something', 1, 1, false),
		);
	}

	/**
	 * @dataProvider dataProvider
	 */
	public function testDataProviderResults($element, $current, $expected, $willBeCalled) {
		$called = false;
		$callback = function($element, $current) use (&$called) {
			$called = true;
		};
		$operation = F\collectionNumberOperation($callback);
		$actual = $operation($element, $current);
		$this->assertEquals($willBeCalled, $called);
		$this->assertEquals($expected, $actual);
	}
}

Use data provider to complete collection number operation test suite.


<?php

use Aedart\Scaffold\Contracts\Templates\Data\Type;
use Aedart\Scaffold\Handlers\PropertyHandler;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Logging\Log;
use Symfony\Component\Console\Style\StyleInterface;
use Mockery as m;

/**
 * Class PropertyHandlerTest
 *
 * @group handlers
 * @group propertyHandler
 *
 * @coversDefaultClass Aedart\Scaffold\Handlers\PropertyHandler
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class PropertyHandlerTest extends BaseUnitTest
{
    /**
     * Returns a new Property handler instance
     *
     * @param Repository $config
     * @param $key
     * @param StyleInterface $output
     * @param Log|null $log [optional]
     *
     * @return PropertyHandler
     */
    public function makePropertyHandler(Repository $config, $key, StyleInterface $output, Log $log = null)
    {

        $handler = new PropertyHandler($config, $key, $output);

        $handler->setOutputPath($this->outputPath());
        $handler->setFile($this->getFilesystem());

        if(!is_null($log)){
            $handler->setLog($log);
        }

        return $handler;
    }

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

    /**
     * @test
     *
     * @covers ::__construct
     */
    public function canObtainInstance()
    {
        $key = $this->faker->word;

        $config = $this->makeConfigRepositoryMock();

        $output = $this->makeStyleInterfaceMock();

        $handler = $this->makePropertyHandler($config, $key, $output);

        $this->assertNotNull($handler);
    }

    /**
     * @test
     *
     * NOTE: In this text we do not test individual
     * property types - we are just testing the general
     * work flow
     *
     * @covers ::processProperty
     *
     * @covers ::processElement
     * @covers ::obtainValueFor
     * @covers ::applyPostProcessOn
     * @covers ::saveValueFor
     */
    public function canProcessTemplateDataProperty()
    {
        $value = $this->faker->uuid;

        $key = $this->faker->word;

        $config = $this->makeConfigRepositoryMock();
        $config->shouldReceive('set')
            ->with($key, $value);

        $output = $this->makeStyleInterfaceMock();
        $output->shouldReceive('text')
            ->with(m::type('string'));

        $property = $this->makePropertyMock(Type::VALUE);
        $property->shouldReceive('getValue')
            ->andReturn($value);
        $property->shouldReceive('hasPostProcess')
            ->andReturn(false);
        $property->shouldReceive('hasDefaultPostProcess')
            ->andReturn(false);

        $handler = $this->makePropertyHandler($config, $key, $output);

        $handler->processProperty($property);
    }
}

Add property handler unit test

Add property handler unit test

Started working on testing the property handler. However, this is far
from done at this point!


<?php
/**
 * This file is part of phpDocumentor.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright 2017 Mike van Riel<mike@phpdoc.org>
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://phpdoc.org
 */

namespace phpDocumentor\Reflection\DocBlock\Tags\Formatter;

use phpDocumentor\Reflection\DocBlock\Tag;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter;

class AlignFormatter implements Formatter
{
    /** @var int The maximum tag name length. */
    protected $maxLen = 0;

    /**
     * Constructor.
     *
     * @param Tag[] $tags All tags that should later be aligned with the formatter.
     */
    public function __construct(array $tags)
    {
        foreach ($tags as $tag) {
            $this->maxLen = max($this->maxLen, strlen($tag->getName()));
        }
    }

    /**
     * Formats the given tag to return a simple plain text version.
     *
     * @param Tag $tag
     *
     * @return string
     */
    public function format(Tag $tag)
    {
        return '@' . $tag->getName() . str_repeat(' ', $this->maxLen - strlen($tag->getName()) + 1) . (string)$tag;
    }
}

Add a tag formatter that aligns all tag values.


<?php
/**
 * Created by PhpStorm.
 * User: evgen
 * Date: 21.07.2019
 * Time: 10:26
 */

namespace OpsWay\ZohoBooks\Api;

class ItemAdjustments
{

}

Add inventory adjustment api + update gitignore


<?php
/**
 * Simple test for syntax-checking Twig-templates.
 *
 * @author Tim van Dijen <tvdijen@gmail.com>
 * @package SimpleSAMLphp
 */

namespace SimpleSAML\Test\Web;

use PHPUnit\Framework\TestCase;

use \SimpleSAML\Configuration;
use \SimpleSAML\XHTML\Template;
use \SimpleSAML\Module;

class TemplateTest extends TestCase
{
    public function testSyntax()
    {
        $config = Configuration::loadFromArray([
            'language.i18n.backend' => 'gettext/gettext',
            'module.enable' => array_fill_keys(Module::getModules(), true),
        ]);
        Configuration::setPreLoadedConfig($config);

        $basedir = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'templates';

        // Base templates
        $files = array_diff(scandir($basedir), array('.', '..'));
        foreach ($files as $file) {
            if (preg_match('/.twig$/', $file)) {
                $t = new Template($config, $file);
                ob_start();
                try {
                    $t->show();
                    $this->addToAssertionCount(1);
                } catch (\Twig_Error_Syntax $e) {
                    $this->fail($e->getMessage().' in '.$e->getFile().':'.$e->getLine());
                }
                ob_clean();
            }
        }

        // Module templates
        foreach (Module::getModules() as $module) {
            $basedir = Module::getModuleDir($module).DIRECTORY_SEPARATOR.'templates';
            if (file_exists($basedir)) {
                $files = array_diff(scandir($basedir), array('.', '..'));
                foreach ($files as $file) {
                    if (preg_match('/.twig$/', $file)) {
                        $t = new Template($config, $module.':'.$file);
                        ob_start();
                        try {
                            $t->show();
                            $this->addToAssertionCount(1);
                        } catch (\Twig_Error_Syntax $e) {
                            $this->fail($e->getMessage().' in '.$e->getFile().':'.$e->getLine());
                        }
                        ob_clean();
                    }
                }
            }
        }
    }
}

Add Test to perform syntax-checks on Twig-templates


<?php
use FluxBB\Markdown\Renderer\XhtmlRenderer;

/**
 * @author Franz Liedke <franz@fluxbb.org>
 */
class CommonMarkTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @dataProvider commonMarkSpecRegressions
     */
    public function testSpecRegressions($source, $expected)
    {
        $parser = new \FluxBB\Markdown\Parser(new XhtmlRenderer());

        $actual = $parser->render($source);

        $this->assertEquals($expected, $actual);
    }

    public function commonMarkSpecRegressions()
    {
        return [
            [ # Example 24
                "####### foo",
                "<p>####### foo</p>",
            ],
        ];
    }

}

Add a test class for CommonMark spec regressions.

Start with one example.


<?php
require_once 'SharedConfigurations.php';

// Predis ships with a KeyPrefixPreprocessor class that is used to transparently
// prefix each key before sending commands to Redis, even for complex commands
// such as SORT, ZUNIONSTORE and ZINTERSTORE. Key prefixes are useful to create
// user-level namespaces for you keyspace, thus eliminating the need for separate
// logical databases.

use Predis\Commands\Preprocessors\KeyPrefixPreprocessor;

$client = new Predis\Client();
$client->getProfile()->setPreprocessor(new KeyPrefixPreprocessor('nrk:'));

$client->mset(array('foo' => 'bar', 'lol' => 'wut'));
var_dump($client->mget('foo', 'lol'));
/*
array(2) {
  [0]=> string(3) "bar"
  [1]=> string(3) "wut"
}
*/

var_dump($client->keys('*'));
/*
array(2) {
  [0]=> string(7) "nrk:foo"
  [1]=> string(7) "nrk:lol"
}
*/
?>

Add an example to show how to leverage key prefixes.


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

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

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

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

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

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

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

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

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

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

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


<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="permissions", uniqueConstraints={@ORM\UniqueConstraint(name="db_name_uniq", columns={"name"})})
 */
class Permissions
{
    /**
     * @var \AppBundle\Entity\FennecUser
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\FennecUser")
     * @ORM\JoinColumn(name="webuser_id", referencedColumnName="id", nullable=false)
     */
    private $webuser;

    /**
     * @ORM\Column(type="string")
     */
    private $permission;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\WebuserData")
     * @ORM\JoinColumn(name="webuser_data_id", referencedColumnName="id", nullable=false)
     */
    private $webuserDataId;

    /**
     * @return FennecUser
     */
    public function getWebuser()
    {
        return $this->webuser;
    }

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

    /**
     * @param mixed $permission
     */
    public function setPermission($permission)
    {
        $this->permission = $permission;
    }

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

    /**
     * @param mixed $webuserDataId
     */
    public function setWebuserDataId($webuserDataId)
    {
        $this->webuserDataId = $webuserDataId;
    }

}

Define entity for user permissions

Define entity for user permissions


<?php

namespace RKD\BanklinkTests;

/**
 * Test suite for Liizi banklink.
 *
 * @author  Rene Korss <rene.korss@gmail.com>
 */
class LiiziTest extends SEBTest
{
    protected $bankClass = "RKD\Banklink\Liizi";

    protected $requestUrl = 'https://klient.liisi.ee/api/ipizza/';
    protected $testRequestUrl = 'https://prelive.liisi.ee:8953/api/ipizza/';
}

Add unit tests for Liizi Payment Link

Add unit tests for Liizi Payment Link


<?php
namespace Helper;

use Behat\Gherkin\Node\TableNode;
use Codeception\Util\Fixtures;

class Acceptance extends \Codeception\Module
{
    /**
     * @When /I have (parameters)?/
     */
     public function iHaveParams(TableNode $table)
     {
         foreach ($table->getRows() as $idx => $row) {
           if ($idx == 0) continue;
           Fixtures::add($row[0], $row[1]);
         }
     }
}

Fix issue with TableNode when using Helper


<?php

namespace Ivory\GoogleMapBundle\Tests\Templating\Helper;

use Ivory\GoogleMapBundle\Templating\Helper\Overlays\GroundOverlayHelper;
use Ivory\GoogleMapBundle\Templating\Helper\Base\BoundHelper;
use Ivory\GoogleMapBundle\Templating\Helper\Base\CoordinateHelper;
use Ivory\GoogleMapBundle\Model\Map;
use Ivory\GoogleMapBundle\Model\Overlays\GroundOverlay;
use Ivory\GoogleMapBundle\Model\Base\Bound;
use Ivory\GoogleMapBundle\Model\Base\Coordinate;

/**
 * Ground overlay helper test
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class GroundOverlayHelperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Ivory\GoogleMapBundle\Templating\Helper\Overlays\GroundOverlayHelper
     */
    protected static $groundOverlayHelper = null;

    /**
     * @override
     */
    protected function setUp()
    {
        self::$groundOverlayHelper = new GroundOverlayHelper(new BoundHelper(new CoordinateHelper()));
    }

    /**
     * Checks the render method
     */
    public function testRender()
    {
        $mapTest = new Map();

        $boundTest = new Bound();
        $boundTest->setSouthWest(new Coordinate(-1.1, -2.1, true));
        $boundTest->setNorthEast(new Coordinate(1.1, 2.1, true));

        $groundOverlayTest = new GroundOverlay();
        $groundOverlayTest->setUrl('url');
        $groundOverlayTest->setBound($boundTest);

        $this->assertEquals(self::$groundOverlayHelper->render($groundOverlayTest, $mapTest),
            'var '.$groundOverlayTest->getBound()->getJavascriptVariable().' = new google.maps.LatLngBounds(new google.maps.LatLng(-1.1, -2.1, true), new google.maps.LatLng(1.1, 2.1, true));'.PHP_EOL.
            'var '.$groundOverlayTest->getJavascriptVariable().' = new google.maps.GroundOverlay("'.$groundOverlayTest->getUrl().'", '.$groundOverlayTest->getBound()->getJavascriptVariable().', {"map":'.$mapTest->getJavascriptVariable().'});'.PHP_EOL
        );

        $groundOverlayTest->setOptions(array(
            'option1' => 'value1',
            'option2' => 'value2'
        ));

        $this->assertEquals(self::$groundOverlayHelper->render($groundOverlayTest, $mapTest),
            'var '.$groundOverlayTest->getBound()->getJavascriptVariable().' = new google.maps.LatLngBounds(new google.maps.LatLng(-1.1, -2.1, true), new google.maps.LatLng(1.1, 2.1, true));'.PHP_EOL.
            'var '.$groundOverlayTest->getJavascriptVariable().' = new google.maps.GroundOverlay("'.$groundOverlayTest->getUrl().'", '.$groundOverlayTest->getBound()->getJavascriptVariable().', {"map":'.$mapTest->getJavascriptVariable().',"option1":"value1","option2":"value2"});'.PHP_EOL
        );
    }
}

Add ground overlay helper tests

Add ground overlay helper tests


<?php
/**
 * Created by PhpStorm.
 * User: s216121
 * Date: 12.10.16
 * Time: 09:34
 */

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ProjectController extends Controller
{
    /**
     * @param $request Request
     * @param $dbversion string
     * @return Response
     * @Route("/{dbversion}/project/overview", name="project_overview")
     */
    public function overviewAction(Request $request, $dbversion){
        return $this->render(
            'project/overview.html.twig',
            [
                'dbversion' => $dbversion,
                'type' => 'project',
                'title' => 'Projects'
            ]
        );
    }
}

Add controller for project routes

Add controller for project routes


<?php
namespace Composer\Installers;

class AuraInstaller extends BaseInstaller
{
    protected $locations = array(
        'package'    => 'package/{$name}/',
        'include'     => 'include/{$name}/',
    );
}

Implement Aura package types: package and include


<?php

namespace Risan\OAuth1;

use Risan\OAuth1\Request\RequestConfigFactory;
use Risan\OAuth1\Credentials\CredentialsFactory;

class OAuth1Factory
{
    /**
     * Create a new OAuth instance.
     *
     * @param  array  $config
     * @return \Risan\OAuth1\OAuth1
     */
    public static function create(array $config)
    {
        $requestConfig = RequestConfigFactory::create($config);

        return new OAuth1($requestConfig, new HttpClient, new CredentialsFactory);
    }
}

Add new factory class to create OAuth1.

:sparkles: Add new factory class to create OAuth1.


<?php

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

namespace Staq;

abstract class Application {

	/*************************************************************************
	  STATIC SHORTHAND METHODS
	 *************************************************************************/
	public static function create( $path = 'Staq/core/ground', $root_uri = '/', $platform = 'prod' ) {
		return ( new \Staq\Server )->create_application( $path, $root_uri, $platform );
	}
	public static function current_application( ) {
		return \Staq\Server::$application;
	}
	public static function get_extensions( ) {
		return self::current_application( )->get_extensions( );
	}
	public static function get_platform( ) {
		return self::current_application( )->get_platform( );
	}
}

Add new shorthand static methods to access to the current application


<?php

include_once( 'errors.inc.php' );
include_once( 'db.pg.class.php' );
include_once( 'session.class.php' );
include_once( 'tools.inc.php' );
include_once( 'json.inc.php' );

$db =& getDB();
$ses =& getSession();

$pid = isset( $_REQUEST[ 'pid' ] ) ? intval( $_REQUEST[ 'pid' ] ) : 0;
$uid = $ses->isSessionValid() ? $ses->getId() : 0;

$tnid = isset( $_REQUEST[ 'tnid' ] ) ? intval( $_REQUEST[ 'tnid' ] ) : -1;

if ( $pid )
{
	if ( $uid )
	{
        $query = "SELECT tn.id AS id, tn.location AS location, greatest(tn.creation_time, tn.edition_time) AS most_recent ".
            "FROM treenode_class_instance tcn, relation r, treenode_class_instance tcn2, treenode tn ".
            "WHERE ".
            "  tcn.treenode_id = $tnid AND ".
            "  r.relation_name = 'element_of' AND ".
            "  tcn.relation_id = r.id AND ".
            "  tcn.class_instance_id = tcn2.class_instance_id AND ".
            "  tn.id = tcn2.treenode_id ".
            "ORDER BY most_recent DESC ".
            "LIMIT 1";

		$result = $db->getResult($query);
		if ($result) {
            echo makeJSON( $result[0] );
		} else
			echo makeJSON( array( '"error"' => "No skeleton and neuron found for treenode $tnid" ) );
	}
	else
		echo makeJSON( array( 'error' => 'You are not logged in currently.  Please log in to get the last modified treenode' ) );
}
else
    echo makeJSON( array( 'error' => 'Project closed. Can not apply operation.' ) );

?>

Add backend code to return the last edited node the same skeleton as a treenode


<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2020, Joas Schilling <coding@schilljs.com>
 *
 * @author Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\Talk\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version8000Date20200402124456 extends SimpleMigrationStep {

	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		$table = $schema->getTable('talk_participants');
		if (!$table->hasIndex('tp_uid')) {
			$table->addIndex(['user_id'], 'tp_uid');
		}

		return $schema;
	}
}

Add a user index on the participants table

Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com>


<?php

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

class AddVisibleToContests extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('contests', function (Blueprint $table) {
            //fix ends_at not being nullable
            $table->timestamp('ends_at')->nullable()->change();

            $table->renameColumn('description', 'description_voting');
            $table->renameColumn('ends_at', 'voting_ends_at');

            $table->timestamp('entry_starts_at')->nullable()->after('show_votes');
            $table->timestamp('entry_ends_at')->nullable()->after('entry_starts_at');
            $table->timestamp('voting_starts_at')->nullable()->after('entry_ends_at');

            $table->text('description_enter')->after('name');
        });
    }

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

            $table->dropColumn('voting_starts_at');
            $table->dropColumn('entry_starts_at');
            $table->dropColumn('entry_ends_at');

            $table->renameColumn('description_voting', 'description');
            $table->renameColumn('voting_ends_at', 'ends_at');

            $table->timestamp('ends_at')->change();
        });
    }
}

Add migration for contest submission changes.


<?php

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

class InsertStatusColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if(Schema::hasTable('assessments') && !Schema::hasColumn('assessments', 'record_status')) {
            Schema::table('assessments', function(Blueprint $table) {
                $table->smallInteger('record_status')->default(1);
            });
        }

        if(Schema::hasTable('assessments_history') && !Schema::hasColumn('assessments_history', 'record_status')) {
            Schema::table('assessments_history', function(Blueprint $table) {
                $table->smallInteger('record_status');
            });
        }

        if(Schema::hasTable('characters') && !Schema::hasColumn('characters', 'record_status')) {
            Schema::table('characters', function(Blueprint $table) {
                $table->smallInteger('record_status')->default(1);
            });
        }

        if(Schema::hasTable('developers') && !Schema::hasColumn('developers', 'record_status')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->smallInteger('record_status')->default(1);
            });
        }

        if(Schema::hasTable('vn') && !Schema::hasColumn('vn', 'record_status')) {
            Schema::table('vn', function(Blueprint $table) {
                $table->smallInteger('record_status')->default(1);
            });
        }
    }

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

        if(Schema::hasColumn('developers', 'record_status')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->dropColumn(['record_status']);
            });
        }

         if(Schema::hasColumn('characters', 'record_status')) {
            Schema::table('characters', function(Blueprint $table) {
                $table->dropColumn(['record_status']);
            });
        }

        if(Schema::hasColumn('assessments_history', 'record_status')) {
            Schema::table('assessments_history', function(Blueprint $table) {
                $table->dropColumn(['record_status']);
            });
        }

        if(Schema::hasColumn('assessments', 'record_status')) {
            Schema::table('assessments', function(Blueprint $table) {
                $table->dropColumn(['record_status']);
            });
        }
    }
}

Prepare migration inserting record_status columns

Affected tables: assessments, assessmemnts_history, characters,
developers


<?php

use Phinx\Migration\AbstractMigration;

class CreatePreviousPasswordTable extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('previous_password');
        $table->addColumn('user_id', 'integer', ['null' => false])
              ->addColumn('password', 'string', ['limit' => 255, 'null' => false])
              ->addColumn('created', 'datetime')
              ->addForeignKey('user_id', 'user', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
              ->create();
    }
}

Create migration for previous_password table.


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

use App\Developer;

class UpdateDeveloperName extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $developers = DB::table('developers')->get();
        foreach($developers as $dev) {
            var_dump($dev);
            if(empty($dev->original) && !empty($dev->romaji)) {
                // $dev->original = $dev->romaji;
                // $dev->romaji = null;
                // echo "WOW";
                // $dev->save();

                $developer = Developer::find($dev->id);
                $developer->original = $developer->romaji;
                $developer->romaji = null;
                $developer->save();
                echo "OK ";
            }
        }

        Model::reguard();
    }
}

Prepare seeder to update developer names