<?php

namespace Mapeadores;

use Entidades\DadosAntigos;
use Entidades\Tamanhos;
use Entidades\Cores;

/**
 * @author Tiago Oliveira de Farias
 */
class CoresAntigas extends DadosAntigos{

	public function __construct(\PDO $pdo)
	{
		parent::__construct($pdo);
	}

	public function buscar()
	{
		$stmt = $this->pdo->prepare('select distinct codigo, cor from ' .self::TABELA. ' group by codigo, cor;');
		$stmt->execute();

		$cores = Array();
		while($data = $stmt->fetch()) {

			$cores[] = new Cores( $data->cor );
		}

		return $cores;
	}
}

Add - classe para buscar "cores antigas" da tabela 'dados_antigos'.


<?php
declare(strict_types=1);

namespace Onion\Framework\Hydrator;

trait PropertyHydrator
{
    /**
     * @inheritdoc
     */
    public function hydrate(array $data)
    {
        $target = clone $this;
        foreach ($data as $name => $value) {
            $property = str_replace('_', '', lcfirst(ucwords($name, '_')));
            if (property_exists($target, $property)) {
                $target->$property = $value;
            }
        }

        return $target;
    }

    /**
     * @inheritdoc
     */
    public function extract(array $keys = []): array
    {
        $data = [];
        if ($keys === []) {
            $reflection = new \ReflectionObject($this);
            foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $name => $value) {
                $data[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name))] = $value;
            }

            return $data;
        }

        foreach ($keys as $name => $value) {
            $data[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name))] = $value;
        }

        return $data;
    }
}

Add hydrator that (de)hydrates the object using public properties


<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

$module_name = 'Utils/QueryBuilder';
if (ModuleManager::is_installed($module_name) < 0) {
    ModuleManager::install($module_name);
}

[UPDATE] Install Query Builder module as dependency of RB


<?php
namespace CLIFramework\Ansi;

class Colors
{
    protected $foregroundColors = array(
        'black'        => '0,30',
        'dark_gray'    => '1,30',
        'blue'         => '0,34',
        'light_blue'   => '1,34',
        'green'        => '0,32',
        'light_green'  => '1,32',
        'cyan'         => '0,36',
        'light_cyan'   => '1,36',
        'red'          => '0,31',
        'light_red'    => '1,31',
        'purple'       => '0,35',
        'light_purple' => '1,35',
        'brown'        => '0,33',
        'yellow'       => '1,33',
        'light_gray'   => '0,37',
        'white'        => '1,37',
    );

    protected $backgroundColors = array(
        'black'      => '40',
        'red'        => '41',
        'green'      => '42',
        'yellow'     => '43',
        'blue'       => '44',
        'magenta'    => '45',
        'cyan'       => '46',
        'light_gray' => '47',
    );

    // Returns colored string
    public function wrap($string, $fg = null, $bg = null) {
        $coloredString = "";

        // Check if given foreground color found
        if ($fg && isset($this->foregroundColors[$fg])) {
            $coloredString .= "\033[" . $this->foregroundColors[$fg] . "m";
        }
        // Check if given background color found
        if ($bg && isset($this->backgroundColors[$bg])) {
            $coloredString .= "\033[" . $this->backgroundColors[$bg] . "m";
        }

        // Add string and end coloring
        $coloredString .=  $string;

        if ($fg || $bg) {
            $coloredString .= "\033[0m";
        }
        return $coloredString;
    }

    // Returns all foreground color names
    public function getForegroundColors() {
        return array_keys($this->foregroundColors);
    }

    // Returns all background color names
    public function getBackgroundColors() {
        return array_keys($this->backgroundColors);
    }

}

Add Ansi Color definition class

Add Ansi Color definition class


<?php

/**
 * White-space agnostic custom expectation class.
 *
 * @package		Testee
 * @author		Stephen Lewis <stephen@experienceinternet.co.uk>
 * @copyright	Experience Internet
 */

require_once PATH_THIRD .'testee/simpletest/expectation.php';

class EqualWithoutWhitespaceExpectation extends EqualExpectation {

	private $_subject;

	/* --------------------------------------------------------------
	 * PUBLIC METHODS
	 * ------------------------------------------------------------ */

	/**
	 * Constructor.
	 *
	 * @access	public
	 * @param 	string		$subject		The subject.
	 * @param	string		$message		Custom failure message.
	 * @return	void
	 */
	public function __construct($subject, $message = '%s')
	{
		$this->_subject = $subject;
		parent::__construct($subject, $message);
	}

	/**
	 * Tests the expectation.
	 *
	 * @access	public
	 * @param	string		$compare		The comparison string.
	 * @return	bool
	 */
	public function test($compare = '')
	{
		$search = '#\s#';
		$replace = '';

        return (preg_replace($search, $replace, $this->_subject)
            == preg_replace($search, $replace, $compare));
	}

	/**
	 * Returns a human-readable test message.
	 *
	 * @access	public
	 * @param	string	$compare	The comparison string.
	 * @return	string
	 */
	public function testMessage($compare = '')
	{
		return $this->test($compare)
			? 'Whitespace-agnostic equal expectation [' .$this->dumper->describeValue($this->_subject) .']'
			: 'Whitespace-agnostic equal expectation fails ' .$this->dumper->describeDifference($this->_subject, $compare);
	}

}

/* End of file		: testee_equal_without_whitespace_expectation.php */
/* File location	: system/third_party/testee/classes/testee_equal_without_whitespace_expectation.php */

Add new 'Equal without whitespace' custom test.


<?php
/*
 * Copyright (c) 2011 Eike Foken <kontakt@eikefoken.de>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Extends CI's config class.
 *
 * @author Eike Foken <kontakt@eikefoken.de>
 */
class MY_Config extends CI_Config {

	/**
	 * Calls the parent constructor.
	 */
	public function __construct() {
		parent::__construct();
		log_message('debug', "Config Class Extension Initialized");
	}

	/**
	 * Handles relative URLs.
	 *
	 * @see CI_Config::site_url()
	 */
	public function site_url($uri = '', $relative = true) {
		$url = parent::site_url($uri);
		return $relative ? parse_url($url, PHP_URL_PATH) : $url;
	}
}

/* End of file MY_Config.php */
/* Location: ./application/core/MY_Config.php */

Extend CI's config class to create relative URLs


<?php
class AddExceptionTypeToIncidents extends CakeMigration {

/**
 * Migration description
 *
 * @var string
 * @access public
 */
	public $description = '';

/**
 * Actions to be performed
 *
 * @var array $migration
 * @access public
 */
	public $migration = array(
		'up' => array(
			'create_field' => array(
			    'incidents' => array(
			        'exception_type' => array(
			            'type' => 'boolean'
			        ),
			    ),
			),
		),
		'down' => array(
			'drop_field' => array(
			    'incidents' => array('exception_type'),
			),
		),
	);

/**
 * Before migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function before($direction) {
		return true;
	}

/**
 * After migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function after($direction) {
		return true;
	}
}

Add 'exception_type' field to Incidents.

Signed-off-by: Dhananjay Nakrani <9e965ab80219a00627f2dc7fe46b57bdbd34c853@gmail.com>


<?hh

class Settings {
  public static function get(string $key): mixed {
    $query = DB::queryFirstRow("SELECT * FROM settings WHERE key=%s", $key);
    return $query['value'];
  }

  public static function set(string $key, mixed $value): void {
    DB::insertUpdate('settings', array(
      'key' => $key,
      'value' => $value
    ));
  }
}

Create settings class for global settings


<?php

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

class StoreSetupLoadoutTable2 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Add the owner_id as foreign key
        Schema::connection('store')->table('loadouts',function (Blueprint $table) {
            $table->foreign('owner_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //Remove the owner id as foreign key
        Schema::connection('store')->table('loadouts',function (Blueprint $table) {
            $table->dropForeign('owner_id');
        });
    }
}

Add the owner_id as foreign key in store_loadouts


<?php

namespace Mila\DAO;

final class eventDAO implements DAOInterface
{
    /*
     * @var \Doctrine\DBAL\Connection
     */
    private $dbCon;

    /*
     * @param \Doctrine\DBAL\Connection $dbCon
     */
    public function __construct($dbCon)
    {
        $this->dbCon = $dbCon;
    }

    public function fetchAll()
    {
        return $this->dbCon->fetchAll('SELECT * FROM events');
    }

    public function fetchById($id)
    {
        return $this->dbCon->fetchAssoc("SELECT * FROM events WHERE id={$id}");
    }
}

Add DAO fetching all available events and single event by id


<?php
class Dummy_Model_Sp_TestCase_SignedPostRequest
    implements Dummy_Model_Sp_TestCase_TestCaseInterface
{
    public function decorateRequest(SAML2_Request $request)
    {
        $sspConfig = Dummy_Model_DiContainer::getInstance()->getSimpleSamlPhpConfig();
        sspmod_saml_Message::addSign($sspConfig, null, $request);
        return $request;
    }

    /**
     * @param string &$bindingType
     */
    public function setBindingType($bindingType)
    {
        return Dummy_Model_Binding_BindingFactory::TYPE_POST;
    }
}

<?php
class Dummy_Model_Sp_TestCase_SignedPostRequest
    implements Dummy_Model_Sp_TestCase_TestCaseInterface
{
    public function decorateRequest(SAML2_Request $request)
    {
        $sspConfig = Dummy_Model_DiContainer::getInstance()->getSimpleSamlPhpConfig();
        sspmod_saml_Message::addSign(
            $sspConfig,
            SimpleSAML_Configuration::loadFromArray(array()),
            $request
        );
        return $request;
    }

    /**
     * @param string &$bindingType
     */
    public function setBindingType($bindingType)
    {
        return Dummy_Model_Binding_BindingFactory::TYPE_POST;
    }
}

Fix Functional Testing after upgrade of SSP


<?php

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

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

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

Add failed queue job table

Add failed queue job table


<?php

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

class CreateLasttweetTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('lasttweet', function(Blueprint $table)
		{
			$table->increments('id');
			$table->text('since_id');
			$table->timestamps();
		});
	}

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

}

Add migration for lasttweet table

Add migration for lasttweet table


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;

class CandidateStep5Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
			     ->add('town_activities', 'choice', array(
			     		'multiple' => TRUE,
			     		'expanded' => TRUE,
			     		'choices' => array(
			     				'1' => 'He tenido experiencia en la mejora del funcionamiento organizativo de entidades',
			     				'2' => 'He participado en la elaboración de planes de protección civil o seguridad ciudadana',
			     				'3' => 'He contribuido a la lucha contra la pobreza o la exclusión social',
			     				'4' => 'He gestionado actividades de atención sanitaria',
			     				'5' => 'He gestionado actividades educativas o culturales',
			     				'6' => 'He gestionado planes de infraestructura, vivienda o urbanismo',
			     				'7' => 'He gestionado actividades de fomento de la sostenibilidad o protección medioambiental',
			     				'8' => 'He gestionado actividades de fomento del empleo',
			     				'9' => 'He gestionado actividades de fomento de la transparencia, la participación ciudadana o la igualdad de género',
			     				'10' => 'He gestionado actividades colectivas en el campo industrial o agrícola',
			     				'11' => 'He gestionado actividades colectivas en el campo de las tecnologías de la información o la comunicación',
			     				'12' => 'He gestionado actividades colectivas de investigación o desarrollo',
			     				'13' => 'He gestionado actividades colectivas en el campo del cooperativismo',
			     				'14' => 'He gestionado eficazmente presupuestos superiores al millón de euros',
			     				'15' => 'He tenido experiencia de trabajo internacional',
			     				'16' => 'He realizado funciones de representación o portavocía de colectivos',
			     		),
			     		'data_class' => NULL,
			     		'constraints' => array(
			     				new Assert\Count(array(
						            'max'        => 3,
						            'minMessage' => 'You must specify at least one email',
						            'maxMessage' => 'Sólo puedes seleccionar hasta {{ limit }} opciones como máximo',
						        ))
			     		)
			     ))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add Candidate Step 5 form type

Add Candidate Step 5 form type


<?php

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

class AllowPostsUrlToBeNull extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('url')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('url')->nullable(false)->change();
        });
    }
}

Add migration to allow the post url to be null


<?php

/**
 * Generates site-wide page chrome.
 * @see https://drupal.org/node/1728148
 **/

?>

<?php if (!empty($tabs['#primary'])): ?><?php print render($tabs); ?><?php endif; ?>
<?php print $messages; ?>

  <?php print $variables['navigation']; ?>

Edit Profile

      <?php print render($page['content']); ?>

  <?php print $variables['footer']; ?>

Add page template for user edit page.

Add page template for user edit page.


<?php

declare(strict_types=1);

namespace Phpcq\Runner\Test\Plugin;

use Phpcq\PluginApi\Version10\Configuration\Builder\StringListOptionBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\PluginConfigurationBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\PluginConfigurationInterface;
use Phpcq\RepositoryDefinition\Plugin\PluginHash;
use Phpcq\Runner\Plugin\ChainPlugin;
use PHPUnit\Framework\TestCase;

/**
 * @covers \Phpcq\Runner\Plugin\ChainPlugin
 */
final class ChainPluginTest extends TestCase
{
    public function testName(): void
    {
        $instance = new ChainPlugin();
        $this->assertEquals('chain', $instance->getName());
    }

    public function testInstalledPlugin(): void
    {
        $installedPlugin = ChainPlugin::createInstalledPlugin();

        $this->assertEquals('chain', $installedPlugin->getName());
        $this->assertEquals([], iterator_to_array($installedPlugin->iterateTools()));

        $pluginVersion = $installedPlugin->getPluginVersion();
        $expectedHash  = PluginHash::createForFile(__DIR__ . '/../../src/Resources/plugins/chain-plugin.php');
        $this->assertEquals('chain', $pluginVersion->getName());
        $this->assertEquals('1.0.0', $pluginVersion->getVersion());
        $this->assertEquals('1.0.0', $pluginVersion->getApiVersion());
        $this->assertTrue($expectedHash->equals($pluginVersion->getHash()));
        $this->assertNull($pluginVersion->getSignaturePath());
        $this->assertFileEquals(
            __DIR__ . '/../../src/Resources/plugins/chain-plugin.php',
            $pluginVersion->getFilePath()
        );
    }

    public function testConfigurationDescription(): void
    {
        $instance             = new ChainPlugin();
        $configOptionsBuilder = $this->getMockForAbstractClass(PluginConfigurationBuilderInterface::class);
        $tasksOption          = $this->getMockForAbstractClass(StringListOptionBuilderInterface::class);
        $configOptionsBuilder->expects($this->once())
            ->method('describeStringListOption')
            ->with('tasks', 'The list of tasks which are executed when running the task')
            ->willReturn($tasksOption);

        $tasksOption
            ->expects($this->once())
            ->method('isRequired');

        $instance->describeConfiguration($configOptionsBuilder);
    }

    public function testTaskNames(): void
    {
        $instance = new ChainPlugin();
        $config = $this->getMockForAbstractClass(PluginConfigurationInterface::class);
        $config
            ->expects($this->once())
            ->method('getStringList')
            ->willReturn(['foo', 'bar']);

        $this->assertEquals(['foo', 'bar'], $instance->getTaskNames($config));
    }
}

Add unit test for chain plugin

Add unit test for chain plugin


<?php

final class PhabricatorNotificationPanelController
  extends PhabricatorNotificationController {

  public function processRequest() {

    $request = $this->getRequest();
    $user = $request->getUser();

    $query = new PhabricatorNotificationQuery();
    $query->setViewer($user);
    $query->setUserPHID($user->getPHID());
    $query->setLimit(15);

    $stories = $query->execute();

    if ($stories) {
      $builder = new PhabricatorNotificationBuilder($stories);
      $notifications_view = $builder->buildView();
      $content = $notifications_view->render();
    } else {
      $content = hsprintf(
        '
%s
',
        pht('You have no notifications.'));
    }

    $content = hsprintf(
      '
%s
'.
      '%s'.
      '
%s
',
      pht('Notifications'),
      $content,
      phutil_tag(
        'a',
        array(
          'href' => '/notification/',
        ),
        'View All Notifications'));

    $unread_count = id(new PhabricatorFeedStoryNotification())
      ->countUnread($user);

    $json = array(
      'content' => $content,
      'number'  => $unread_count,
    );

    return id(new AphrontAjaxResponse())->setContent($json);
  }
}

<?php

final class PhabricatorNotificationPanelController
  extends PhabricatorNotificationController {

  public function processRequest() {

    $request = $this->getRequest();
    $user = $request->getUser();

    $query = new PhabricatorNotificationQuery();
    $query->setViewer($user);
    $query->setUserPHID($user->getPHID());
    $query->setLimit(15);

    $stories = $query->execute();

    if ($stories) {
      $builder = new PhabricatorNotificationBuilder($stories);
      $notifications_view = $builder->buildView();
      $content = $notifications_view->render();
    } else {
      $content = hsprintf(
        '
%s
',
        pht('You have no notifications.'));
    }

    $content = hsprintf(
      '
%s
'.
      '%s'.
      '
%s
',
      pht('Notifications'),
      $content,
      phutil_tag(
        'a',
        array(
          'href' => '/notification/',
        ),
        'View All Notifications'));

    $unread_count = id(new PhabricatorFeedStoryNotification())
      ->countUnread($user);

    $json = array(
      'content' => $content,
      'number'  => (int)$unread_count,
    );

    return id(new AphrontAjaxResponse())->setContent($json);
  }
}

Fix weird "0" notification numbers

Fix weird "0" notification numbers

Summary: The JsShrink change swapped an "== 0" for "=== 0" in JS, but we're currently sending a string down. Fixes T3230.

Test Plan: I'm not 100% sure this actually fixes it but probably? Let me know if you still see it.

Reviewers: chad, btrahan

Reviewed By: chad

CC: aran

Maniphest Tasks: T3230

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


<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

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

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
//        parent::buildForm($builder, $options);

        $builder
            ->add('plainPassword', 'password')
            ->add('email', 'email')
            ->add('title')
            ->add('firstNames')
            ->add('lastName')
            ->add('dob', 'date', array(
                'widget' => 'single_text',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_register'),
        ));
    }

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

<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

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

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
//        parent::buildForm($builder, $options);

        $builder
            ->add('plainPassword', 'password', array(
                'description' => 'Plain text password. Encoded before new user is persisted.',
            ))
            ->add('email', 'email', array(
                'description' => 'Email address. Must be unique.',
            ))
            ->add('title', 'text', array(
                'description' => 'Salutation.',
            ))
            ->add('firstNames', 'text', array(
                'description' => 'First name(s).',
            ))
            ->add('lastName', 'text', array(
                'description' => 'Last name.',
            ))
            ->add('dob', 'date', array(
                'widget' => 'single_text',
                'description' => 'Date of birth.',
                'required' => false,
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_register'),
        ));
    }

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

Add API documentation (JANUS-19) * Add form field descriptions.


<?php

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

class AddPinnedFieldToComments extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('comments', function (Blueprint $table) {
            $table->boolean('pinned')->default(false);
        });
    }

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

Add a migration with the pinned field to comments


// SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php

$double_quotes = "SELECT * FROM tbl";
//                  ^ source.sql keyword
//                       ^ source.sql keyword
//                          ^ source.sql keyword

$single_quotes = 'SELECT * FROM tbl';
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$double_quotes = "UPDATE t1 SET col1 = col1 + 1, col2 = col1;";
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$single_quotes = 'UPDATE t1 SET col1 = col1 + 1, col2 = col1;';
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$double_quotes = "INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);";
//                  ^ source.sql keyword
//                          ^ source.sql keyword
//                                                  ^ source.sql keyword

$single_quotes = 'INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);';
//                  ^ source.sql keyword
//                          ^ source.sql keyword
//                                                      ^ source.sql keyword

Add sql string interpolation test

Add sql string interpolation test


<?php

namespace SpreadsheetsReplacement\Action\Regexp;

use SpreadsheetsReplacement\Action\Action;

/**
 * Action to modify column's value with preg_replace.
 *
 * @author florian
 */
class Regexp extends Action implements IRegexp {

    private $pattern;

    private $replacement;

    /**
     * {@inheritDoc}
     */
    public function getPattern() {
        return $this->pattern;
    }

    /**
     * Modify the pattern.
     * @param string $pattern the pattern.
     */
    public function setPattern($pattern) {
        $this->pattern = $pattern;
    }

    /**
     * {@inheritDoc}
     */
    public function getReplacement() {
        return $this->replacement;
    }

    /**
     * Modify the replacement.
     * @param string $replacement the replacement
     */
    public function setReplacement($replacement) {
        $this->replacement = $replacement;
    }

    /**
     * {@inheritDoc}
     */
    public function replace($value) {
        return preg_replace($this->getPattern(), $this->getReplacement(), $value);
    }

}

Add an action for replacement with regexp


<?
	# $Id: user_tasks.php,v 1.1.2.1 2003-01-10 16:03:25 dan Exp $
	#
	# Copyright (c) 1998-2001 DVL Software Limited
	#

// base class for user tasks
class UserTasks {

	var $user_id;
	var $tasks;

	var $dbh;

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

	function FetchByID($user_id) {
#		echo "\$user_id = '$user_id'
\n";
		if (IsSet($user_id)) {
			$this->id = $user_id;
		}
		$sql = "select id, name from user_tasks, tasks where user_id = $this->id and user_tasks.task_id = tasks.id";
#		echo "
sql = '$sql'

";

		$result = pg_exec($this->dbh, $sql);
		if ($result) {
			$numrows = pg_numrows($result);
			if ($numrows == 1) {
#				echo "fetched by ID succeeded
";
				$myrow = pg_fetch_array ($result, 0);
				$this->tasks{$myrow[name]} = $myrow[id];
#				echo "\$myrow[name]='$myrow[name]' = $myrow[id]
\n";
#				echo "\$this->tasks{$myrow[name]} = '$this->tasks{$myrow[name]}'
\n";
			}
		}

        return $this->id;
	}
}

Allow us to add users to tasks

Allow us to add users to tasks

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


<?php

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

class CreateRoleUserPivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->primary(['role_id', 'user_id']);
        });
    }

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

Create roles-users pivot table so user can be assigned to multiple roles


<?php
/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace MpaCustomDoctrineHydratorTest\Assets\Entity;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Doctrine\ORM\Mapping\Entity;

class CustomGenerator extends AbstractIdGenerator
{
    /**
     * @param  EntityManager $entityManager
     * @param  Entity        $entity
     * @return integer
     */
    public function generate(EntityManager $entityManager, $entity)
    {
        return rand(10, 100);
    }
}

Add a custom generator for tests

Add a custom generator for tests


<?php
/**
 * This file is part of the Axstrad library.
 *
 * (c) Dan Kempster <dev@dankempster.co.uk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright 2014-2015 Dan Kempster <dev@dankempster.co.uk>
 */

namespace Axstrad\Component\Content\Tests\Unit;

use Axstrad\Component\Test\TestCase;

/**
 * Axstrad\Component\Content\Tests\Unit\BaseOrmEntityTest
 *
 * @author Dan Kempster <dev@dankempster.co.uk>
 * @license MIT
 * @package Axstrad/Content
 * @subpackage Tests
 * @group unit
 */
class BaseOrmEntityTest extends TestCase
{
    /**
     * @dataProvider fixtureProvider
     */
    public function testFixtureHasCopy($fixture)
    {
        $this->assertObjectHasAttribute(
            'copy',
            $fixture
        );
    }

    /**
     * @dataProvider fixtureProvider
     */
    public function testFixtureGetIdReturnsNull($fixture)
    {
        $this->assertNull($fixture->getId());
    }

    public function fixtureProvider()
    {
        return array(
            [$this->getMockForAbstractClass('Axstrad\Component\Content\Orm\Copy')],
            [$this->getMockForAbstractClass('Axstrad\Component\Content\Orm\Article')]
        );
    }

    /**
     * @dataProvider headingFixtureProvider
     */
    public function testFixtureHasHeading($fixture)
    {
        $this->assertObjectHasAttribute(
            'heading',
            $fixture
        );
    }

    public function headingFixtureProvider()
    {
        return array(
            [$this->getMockForAbstractClass('Axstrad\Component\Content\Orm\Article')]
        );
    }
}

Add unit test for the abstract entities

Add unit test for the abstract entities


<?php

namespace JWX\JWK\Parameter;

use JWX\Util\Base64;

class KeyValueParameter extends RegisteredJWKParameter
{
	/**
	 * Constructor
	 *
	 * @param string $key Base64url encoded key
	 */
	public function __construct($key) {
		parent::__construct(self::PARAM_KEY_VALUE, $key);
	}

	/**
	 * Initialize from binary key
	 *
	 * @param string $key
	 * @return self
	 */
	public static function fromKey($key) {
		return new self(Base64::urlEncode($key));
	}

	/**
	 * Get key in binary format
	 *
	 * @return string
	 */
	public function key() {
		return Base64::urlDecode($this->_value);
	}
}

Add JWK Key Value parameter

Add JWK Key Value parameter


<?php

use Phinx\Migration\AbstractMigration;

class MentorApprenticeLinkTableCreate extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     *
     * Uncomment this method if you would like to use it.
     *
    public function change()
    {
    }
    */

    /**
     * Migrate Up.
     */
    public function up()
    {
        $mentorApprenticeXref = $this->table('mentorApprenticeXref');
        $mentorApprenticeXref
            ->addColumn('mentorId', 'integer')
            ->addColumn('apprenticeId', 'integer')
            ->create()
        ;
    }

    /**
     * Migrate Down.
     */
    public function down()
    {
        $this->dropTable('mentorApprenticeXref');
    }
}

Add database migration for Mentor Apprentice link table


<?php
    require_once '..\docx2md.php';

    $converter = new Docx2md\Docx2md;

    $files = glob('docx/*.docx', GLOB_BRACE);
    foreach ($files as $file) {
        echo $converter->parseFile($file) . '

';
    }

Create example script demoing the converter


<?php

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

class MakePopularityScoresSigned extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        /** doctrine/dbal can't handle ALTERing the `events` table because the `state`
         * column is an ENUM even though we aren’t touching that column.
         * Therefore just use raw SQL instead
         *
            Schema::table('events', function (Blueprint $table) {
                $table->decimal('popularity_score', 12, 6)->change();
                $table->decimal('short_term_popularity_score', 7, 6)->change();
                $table->decimal('long_term_popularity_score', 7, 6)->change();
            });

            Schema::table('performers', function (Blueprint $table) {
                $table->decimal('popularity_score', 7, 6)->change();
            });

            Schema::table('venues', function (Blueprint $table) {
                $table->decimal('popularity_score', 7, 6)->change();
            });
         */
        DB::statement('ALTER TABLE `events` CHANGE COLUMN `popularity_score` `popularity_score` DECIMAL(12, 6) NOT NULL DEFAULT 0.000000  COMMENT \'\' AFTER `category_id`;');
        DB::statement('ALTER TABLE `events` CHANGE COLUMN `short_term_popularity_score` `short_term_popularity_score` DECIMAL(7, 6) NOT NULL DEFAULT 0.000000  COMMENT \'\' AFTER `popularity_score`;');
        DB::statement('ALTER TABLE `events` CHANGE COLUMN `long_term_popularity_score` `long_term_popularity_score` DECIMAL(7, 6) NOT NULL DEFAULT 0.000000  COMMENT \'\' AFTER `short_term_popularity_score`;');

        DB::statement('ALTER TABLE `performers` CHANGE COLUMN `popularity_score` `popularity_score` DECIMAL(7, 6) NOT NULL DEFAULT 0.000000  COMMENT \'\' AFTER `category_id`;');

        DB::statement('ALTER TABLE `tevoharvester`.`venues` CHANGE COLUMN `popularity_score` `popularity_score` DECIMAL(7, 6) NOT NULL DEFAULT 0.000000  COMMENT \'\' AFTER `slug`;');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // As the band Boston said, Don’t Look Back
    }
}

Add migration to make `popularity_score`s signed

Ticket Evolution is allowing negative `popularity_score`s, which doesn’t make any sense, but easier to handle it here than to get it fixed at the source.


<?php

namespace Lanin\Laravel\ApiExceptions;

use Exception;
use Lanin\Laravel\ApiExceptions\Contracts\DontReport;

class ValidationFailedApiException extends ApiException implements DontReport
{
    /**
     * @var array
     */
    protected $errors = [];

    /**
     * Create a new ValidationFailedApiException.
     *
     * @param array $errors
     * @param string $message
     * @param Exception $previous
     */
    public function __construct(array $errors, $message = '', Exception $previous = null)
    {
        $this->errors = $errors;

        if (empty($message)) {
            $message = 'Validation failed.';
        }

        parent::__construct(422, 'validation_failed', $message, $previous);
    }

    /**
     * Get array of errors
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Add extra info to the output.
     *
     * @return mixed
     */
    public function getMeta()
    {
        return [
            'errors' => $this->getErrors(),
        ];
    }
}

<?php

namespace Lanin\Laravel\ApiExceptions;

use Exception;
use Lanin\Laravel\ApiExceptions\Contracts\DontReport;

class ValidationFailedApiException extends ApiException implements DontReport
{
    /**
     * @var array
     */
    protected $errors = [];

    /**
     * Create a new ValidationFailedApiException.
     *
     * @param array $errors
     * @param string $message
     * @param Exception $previous
     */
    public function __construct(array $errors, $message = '', Exception $previous = null)
    {
        $this->errors = $errors;

        if (empty($message)) {
            $message = 'Validation failed.';
        }

        parent::__construct(422, 'validation_failed', $message, $previous);
    }

    /**
     * Get array of errors
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Convert and return validations errors in native Laravel way.
     *
     * @return array
     */
    public function getNativeErrors()
    {
        $return = [];

        foreach ($this->errors as $field => $errors) {
            $return[$field] = [];
            foreach ($errors as $error) {
                $return[$field][] = $error['message'];
            }
        }

        return $return;
    }

    /**
     * Add extra info to the output.
     *
     * @return mixed
     */
    public function getMeta()
    {
        return [
            'errors' => $this->getErrors(),
        ];
    }
}

Add getNativeErrors method to return validation errors in Laravel way.


<?php

use Phinx\Migration\AbstractMigration;

class SetDefaultValueToIsPublicOnDocs extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    addCustomColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Any other destructive changes will result in an error when trying to
     * rollback the migration.
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function up()
    {
        $this->table('documents')
             ->changeColumn('is_public', 'boolean', ['default' => false])
             ->update();
    }

    public function down()
    {
        $this->table('documents')
             ->changeColumn('is_public', 'boolean')
             ->update();
    }
}

Fix default value on is_public to false

Fix default value on is_public to false


<?php

use yii\db\Schema;
use console\components\Migration;

class m150730_113623_create_junction_in_section_table extends Migration
{
    public function up()
    {
        $this->addColumn('{{%section}}', 'section_id', Schema::TYPE_INTEGER . ' NULL DEFAULT NULL');
        $this->createIndex('section__section_id', '{{%section}}', 'section_id');
        $this->addForeignKey('section__section_id', '{{%section}}', 'section_id', '{{%section}}', 'id', 'SET NULL', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('section__section_id', '{{%section}}');
        $this->dropIndex('section__section_id', '{{%section}}');
        $this->dropColumn('{{%section}}', 'section_id');
    }
}

Add section ID foreign key column to section table.


<?php

namespace spec\MageTest\PhpSpec\MagentoExtension\Extension;

use MageTest\PhpSpec\MagentoExtension\Extension\LocatorFactory;
use MageTest\PhpSpec\MagentoExtension\Locator\Magento\BlockLocator;
use MageTest\PhpSpec\MagentoExtension\Locator\Magento\ControllerLocator;
use MageTest\PhpSpec\MagentoExtension\Locator\Magento\HelperLocator;
use MageTest\PhpSpec\MagentoExtension\Locator\Magento\ModelLocator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class LocatorFactorySpec extends ObjectBehavior
{
    function it_should_get_block_locator()
    {
        $this->getLocator('block')->shouldHaveType(BlockLocator::class);
    }

    function it_should_get_model_locator()
    {
        $this->getLocator('model')->shouldHaveType(ModelLocator::class);
    }

    function it_should_get_helper_locator()
    {
        $this->getLocator('helper')->shouldHaveType(HelperLocator::class);
    }

    function it_should_get_controller_locator()
    {
        $this->getLocator('controller')->shouldHaveType(ControllerLocator::class);
    }

    function it_should_throw_exception_when_an_unrecognised_type_is_used()
    {
        $this->shouldThrow(\RuntimeException::class)->duringGetLocator('foo');
    }
}

Add specs for locator factory

Add specs for locator factory


<?php

namespace App\Commands;

use App\Actions\EditAfter as EditAfterAction;
use LaravelZero\Framework\Commands\Command;

class EditAfter extends Command
{
    protected $signature = 'edit-after {--editor= : Open the config file in the specified <info>EDITOR</info> or the system default if none is specified.}';

    protected $description = 'Edit Config File. A new config file is created if one does not already exist.';

    public function handle()
    {
        app()->bind('console', function () {
            return $this;
        });

        app(EditAfterAction::class)();
    }
}

Revert "remove redundant edit-after command."

This reverts commit 34005c38


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

namespace ZendTest\Cache\Storage\Adapter;

use Zend\Cache;
use Zend\Session\Container as SessionContainer;
use Zend\Session\Config\StandardConfig as SessionConfig;
use ZendTest\Session\TestAsset\TestManager as TestSessionManager;

/**
 * @group      Zend_Cache
 */
class SessionTest extends CommonAdapterTest
{
    public function setUp()
    {
        $_SESSION = array();
        SessionContainer::setDefaultManager(null);
        $sessionConfig    = new SessionConfig(array('storage' => 'Zend\Session\Storage\ArrayStorage'));
        $sessionManager   = $manager = new TestSessionManager($sessionConfig);
        $sessionContainer = new SessionContainer('Default', $manager);

        $this->_options = new Cache\Storage\Adapter\SessionOptions(array(
            'session_container' => $sessionContainer
        ));
        $this->_storage = new Cache\Storage\Adapter\Session();
        $this->_storage->setOptions($this->_options);

        parent::setUp();
    }

    public function tearDown()
    {
        $_SESSION = array();
        SessionContainer::setDefaultManager(null);
    }
}

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

namespace ZendTest\Cache\Storage\Adapter;

use Zend\Cache;
use Zend\Session\Container as SessionContainer;

/**
 * @group      Zend_Cache
 */
class SessionTest extends CommonAdapterTest
{
    public function setUp()
    {
        $_SESSION = array();
        SessionContainer::setDefaultManager(null);
        $sessionContainer = new SessionContainer('Default');

        $this->_options = new Cache\Storage\Adapter\SessionOptions(array(
            'session_container' => $sessionContainer
        ));
        $this->_storage = new Cache\Storage\Adapter\Session();
        $this->_storage->setOptions($this->_options);

        parent::setUp();
    }

    public function tearDown()
    {
        $_SESSION = array();
        SessionContainer::setDefaultManager(null);
    }
}

Fix tests which require optional zend-session asset


<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20190826000000 extends AbstractMigration implements RepeatableMigrationInterface
{

    public function upgradeDatabase()
    {
        /* Refresh youtube block */
        $this->refreshBlockType('youtube');
    }
}

Add a migration to refresh the YouTube block


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * 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 license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Loader
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * @namespace
 */
namespace Zend\Loader;

/**
 * Pluggable class interface
 *
 * @category   Zend
 * @package    Zend_Loader
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Pluggable
{
    /**
     * Get plugin broker instance
     *
     * @return Zend\Loader\Broker
     */
    public function getBroker();

    /**
     * Set plugin broker instance
     *
     * @param  string|Broker $broker Plugin broker to load plugins
     * @return Zend\Loader\Pluggable
     */
    public function setBroker($broker);

    /**
     * Get plugin instance
     *
     * @param  string     $plugin  Name of plugin to return
     * @param  null|array $options Options to pass to plugin constructor (if not already instantiated)
     * @return mixed
     */
    public function plugin($name, array $options = null);
}

Add missing pluggable interface file.

Add missing pluggable interface file.


<?php
/**
 * This file is part of the backlog-velocity.
 *
 * (c) Yannick Voyer (http://github.com/yvoyer)
 */

namespace Star\Component\Sprint\Tests\Functional;

use Star\Component\Sprint\Entity\EntityInterface;
use Star\Component\Sprint\Entity\Sprinter;
use Star\Component\Sprint\Entity\Team;

/**
 * Class DoctrineMappingTest
 *
 * @author  Yannick Voyer (http://github.com/yvoyer)
 *
 * @package Star\Component\Sprint\Tests\Functional
 */
class DoctrineMappingTest extends FunctionalTestCase
{
    /**
     * Returns a refreshed object containing data from db.
     *
     * @param EntityInterface $object
     *
     * @return EntityInterface
     */
    private function getRefreshedObject(EntityInterface $object)
    {
        $em = $this->getEntityManager();
        $em->clear();

        $id = $object->getId();
        $this->assertNotNull($id, 'The id should not be null');

        return $em->find(get_class($object), $id);
    }

    public function testShouldPersistTeam()
    {
        $name = uniqid('team-name-');
        $team = new Team($name);

        $em = $this->getEntityManager();
        $em->persist($team);
        $em->flush();

        /**
         * @var $team Team
         */
        $team = $this->getRefreshedObject($team);

        $this->assertSame($name, $team->getName(), 'Name is not as expected');
    }

    public function testShouldPersistSprinter()
    {
        $name     = uniqid('sprinter-name-');
        $sprinter = new Sprinter($name);

        $em = $this->getEntityManager();
        $em->persist($sprinter);
        $em->flush();

        /**
         * @var $sprinter Sprinter
         */
        $sprinter = $this->getRefreshedObject($sprinter);

        $this->assertSame($name, $sprinter->getName(), 'Name is not as expected');
    }
}

Add functional test for doctrine mapping


<?php
/**
 * Test the DATE column.
 *
 * @author    Steven A Zahm
 * @since     2.0
 * @license   MIT
 * @copyright Iron Bound Designs, 2016.
 */

namespace IronBound\DB\Tests\Unit\Columns;

use IronBound\DB\Table\Column\Date;

/**
 * Class Test_DateTime
 *
 * @package IronBound\DB\Tests\Unit\Columns
 */
class Test_Date extends \WP_UnitTestCase {

	public function test_convert_raw_to_value_returns_null_for_empty_values() {

		$datetime = new Date( 'created' );

		$this->assertNull( $datetime->convert_raw_to_value( '' ) );
	}

	public function test_convert_raw_to_value_returns_null_for_invalid_values() {

		$datetime = new Date( 'created' );

		$this->assertNull( $datetime->convert_raw_to_value( 'garbage' ) );
	}

	public function test_prepare_for_storage_returns_null_for_empty_values() {

		$datetime = new Date( 'created' );

		$this->assertNull( $datetime->prepare_for_storage( '' ) );
	}

	/**
	 * @expectedException \IronBound\DB\Exception\InvalidDataForColumnException
	 */
	public function test_prepare_for_storage_throws_exception_for_invalid_object() {

		$datetime = new Date( 'created' );

		$this->assertNull( $datetime->prepare_for_storage( new \stdClass() ) );
	}

	/**
	 * @dataProvider _dp_prepare_for_storage
	 *
	 * @param mixed  $value
	 * @param string $expected
	 */
	public function test_prepare_for_storage( $value, $expected ) {

		$column = new Date( 'created' );

		$this->assertEquals( $expected, $column->prepare_for_storage( $value ) );
	}

	public function _dp_prepare_for_storage() {
		return array(
			array( 1469386689, '2016-07-24' ),
			array( 'July 24, 2016 6pm', '2016-07-24' ),
			array( '2016-07-24 18:58:09', '2016-07-24' ),
			array( new \DateTime( '2016-07-24 18:58:09', new \DateTimeZone( 'UTC' ) ), '2016-07-24' )
		);
	}
}

Add unit tests for `Date` column.

Add unit tests for `Date` column.


<?php

	if (Permission::Insufficient('developer'))
		CoreUtils::NotFound();

	header('Content-Type: text/plain; charset=utf-8;');
	readfile(APPATH.'../mlpvc-rr-error.log');

Add a page to show error log file

Add a page to show error log file


<?php

namespace Tests\Regis\Application\CommandHandler\Github\Inspection;

use Regis\Application\Command;
use Regis\Application\CommandHandler;
use Regis\Application\Entity\Github\PullRequestInspection;
use Regis\Application\Entity\Inspection\Report;
use Regis\Application\Entity\Inspection\Violation;
use Regis\Application\Model\Github\PullRequest;
use Regis\Application\Reporter;

class SendViolationsAsCommentsTest extends \PHPUnit_Framework_TestCase
{
    private $reporter;
    /** @var CommandHandler\Github\Inspection\SendViolationsAsComments */
    private $handler;

    public function setUp()
    {
        $this->reporter = $this->getMockBuilder(Reporter::class)->getMock();
        $this->handler = new CommandHandler\Github\Inspection\SendViolationsAsComments($this->reporter);
    }

    public function testViolationsAreTransferedToTheReporter()
    {
        $pullRequest = $this->getMockBuilder(PullRequest::class)->disableOriginalConstructor()->getMock();
        $inspection = $this->getMockBuilder(PullRequestInspection::class)->disableOriginalConstructor()->getMock();
        $report = $this->getMockBuilder(Report::class)->disableOriginalConstructor()->getMock();

        $violation1 = $this->getMockBuilder(Violation::class)->disableOriginalConstructor()->getMock();
        $violation2 = $this->getMockBuilder(Violation::class)->disableOriginalConstructor()->getMock();

        $inspection->expects($this->once())
            ->method('getReport')
            ->will($this->returnValue($report));
        $report->expects($this->once())
            ->method('getViolations')
            ->will($this->returnValue(new \ArrayIterator([$violation1, $violation2])));

        $this->reporter->expects($this->exactly(2))
            ->method('report')
            ->withConsecutive(
                [$violation1, $pullRequest],
                [$violation1, $pullRequest]
            );

        $command = new Command\Github\Inspection\SendViolationsAsComments($inspection, $pullRequest);

        $this->handler->handle($command);
    }
}

Add tests for the SendViolationsAsComments command handler


<?php

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

class RemoveEventIdFromPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropForeign('posts_event_id_foreign');
            $table->dropIndex('posts_event_id_index');
            $table->dropColumn('event_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->integer('event_id')->unsigned()->index()->comment('The event this post corresponds to.');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
        });
    }
}

Drop event_id from posts table

Drop event_id from posts table


<?php

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

class AddRememberTokenAndTimestampsToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropRememberToken();
            $table->dropTimestamps();
        });
    }
}

Add database migration for remember token and timestamps for user model.


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

$client = new apiClient();
$client->setApplicationName('Google Translate PHP Starter Application');

// Visit https://code.google.com/apis/console?api=translate to generate your
// client id, client secret, and to register your redirect uri.
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiTranslateService($client);

$langs = $service->languages->listLanguages();
print "
Languages

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

$translations = $service->translations->listTranslations('Hello', 'hi');
print "
Translations

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

Add a sample application for the Google Translate service.


<?php

namespace Illuminate\Database\Query\Processors;

use Illuminate\Database\Query\Builder;

class SqlServerProcessor extends Processor
{
    /**
     * Process an "insert get ID" query.
     *
     * @param  \Illuminate\Database\Query\Builder  $query
     * @param  string  $sql
     * @param  array   $values
     * @param  string  $sequence
     * @return int
     */
    public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
    {
        $query->getConnection()->insert($sql, $values);

        $id = $query->getConnection()->getPdo()->lastInsertId();

        return is_numeric($id) ? (int) $id : $id;
    }

    /**
     * Process the results of a column listing query.
     *
     * @param  array  $results
     * @return array
     */
    public function processColumnListing($results)
    {
        $mapping = function ($r) {
            $r = (object) $r;

            return $r->name;
        };

        return array_map($mapping, $results);
    }
}

<?php

namespace Illuminate\Database\Query\Processors;

use Illuminate\Database\Query\Builder;

class SqlServerProcessor extends Processor
{
    /**
     * Process an "insert get ID" query.
     *
     * @param  \Illuminate\Database\Query\Builder  $query
     * @param  string  $sql
     * @param  array   $values
     * @param  string  $sequence
     * @return int
     */
    public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
    {
        $connection = $query->getConnection();
        $connection->insert($sql, $values);
        if ($connection->getConfig('odbc') === true) {
            $result = $connection->select("SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid");
            if (!$result) {
                throw new Exception('Error retrieving lastInsertId');
            }
            $id = $result[0]->insertid;
        }
        else {
            $id = $connection->getPdo()->lastInsertId();
        }

        return is_numeric($id) ? (int) $id : $id;
    }

    /**
     * Process the results of a column listing query.
     *
     * @param  array  $results
     * @return array
     */
    public function processColumnListing($results)
    {
        $mapping = function ($r) {
            $r = (object) $r;

            return $r->name;
        };

        return array_map($mapping, $results);
    }
}

Work around lack of lastInsertId() for ODBC with PDO for MSSQL


<?
include '../scat.php';
include '../lib/item.php';

$id= (int)$_REQUEST['id'];

$code= $_REQUEST['code'];

if (!$id && $code) {
  $code= $db->escape($code);
  $q= "SELECT id FROM item WHERE code = '$code'";
  $id= $db->get_one($q);
};

if (!$id)
  die_jsonp("No item specified.");

$item= item_load($db, $id);

echo jsonp(array('item' => $item));

Add (unused) item load API

Add (unused) item load API


<?php

/*
* The settings in this file are used to validate user input.
* They define the minimum and maximum lengts of data the user can enter throughout the application.
*/

abstract class DataValidationConfig {
    const PASSWORDMINLENGTH = 8;
    const PASSWORDMAXLENGTH = 1000;
    const EMAILMAXLENGTH = 50;

    const STRINGMAXLENGTH = 30;
    const HOUSENUMBERMAXLENGTH = 4;
    const POSTALCODEMINLENGTH = 4;
    const POSTALCODEMAXLENGTH = 6;
    const PHONEMAXLENGTH = 14;
    const DATEMAXLENGTH = 10;
    const BALANCEMAXLENGTH = 10;
    const YEARMAXLENGTH = 4;
    const CARDNUMBERMAXLENGTH = 8;

    const ADMINPERMISSIONMIN = 0;
    const ADMINPERMISSIONMAX = 1;
    const USERMANAGERPERMISSIONMIN = 0;
    const USERMANAGERPERMISSIONMAX = 1;
    const AUTHORIZEDBROWSERMANAGERPERMISSIONMIN = 0;
    const AUTHORIZEDBROWSERMANAGERPERMISSIONMAX = 1;
}

Add config file that hold global values for form validation.


<?php

namespace Radvance\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;
use Symfony\Component\Process\Exception\ProcessFailedException;
use RuntimeException;

class SchemaLoadCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('schema:load')
            ->setDescription('Uses dbtk-schema-loader to update db schema')
            ->addOption(
                'apply',
                null,
                InputOption::VALUE_NONE,
                'Apply allow you to synchronise schema'
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $apply = $input->getOption('apply');
        $filename = 'app/config/parameters.yml';
        if (!file_exists($filename)) {
            throw new RuntimeException("No such file: " . $filename);
        }
        $data = file_get_contents($filename);
        $config = Yaml::parse($data);

        if (isset($config['pdo'])) {
            $pdo = $config['pdo'];
        } else {
            if (!isset($config['parameters']['pdo'])) {
                throw new RuntimeException("Can't find pdo configuration");
            }
            $pdo = $config['parameters']['pdo'];
        }

        $cmd = 'vendor/bin/dbtk-schema-loader schema:load app/schema.xml ' . $pdo;
        if ($apply) {
            $cmd .= ' --apply';
        }

        $process = new Process($cmd);
        $output->writeLn($process->getCommandLine());
        $process->run();

        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }
        $output->write($process->getOutput());
    }
}

Add schema:load command that reuses config info from parameters.yml


<?php namespace Flarum\Events;

use Flarum\Api\Request;
use Flarum\Http\RouteCollection;
use Psr\Http\Message\ServerRequestInterface;

class RegisterApiRoutes
{
    /**
     * @var RouteCollection
     */
    public $routes;

    /**
     * @param RouteCollection $routes
     */
    public function __construct(RouteCollection $routes)
    {
        $this->routes = $routes;
    }

    public function get($url, $name, $action)
    {
        $this->route('get', $url, $name, $action);
    }

    public function patch($url, $name, $action)
    {
        $this->route('patch', $url, $name, $action);
    }

    protected function route($method, $url, $name, $action)
    {
        $this->routes->$method($url, $name, $this->action($action));
    }

    protected function action($class)
    {
        return function (ServerRequestInterface $httpRequest, $routeParams) use ($class) {
            $action = app($class);
            $actor = app('flarum.actor');

            $input = array_merge($httpRequest->getQueryParams(), $httpRequest->getAttributes(), $routeParams);
            $request = new Request($input, $actor, $httpRequest);

            return $action->handle($request);
        };
    }
}

Allow for the addition of new API endpoints


<?php
declare(strict_types=1);

namespace Xerkus\Neovim\Plugin\RpcHandler;

/**
 * Rpc handler that announces itself to neovim.
 *
 */
interface RpcSpec
{
    /**
     * Rpc method name, usually "{$path}:{$type}:{$name}"
     */
    public function getMethodName() : string;

    /**
     * Rpc type
     */
    public function getType() : string;

    /**
     * Name of the function, command or autocommand, etc
     */
    public function getName() : string;

    /**
     * Sync-ed rpc calls are blocking neovim
     *
     * Async call does not block and ignores return value or errors
     *
     * Note to implementors: blocking call does not mean plugin can not receive
     * nested calls. Be carefull not to cause deadlock
     */
    public function getIsSync() : bool;

    /**
     * List of Rpc options
     */
    public function getOpts() : array;

    /**
     * Rpc handler spec as array prepared for export to neovim
     *
     * Returns array with keys 'type', 'name', 'sync' and 'opts'
     */
    public function getSpecArray() : array;

    /**
     * Controls where rpc handler should be announced to neovim
     *
     * Currently only 'command', 'autocmd' and 'function' types are supported
     * by neovim and exported on 'specs' request
     */
    public function getShouldExport() : bool;

    /**
     *
     */
    public function getPluginPath();

    /**
     * Returns spec with plugin path $pluginPath
     */
    public function withPluginPath(string $pluginPath = null) : self;
}

Add initial interface for rpc handler spec object


<?php

namespace ilateral\SilverStripe\Searchable\Tasks;

use ilateral\SilverStripe\Searchable\Model\SearchTable;
use ilateral\SilverStripe\Searchable\Searchable;
use SilverStripe\ORM\DB;
use SilverStripe\Dev\BuildTask;
use SilverStripe\Control\Director;
use SilverStripe\ORM\DatabaseAdmin;
use SilverStripe\Control\Controller;

/**
 * Take data from linked objects and import into search table
 */
class ImportSearchDataTask extends BuildTask
{

    /**
     * Should this task be invoked automatically via dev/build?
     *
     * @config
     *
     * @var bool
     */
    private static $run_during_dev_build = true;

    private static $segment = 'ImportSearchDataTask';

    protected $title = "Import search data";

    protected $description = "Import data into search table";

    /**
     * Run this task
     *
     * @param \SilverStripe\Control\HTTPRequest $request The current request
     *
     * @return void
     */
    public function run($request)
    {
        $objects = Searchable::config()->objects;

        foreach (array_keys($objects) as $classname) {
            $this->log("Importing {$classname}");
            $count = $this->importObject($classname);
            $this->log("Impoted {$count} records");
        }
    }

    /**
     * Import a single object class into search table and return how
     * many objects were imported
     *
     * @param string $classname
     *
     * @return int
     */
    protected function importObject($classname)
    {
        $count = 0;

        foreach ($classname::get() as $object) {
            $search = SearchTable::get()
                ->filter(
                    [
                        'BaseObjectID' => $object->ID,
                        'BaseObjectClass' => get_class($object)
                    ]
                )->first();

            if (empty($search)) {
                $search = SearchTable::create();
                $search->BaseObjectID = $object->ID;
                $search->BaseObjectClass = get_class($object);
            }

            $data = $object->toMap();
            unset($data['ID']);
            unset($data['ClassName']);

            $search->update($data);
            $search->write();
            $count++;
        }

        return $count;
    }

    /**
     * @param string $text
     */
    protected function log($text)
    {
        if (Controller::curr() instanceof DatabaseAdmin) {
            DB::alteration_message($text, 'obsolete');
        } elseif (Director::is_cli()) {
            echo $text . "\n";
        } else {
            echo $text . "<br/>";
        }
    }
}

Add custom build task to fill search table with related data


<?php

namespace Imhonet\Connection\DataFormat\Arr\PDO;

use Imhonet\Connection\DataFormat\IArr;

class Group implements IArr
{

    private $data;

    private $groups = [];

    public function addGroup($group_field)
    {
        $this->groups[] = $group_field;

        return $this;
    }

    /**
     * @param mixed $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;

        return $this;
    }

    /**
     * @return array
     */
    public function formatData()
    {
        $result = [];

        foreach ($this->data as $row) {
            $cutted = $row;
            $point = & $result;
            foreach ($this->groups as $group) {
                assert(isset($cutted[$group]));

                if (!isset($point[$cutted[$group]])) {
                    $point[$cutted[$group]] = [];
                }
                $point = & $point[$cutted[$group]];
                unset($cutted[$group]);
            }
            $point[] = $cutted;
        }

        return $result;
    }

    /**
     * @return null
     */
    public function formatValue()
    {
        return null;
    }
}

Add group data format to PDO Arr

Add group data format to PDO Arr


<?php

class TestActionRead
    extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->config  = $this->getMockBuilder('\Noodlehaus\ConfigInterface')->getMock();
        $this->logger  = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();
        $this->adapter = $this->getMockBuilder('\SlimMicroService\Adapter\AdapterInterface')->getMock();

        $this->request  = $this->getMockBuilder('\Slim\Http\Request')->disableOriginalConstructor()->getMock();
        $this->response = $this->getMockBuilder('\Slim\Http\Response')->disableOriginalConstructor()->getMock();

        $this->class = new \SlimMicroService\Action\ActionRead($this->config, $this->logger, $this->adapter);
    }

    public function testMethodDispatchNotFoundBehavior()
    {
        $responseData = array(
            'status'  => 'error',
            'content' => 'Resource not found!'
        );

        $this->adapter
            ->expects($this->once())
            ->method('read')
            ->with('example', '0')
            ->will($this->returnValue(NULL));

        $this->response
            ->expects($this->once())
            ->method('withJson')
            ->with($responseData, 404);

        $this->class->dispatch(
            $this->request,
            $this->response,
            array('resource' => 'example', 'id' => '0')
        );
    }

    public function testMethodDispatchFoundBehavior()
    {
        $enityData = array('id' => '0', 'name' => 'example');

        $responseData = array(
            'status'  => 'ok',
            'content' => $enityData
        );

        $this->adapter
            ->expects($this->once())
            ->method('read')
            ->with('example', '0')
            ->will($this->returnValue($enityData));

        $this->response
            ->expects($this->once())
            ->method('withJson')
            ->with($responseData, 200);

        $this->class->dispatch(
            $this->request,
            $this->response,
            array('resource' => 'example', 'id' => '0')
        );
    }
}

Add PHPUnit test for \Aciton\AcitonRead

Add PHPUnit test for \Aciton\AcitonRead


<?php

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

class CreateWorldsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('worlds', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('realm_id');
            $table->string('name');
            $table->boolean('pvp')->default(true);
            $table->smallInteger('gamemode')->default(0);
            $table->boolean('spawn_animals')->default(true);
            $table->smallInteger('difficulty')->default(1);
            $table->boolean('spawn_monsters')->default(true);
            $table->integer('spawn_protection')->default(0);
            $table->boolean('spawn_npcs')->default(true);
            $table->boolean('force_gamemode')->default(false);
            $table->boolean('command_blocks')->default(false);
        });
    }

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

Add migration for worlds table.

Add migration for worlds table.


<?php
/*
 * 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, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace ProxyManagerTestAsset;

/**
 * Class with a private property whose collides with the parent class' property naming
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
class ClassWithCollidingPrivateInheritedProperties extends ClassWithPrivateProperties
{
    /**
     * @var string
     */
    private $property0 = 'childClassProperty0';
}

Test asset for classes with colliding inherited properties


<?php
/**
 * Has_Multiple_AdminsTest
 *
 * @package   Google
 * @copyright 2021 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Tests\Core\Authentication;

use Google\Site_Kit\Context;
use Google\Site_Kit\Core\Authentication\Has_Multiple_Admins;
use Google\Site_Kit\Core\Storage\Transients;
use Google\Site_Kit\Tests\TestCase;

/**
 * @group Authentication
 */
class Has_Multiple_AdminsTest extends TestCase {

	/**
	 * @var Context
	 */
	protected $context;

	/**
	 * @var Transients
	 */
	protected $transients;

	public function setUp() {
		parent::setUp();
		$this->context    = new Context( GOOGLESITEKIT_PLUGIN_MAIN_FILE );
		$this->transients = new Transients( $this->context );
	}

	public function test_get() {
		$has_multiple_admins = new Has_Multiple_Admins( $this->transients );

		// Should return FALSE since we don't have multiple admins yet.
		$this->assertFalse( $has_multiple_admins->get() );

		// Create a second admin, the first one (with ID=1) we already have.
		$this->factory()->user->create( array( 'role' => 'administrator' ) );

		// Delete the transient and check that we have multiple admins now.
		$this->transients->delete( Has_Multiple_Admins::OPTION );
		$this->assertTrue( $has_multiple_admins->get() );
	}

}

Add a test for the php class.

Add a test for the php class.


<?php
/**
 * @author    Andreas Fischer <bantu@phpbb.com>
 * @copyright MMXIV Andreas Fischer
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

require_once 'Net/SFTP/Stream.php';

class Unit_Net_SFTPStreamTest extends PhpseclibTestCase
{
    protected $protocol = 'sftptest';

    public function setUp()
    {
        parent::setUp();
        if (in_array($this->protocol, stream_get_wrappers())) {
            stream_wrapper_unregister($this->protocol);
        }
    }

    public function testRegisterFromSideEffect()
    {
        // Including the file registers 'sftp' as a stream.
        $this->assertContains('sftp', stream_get_wrappers());
    }

    public function testRegisterWithArgument()
    {
        Net_SFTP_Stream::register($this->protocol);
        $this->assertContains($this->protocol, stream_get_wrappers());
    }
}

Add unit test for (to be added) Net_SFTP_Stream::register().


<?php
/**
 * Tests for the MediaObject schema.
 *
 * @package Schemify
 */

namespace Test\Schemas;

use Schemify\Schemas\CreativeWork;
use Schemify\Schemas\MediaObject;
use WP_UnitTestCase;

class MediaObjectTest extends WP_UnitTestCase {

	public function testGetAssociatedArticle() {
		$post       = $this->factory()->post->create();
		$attachment = $this->factory()->attachment->create( [
			'post_parent' => $post,
		] );
		$media      = new MediaObject( $attachment, true );

		$this->assertInstanceOf( CreativeWork::class, $media->getAssociatedArticle( $attachment ) );
	}

	public function testGetAssociatedArticleReturnsNullIfNotMain() {
		$media = new MediaObject( 123, false );

		$this->assertNull( $media->getAssociatedArticle( 123 ) );
	}

	/**
	 * @expectedException PHPUnit_Framework_Error_Warning
	 */
	public function testGetAssociatedArticleHandlesMissingSchemas() {
		$post       = $this->factory()->post->create();
		$attachment = $this->factory()->attachment->create( [
			'post_parent' => $post,
		] );
		$media      = new MediaObject( $attachment, true );

		add_filter( 'schemify_schema', function () {
			return 'ThisIsNotAClass';
		} );

		$this->assertNull( $media->getAssociatedArticle( $attachment ) );
	}

	public function testGetAssociatedArticleIfMediaIsUnattached() {
		$attachment = $this->factory()->attachment->create();
		$media      = new MediaObject( $attachment, true );

		$this->assertNull( $media->getAssociatedArticle( $attachment ) );
	}

	public function testGetContentUrl() {
		$post  = $this->factory()->attachment->create();
		$media = new MediaObject( $post );

		add_filter( 'wp_get_attachment_url', function () {
			return 'https://example.com/foo';
		} );

		$this->assertEquals( 'https://example.com/foo', $media->getContentUrl( $post ) );
	}

	public function testGetThumbnailUrl() {
		$post  = $this->factory()->attachment->create();
		$media = new MediaObject( $post );

		add_filter( 'wp_get_attachment_image_src', function () {
			return [ 'https://example.com/foo.jpg', 150, 150 ];
		} );

		$this->assertEquals( 'https://example.com/foo.jpg', $media->getThumbnailUrl( $post ) );
	}

	public function testGetThumbnailUrlReturnsNullIfThumbnailIsNotFound() {
		$media = new MediaObject( 123 );

		add_filter( 'wp_get_attachment_image_src', function () {
			return false;
		} );

		$this->assertNull( $media->getThumbnailUrl( 123 ) );
	}
}

Add tests for the MediaObject schema

Add tests for the MediaObject schema


<?php

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

class AddLevelToUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('users', function(Blueprint $table) {
			$table->enum('level', array('beginner','advance','expert'))->default('beginner');
		});
	}

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

}

Add level to the user model

Add level to the user model


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

namespace PH7\Test\Unit\App\System\Module\ProfileFaker\Inc\Classes;

require_once PH7_PATH_SYS_MOD . 'profile-faker/inc/class/Cleanup.php';

use PH7\Cleanup;
use PHPUnit_Framework_TestCase;

class CleanupTest extends PHPUnit_Framework_TestCase
{
    /**
     * @param string $sActualUsername
     * @param string $sExpectedUsername
     * @param int $iLength
     *
     * @dataProvider usernamesProvider
     */
    public function testUsername($sActualUsername, $sExpectedUsername, $iLength)
    {
        $sCleanedUsername = Cleanup::username($sActualUsername, $iLength);
        $this->assertSame($sCleanedUsername, $sExpectedUsername);
    }

    /**
     * @return array
     */
    public function usernamesProvider()
    {
        return [
            ['pierre.soria', 'pierre-soria', 40],
            ['pierre-henry soria', 'pierre-henry-soria', 40],
            ['Marie-Amelie.Rollier', 'Marie-Amelie-R', 14],
            ['marie..heloise Beghin', 'marie--helois', 13],
            ['.', '', 0]
        ];
    }
}

Add unit test for Username Cleanup class


<?php

namespace Risan\OAuth1\Test\Unit\Provider;

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Provider\Upwork;
use Risan\OAuth1\Signature\HmacSha1Signer;
use Risan\OAuth1\Provider\ProviderInterface;

class UpworkTest extends TestCase
{
    private $upwork;

    function setUp()
    {
        $this->upwork = new Upwork();
    }

    /** @test */
    function it_implements_provider_interface()
    {
        $this->assertInstanceOf(ProviderInterface::class, $this->upwork);
    }

    /** @test */
    function it_has_correct_uri_config()
    {
        $this->assertEquals([
            'temporary_credentials_uri' => 'https://www.upwork.com/api/auth/v1/oauth/token/request',
            'authorization_uri' => 'https://www.upwork.com/services/api/auth',
            'token_credentials_uri' => 'https://www.upwork.com/api/auth/v1/oauth/token/access',
            'base_uri' => 'https://www.upwork.com/',
        ], $this->upwork->getUriConfig());
    }

    /** @test */
    function it_has_hmac_sha1_signer()
    {
        $this->assertInstanceOf(HmacSha1Signer::class, $this->upwork->getSigner());
    }
}

Add test for upwork provider.

:white_check_mark: Add test for upwork provider.


<?php

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

namespace Surfnet\Stepup\Configuration\Api;

use Surfnet\Stepup\Configuration\Value\Institution;

interface InstitutionConfigurationCreationService
{
    /**
     * @param Institution $institution
     * @return void
     */
    public function createConfigurationFor(Institution $institution);
}

Introduce service for creating institution configuration concept


<?php
declare(strict_types=1);
namespace CondorcetPHP\Condorcet\DataManager;

use PHPUnit\Framework\TestCase;

use CondorcetPHP\Condorcet\DataManager\ArrayManager;

class ArrayManagerTest extends TestCase
{
    private ArrayManager $ArrayManager;

    protected function setUp() : void
    {
        $this->ArrayManager = new class extends ArrayManager {
            protected function preDeletedTask ($object) : void {}
            public function getDataContextObject () : DataContextInterface {}
        };
    }

    public function testOffsetSetAndOffetsetGet () : void
    {
        self::assertNull($this->ArrayManager->key());

        $this->ArrayManager[42] = 'foo';

        self::assertSame('foo', $this->ArrayManager[42]);

        self::assertNull($this->ArrayManager[43]);
    }
}

Include some tests for abstract class ArrayManager for method not used in VoteManager extension used by Condorcet.


<?php
/*
 * SolusVM_ServiceSingleSignOn
 *
 * Perform single sign-on for a given instance of a product/service in this case VPS to the SolusVM control panel
 *
 * @package		SolusVM
 * @category	WHMCS Provisioning Modules
 * @author		Trajche Petrov
 * @link		https://qbit.solutions/
*/
	class SolusVM_ServiceSingleSignOn extends SolusVM
	{
		function _exec()
		{
			// check if the VPS is into the module database
			if($this->input['vm_id'])
			{
				// try to fetch client login keys
				$login = $this->_api(array
				(
					'action' 	=> 'client-key-login',
					'vserverid' => $this->input['vm_id'],
					'forward'	=> 1
				));

				if($login->status == 'success')
				{
					// set autologin redirect URL
					$url = $this->__set_redirect_url( $login );

					return array // send redirect result to WHMCS
					(
						'success' => true,
						'redirectTo' => $url
					);
				}
				elseif(!is_object($login) or !isset($login))
					return array('success' => false, 'errorMsg' => 'Some API transport error occured please check module debug log!');
				else
					return array('success' => false, 'errorMsg' => $login->statusmsg);
			}
			else
				return array('success' => false, 'errorMsg' => 'Can\'t find VPS ID into module database');
		}

/*
 * ---------------------------------------------------------------------------------------------------------------------
 *  Generate redirect URl
 * ---------------------------------------------------------------------------------------------------------------------
*/
		private function __set_redirect_url( $LOGIN )
		{
			$master = $this->_get_master_url(); // get master location

			return $master.'/auth.php?_a='.$LOGIN->hasha.'&_b='.$LOGIN->hashb;
		}
	}

Add single Sign-On feature for services and products. It automatically logs in the users on SolusVM control panel.


<?php

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

class AddIndexToKudosuHistoriesKudosuable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('osu_kudos_exchange', function ($table) {
            $table->index(['kudosuable_type', 'kudosuable_id']);
        });
    }

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

Add index to kudosu histories table

Add index to kudosu histories table


<?php

class Default_View_Helper_Sort extends Zend_View_Helper_Abstract
{
	public function sort($label, $column, $sort, $sortOrder)
	{
		$orders = array('desc' => 'asc', 'asc' => 'desc');
		if (!in_array($sortOrder, $orders)) $sortOrder = reset($orders);

		$url = $this->view->url(array('sort' => $column, 'sortOrder' => $orders[$sortOrder]));
		$result = 'view->escape($this->view->translate('Sort by "%s"', array($label))) . '" href="' . $url . '">' . $label . '';

		return $result;
	}
}

?>

FIX forgot a file !

FIX forgot a file !


<?php

include('vendor/autoload.php');

echo "Requesting XML ranges file...\n";

$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://www.isbn-international.org/?q=bl_proxy/GetRangeInformations', [
    'form_params' => [
        'format' => 1,
        'language' => 'en',
        'translatedTexts' => 'Printed;Last Change'
    ]
]);

echo $res->getBody();

echo $res->getStatusCode();

Add a PHP cli script to get range file adress from isbn authority


<?php

namespace Marein\Nchan\Http;

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

class ThrowExceptionIfRequestRequiresAuthenticationClientTest extends TestCase
{
    /**
     * @test
     */
    public function itShouldThrowExceptionOnForbiddenGetRequest(): void
    {
        $this->expectException(AuthenticationRequiredException::class);

        $client = new ThrowExceptionIfRequestRequiresAuthenticationClient(
            $this->createForbiddenClient()
        );

        $client->get(new Request('http://localhost', []));
    }

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

        $client = new ThrowExceptionIfRequestRequiresAuthenticationClient(
            $this->createForbiddenClient()
        );

        $client->post(new Request('http://localhost', []));
    }

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

        $client = new ThrowExceptionIfRequestRequiresAuthenticationClient(
            $this->createForbiddenClient()
        );

        $client->delete(new Request('http://localhost', []));
    }

    /**
     * @return Client
     */
    private function createForbiddenClient(): Client
    {
        return new class implements Client
        {
            public function get(Request $request): Response
            {
                return $this->createForbiddenResponse();
            }

            public function post(Request $request): Response
            {
                return $this->createForbiddenResponse();
            }

            public function delete(Request $request): Response
            {
                return $this->createForbiddenResponse();
            }

            private function createForbiddenResponse(): Response
            {
                return new class implements Response
                {
                    public function statusCode(): int
                    {
                        return Response::FORBIDDEN;
                    }

                    public function body(): string
                    {
                        return '';
                    }
                };
            }
        };
    }
}

Add unit test for ThrowExceptionIfRequestRequiresAuthenticationClient


<?php
	#
	# $Id: password-reset-via-token.php,v 1.1 2010-09-17 14:44:55 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	if (IsSet($_REQUEST["origin"])) $origin = $_REQUEST["origin"];
	GLOBAL $numberofdays;
	GLOBAL $page_size;
?>

<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=" . $origin ?>" method="POST" NAME=f>

              <INPUT TYPE="hidden" NAME="token" VALUE="<?php echo $token ?>">
               Password:

               <INPUT TYPE="PASSWORD" NAME="Password1" VALUE="<?php if (IsSet($Password1)) echo htmlentities($Password1) ?>" size="20">

               Confirm Password:

               <INPUT TYPE="PASSWORD" NAME="Password2" VALUE="<?php if (IsSet($Password2)) echo htmlentities($Password2) ?>" size="20">

            <INPUT TYPE="submit" VALUE="Set password" NAME="submit">

</FORM>

Add form for forgotten passwords

Add form for forgotten passwords

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


<?php

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

/**
 * Class CreateLaralyticsInfoTable
 */
class CreateLaralyticsInfoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('laralytics_info', function (Blueprint $table) {

            $engine = Config::get('database.default');

            $table->increments('id');
            $table->integer('user_id')->index()->nullable();
            $table->string('version');
            $table->string('session', 250);
            $table->string('browser');
            $table->integer('browser_width');
            $table->integer('browser_height');
            $table->integer('device_width');
            $table->integer('device_height');

            // Auto timestamp for postgreSQL and others
            if ($engine === 'pgsql') {
                $table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'));
            } else {
                $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            }
        });
    }

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

Create migration for laralytics_info table


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

namespace Zend\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;

class ViewResolverFactory implements FactoryInterface
{
    /**
     * Create the aggregate view resolver
     *
     * Creates a Zend\View\Resolver\AggregateResolver and attaches the template
     * map resolver and path stack resolver
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return ViewResolver\AggregateResolver
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $resolver = new ViewResolver\AggregateResolver();
        $resolver->attach($serviceLocator->get('ViewTemplateMapResolver'));
        $resolver->attach($serviceLocator->get('ViewTemplatePathStack'));
        return $resolver;
    }
}

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

namespace Zend\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;

class ViewResolverFactory implements FactoryInterface
{
    /**
     * Create the aggregate view resolver
     *
     * Creates a Zend\View\Resolver\AggregateResolver and attaches the template
     * map resolver and path stack resolver
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return ViewResolver\AggregateResolver
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $resolver = new ViewResolver\AggregateResolver();
        $resolver->attach(new ViewResolver\RelativeFallbackResolver($serviceLocator->get('ViewTemplateMapResolver')));
        $resolver->attach(new ViewResolver\RelativeFallbackResolver($serviceLocator->get('ViewTemplatePathStack')));
        return $resolver;
    }
}

Move logic to new RelativeFallbackResolver


<?php

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

class AddActiveToEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('events', function (Blueprint $table) {
            $table->boolean('active')->default(false);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('events', function (Blueprint $table) {
            //
        });
    }
}

Add migration for adding 'active' column in events table


<?php

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

class ChangeDescModelSizeInMachinesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('machines', function (Blueprint $table) {
            $table->string('model', 100)->change();
            $table->string('description', 100)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('machines', function (Blueprint $table) {
            $table->string('model', 50)->change();
            $table->string('description', 60)->change();
        });
    }
}

Change size of description, model in machines table


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
function fetch_menu($menu_type='user') {

    $menulst = array();
    $CI = & get_instance();
    $table = 'menu';
    $sess_data = $CI->session->userdata();
    $sql =  $CI->db->select("menuid,menuname,menuurl,menuparent")
                   ->from($table)
                   ->where('menustatus',1)
                   ->where("menuaccess",$menu_type)
                   ->order_by('menuposition')
                   ->get();
    $res = $sql->result_array();
    $i = 0;
    foreach($res as $k => $val){
        if($val['menuparent'] == 0){
            $menulst[$val['menuid']]['menuname'] = $val['menuname'];
            $menulst[$val['menuid']]['menuurl'] = $val['menuurl'];
            if(!isset($menulst[$val['menuid']]['child'])){
                $menulst[$val['menuid']]['child'] = array();
            }
        }else{
            if(!isset($menulst[$val['menuparent']])) {
                $menulst[$val['menuparent']] = array();
            }
            $menulst[$val['menuparent']]['child'][$val['menuid']]['menuname'] = $val['menuname'];
            $menulst[$val['menuparent']]['child'][$val['menuid']]['menuurl']  = $val['menuurl'];
        }
    }
    return $menulst;
}

Add:
Add new menu details and other login page views