<?php

namespace AppBundle\Form;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName');
    }

    public function getParent()
    {
        return BaseRegistrationFormType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('csrf_protection', false);
    }
}

Extend form for editing user profile

Extend form for editing user profile


<?php
/**
 * Copyright (c) 2017, Nosto Solutions Ltd
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author Nosto Solutions Ltd <contact@nosto.com>
 * @copyright 2017 Nosto Solutions Ltd
 * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause
 *
 */

namespace Nosto\Operation;

use Nosto\NostoException;
use Nosto\Request\Api\ApiRequest;
use Nosto\Request\Api\Token;
use Nosto\Request\Http\Exception\AbstractHttpException;

/**
 * Operation class for upserting and deleting products through the Nosto API.
 * A product upsert will create the product if it doesn't exist or update it if
 * it does, while a product delete also results in an upsert but flags the
 * product's availability as 'Discontinued'
 */
class DeleteProduct extends AbstractAccountOperation
{
    /**
     * @var array
     */
    private $productIds;

    /**
     * Adds a product tho the collection on which the operation is the performed.
     *
     * @param array $productIds
     */
    public function setProductIds(array $productIds)
    {
        $this->productIds = $productIds;
    }

    /**
     * Sends a POST request to create or update all the products currently in the collection.
     *
     * @return bool if the request was successful.
     * @throws NostoException on failure.
     * @throws AbstractHttpException
     */
    public function delete()
    {
        $request = $this->initApiRequest($this->account->getApiToken(Token::API_PRODUCTS));
        $request->setPath(ApiRequest::PATH_PRODUCTS_DISCONTINUE);
        $response = $request->post($this->productIds);
        return $this->checkResponse($request, $response);
    }
}

Add delete operation for product

Add delete operation for product


<?php

namespace Tests\AppBundle\API\Mapping;

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

class ByOrganismNameTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $service = $this->webservice->factory('mapping', 'byOrganismName');

        // Test with existing IDs
        $names = [
            'Galactites tomentosa',
            'Austrolejeunea bidentata',
            'Melilotus infestus',
            'Cyclogramma sp. 73',
            'Willkommia'
        ];
        $expected = [
            'Galactites tomentosa' => 505,
            'Austrolejeunea bidentata' => 1337,
            'Melilotus infestus' => 1564,
            'Cyclogramma sp. 73' => 1559,
            'Willkommia' => 1727
        ];
        $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db, 'names' => $names)),
            null);
        $this->assertEquals($expected, $result);

        // Test with some non-existing IDs
        $names = [
            'Galactites tomentosa',
            'Austrolejeunea bidentata',
            'Melilotus infestus',
            'Cyclogramma sp. 73',
            'Willkommia',
            'non_existing'
        ];
        $expected = [
            'Galactites tomentosa' => 505,
            'Austrolejeunea bidentata' => 1337,
            'Melilotus infestus' => 1564,
            'Cyclogramma sp. 73' => 1559,
            'Willkommia' => 1727,
            'non_existing' => null
        ];
        $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db, 'names' => $names)),
            null);
        $this->assertEquals($expected, $result);
    }
}

Add test for mapping byOrganismName

Add test for mapping byOrganismName


<?php

namespace Api\Library\Shared\Script\Migration;

use Api\Model\ProjectModel;
use Api\Model\ProjectListModel;
use Api\Model\Shared\Rights\ProjectRoles;

(php_sapi_name() == 'cli') or die('this script must be run on the command-line');

require_once('../scriptConfig.php');

class FixProjectOwnerRole
{
    public static function run($mode = 'test')
    {
        $testMode = ($mode != 'run');
        print("Fix project_owner role\n");

        $projectList = new ProjectListModel();
        $projectList->read();
        $totalProjectCount = $projectList->count;

        $ownerRoleUpdated = 0;
        $projectCount = 0;
        $skippedProjects = 0;
        foreach ($projectList->entries as $projectParams) {
            $projectId = $projectParams['id'];
            $project = new ProjectModelForUseWithProjectOwnerRoleMigration($projectId);
            if ($project->ownerRef->id == "") {
                print("Project owner for $project->projectName undefined.  Skipping\n");
                $skippedProjects++;
            } else if (!$project->hasHadProjectOwnerRoleMigrated) {
                print("-------------  $project->projectName.\n");
                self::analyzeProject($project, $projectId, $testMode);
                $projectCount++;
                $ownerRoleUpdated++;
            } else {
                print("\nSkipping $project->projectName: already migrated\n");
                $skippedProjects++;
            }

            unset($project);
            if ($projectCount >= $totalProjectCount) {
                print("\nProcessed projects " . ($skippedProjects + 1) . " - " .
                    ($skippedProjects + $projectCount) . " of $totalProjectCount projects\n");
                break;
            }
        }
        if ($skippedProjects > 0) {
            print("Skipped $skippedProjects projects\n");
        }
        print("$ownerRoleUpdated projects had project_owner role migrated\n");
    }

    /**
     * Analyze a project: assign project owner role.
     * @param ProjectModelForUseWithProjectOwnerRoleMigration $project
     * @param string $projectId
     * @param string $testMode
     */
    private static function analyzeProject($project, $projectId, $testMode)
    {
        $ownerId = $project->ownerRef->id;
        $usersArray = $project->users->getArrayCopy();
        if ($project->userIsMember($ownerId) && ($usersArray[$ownerId]->role != ProjectRoles::OWNER)) {
            $project->addUser($ownerId, ProjectRoles::OWNER);
        }

        if (!$testMode) {
            $project->hasHadProjectOwnerRoleMigrated = true;
            $project->write();
        }
    }
}

/**
 * Class ProjectModelForUseWithProjectOwnerRoleMigration
 * Has a flag to store in Mongo about whether the project owner role has been migrated
 * @package Api\Library\Shared\Script\Migration
 */
class ProjectModelForUseWithProjectOwnerRoleMigration extends ProjectModel {
    public $hasHadProjectOwnerRoleMigrated;
}

FixProjectOwnerRole::run('run');

Add migration script to assign project owner


<?php

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

class CreateSchedulesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedules', function (Blueprint $table) {
            $table->increments('id');
            $table->date('run_at'); // date when to be run
            $table->string('action'); // action class name
            $table->string('who_object'); // eg. company
            $table->integer('who_id'); // 3 = company Id
            $table->json('parameters'); // parameters to run action class with
            $table->enum('status', ['done', 'in_progress', 'new'])->default('new');
            $table->string('last_message'); // useful if error ocured
            $table->dateTime('started_at')->nullable();
            $table->dateTime('finished_at')->nullable();
            $table->timestamps();
        });
    }

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

Add migration - create schedules table

Add migration - create schedules table


<?php

namespace TijsVerkoyen\Bpost;

use Psr\Log\LoggerInterface;

class Logger
{
    /** @var  LoggerInterface */
    private $logger;

    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function debug($message, array $context = array())
    {
        if ($this->logger) {
            $this->logger->debug($message, $context);
        }
    }

}

Add logger, using psr/log interface

refactor: Add logger, using psr/log interface


<?php

namespace ApplicationMigrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20140513113258 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('CREATE TABLE tblfeeds (
            feedId integer auto_increment NOT NULL,
            feedDateTime DATETIME NULL,
            feedAmount int NOT NULL,
            feedNotes TEXT NULL,
            feedTemperature FLOAT (5,2) NULL,
            userId integer NOT NULL,
            created timestamp,
            updated timestamp,
            PRIMARY KEY (feedId)
        )');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->addSql('DROP TABLE tblfeeds');
    }
}

Add a migration for the feeds table

Add a migration for the feeds table


<?php

namespace Ice\UsernameGeneratorBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ice_username_generator');

        $rootNode
            ->children()
            ->scalarNode('username_format')
            ->defaultValue('%s@ice')
            ->info('A printf formatted string with a single %s placeholder.')
            ->end()
            ->scalarNode('sequence_start')
            ->validate()
            ->ifTrue(function ($v) {
            return !is_int($v);
        })
            ->thenInvalid('Must be an integer but %s found.')
            ->end()
            ->defaultValue(1)
            ->info('The lowest number that will be appended to the User\'s initials to form their username.')
            ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Ice\UsernameGeneratorBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ice_username_generator');

        $rootNode
            ->children()
            ->scalarNode('username_format')
            ->defaultValue('%s')
            ->info('A printf formatted string with a single %s placeholder.')
            ->end()
            ->scalarNode('sequence_start')
            ->validate()
            ->ifTrue(function ($v) {
            return !is_int($v);
        })
            ->thenInvalid('Must be an integer but %s found.')
            ->end()
            ->defaultValue(1)
            ->info('The lowest number that will be appended to the User\'s initials to form their username.')
            ->end()
            ->end();

        return $treeBuilder;
    }
}

Set default UsernameGenerator username format to %s to work with the current routing requirements. Both will need updating when the format is agreed.


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

use Tlumx\Log\Writer\File as FileWrite;

class FileTest extends \PHPUnit_Framework_TestCase
{
    protected $logDir;

    public function setUp()
    {
        $this->logDir = @tempnam(sys_get_temp_dir(), 'tlumxframework_tmp_log');
        if (!$this->logDir) {
            $e = error_get_last();
            $this->fail("Can't create temporary log directory-file: {$e['message']}");
        } elseif (!@unlink($this->logDir)) {
            $e = error_get_last();
            $this->fail("Can't remove temporary log directory-file: {$e['message']}");
        } elseif (!@mkdir($this->logDir, 0777)) {
            $e = error_get_last();
            $this->fail("Can't create temporary log directory: {$e['message']}");
        }
    }

    public function tearDown()
    {
        testRemoveDirTree($this->logDir);
    }

    public function testImplements()
    {
        $writer = new FileWrite($this->logDir);
        $this->assertInstanceOf('Tlumx\Log\Writer\WriterInterface', $writer);
    }

    /**
     * @expectedException Exception
     */
    public function testInvalidDir()
    {
        $log = new FileWrite('some_invalid_dir');
    }

    public function testLogFileWrite()
    {
        $writer = new FileWrite($this->logDir);

        $datetime = new \DateTime();
        $writer->write([
            [$datetime, 'error', 500, 'some message']
        ]);

        $filename = $this->logDir.DIRECTORY_SEPARATOR.date('Y-m-d').'.log';
        $this->assertTrue(file_exists($filename));

        $lines = file($filename);
        $lastLine = $lines[count($lines) - 1];
        $timestamp = $datetime->format('c');
        $actual = "[$timestamp] error (500): some message".PHP_EOL;

        $this->assertEquals($lastLine, $actual);

        $writer->write([
            [$datetime, 'error', 400, 'some2 message']
        ]);

        $lines = file($filename);
        $lastLine = $lines[count($lines) - 1];
        $actual = "[$timestamp] error (400): some2 message".PHP_EOL;

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

Add tests for FileWriter Logger

Add tests for FileWriter Logger


<?php

class Stripe_TransferTest extends Stripe_TestCase
{
  public function testCreate()
  {
    $recipient = self::createTestRecipient();

    self::authorizeFromEnv();
    $transfer = Stripe_Transfer::create(
        array(
          'amount' => 100,
          'currency' => 'usd',
          'recipient' => $recipient->id
        )
    );
    $this->assertSame('pending', $transfer->status);
  }

  public function testRetrieve()
  {
    $recipient = self::createTestRecipient();

    self::authorizeFromEnv();
    $transfer = Stripe_Transfer::create(
        array(
          'amount' => 100,
          'currency' => 'usd',
          'recipient' => $recipient->id
        )
    );
    $reloaded = Stripe_Transfer::retrieve($transfer->id);
    $this->assertSame($reloaded->id, $transfer->id);
  }

  /**
   * @expectedException Stripe_InvalidRequestError
   */
  public function testCancel()
  {
    $recipient = self::createTestRecipient();

    self::authorizeFromEnv();
    $transfer = Stripe_Transfer::create(
        array(
          'amount' => 100,
          'currency' => 'usd',
          'recipient' => $recipient->id
        )
    );
    $reloaded = Stripe_Transfer::retrieve($transfer->id);
    $this->assertSame($reloaded->id, $transfer->id);

    $reloaded->cancel();
  }

  public function testTransferUpdateMetadata()
  {
    $recipient = self::createTestRecipient();

    self::authorizeFromEnv();
    $transfer = Stripe_Transfer::create(
        array(
            'amount' => 100,
            'currency' => 'usd',
            'recipient' => $recipient->id
        )
    );

    $transfer->metadata['test'] = 'foo bar';
    $transfer->save();

    $updatedTransfer = Stripe_Transfer::retrieve($transfer->id);
    $this->assertSame('foo bar', $updatedTransfer->metadata['test']);
  }

  public function testTransferUpdateMetadataAll()
  {
    $recipient = self::createTestRecipient();

    self::authorizeFromEnv();
    $transfer = Stripe_Transfer::create(
        array(
          'amount' => 100,
          'currency' => 'usd',
          'recipient' => $recipient->id
        )
    );

    $transfer->metadata = array('test' => 'foo bar');
    $transfer->save();

    $updatedTransfer = Stripe_Transfer::retrieve($transfer->id);
    $this->assertSame('foo bar', $updatedTransfer->metadata['test']);
  }

  public function testRecipientUpdateMetadata()
  {
    $recipient = self::createTestRecipient();

    $recipient->metadata['test'] = 'foo bar';
    $recipient->save();

    $updatedRecipient = Stripe_Recipient::retrieve($recipient->id);
    $this->assertSame('foo bar', $updatedRecipient->metadata['test']);
  }

  public function testRecipientUpdateMetadataAll()
  {
    $recipient = self::createTestRecipient();

    $recipient->metadata = array('test' => 'foo bar');
    $recipient->save();

    $updatedRecipient = Stripe_Recipient::retrieve($recipient->id);
    $this->assertSame('foo bar', $updatedRecipient->metadata['test']);
  }
}

Add PHPUnit test for Stripe_Transfer

Add PHPUnit test for Stripe_Transfer


<?php
/**
 * Go! AOP framework
 *
 * @copyright Copyright 2011, Lisachenko Alexander <lisachenko.it@gmail.com>
 *
 * This source file is subject to the license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Go\Aop\Framework;

use Go\Core\AspectContainer;
use ReflectionClass;

/**
 * Static initialization joinpoint is invoked after class is loaded into memory
 */
class StaticInitializationJoinpoint extends AbstractJoinpoint
{

    /**
     * @var ReflectionClass
     */
    protected $reflectionClass;

    /**
     * Constructor for static initialization joinpoint
     *
     * @param string $className Name of the class
     * @param string $type Type of joinpoint
     * @param $advices array List of advices for this invocation
     *
     * @internal param ReflectionClass $reflectionClass Reflection of class
     */
    public function __construct($className, $type, array $advices)
    {
        if (strpos($className, AspectContainer::AOP_PROXIED_SUFFIX)) {
            $originalClass = substr($className, 0, -strlen(AspectContainer::AOP_PROXIED_SUFFIX));
        } else {
            $originalClass = $className;
        }
        $this->reflectionClass = new \ReflectionClass($originalClass);
        parent::__construct($advices);
    }

    /**
     * Proceeds to the next interceptor in the chain.
     *
     * @return mixed see the children interfaces' proceed definition.
     */
    public function proceed()
    {
        if (isset($this->advices[$this->current])) {
            $currentInterceptor = $this->advices[$this->current++];
            $currentInterceptor->invoke($this);
        }
    }

    /**
     * Invokes current joinpoint with all interceptors
     *
     * @return mixed
     */
    final public function __invoke()
    {
        $this->current = 0;

        return $this->proceed();
    }

    /**
     * Returns the object that holds the current joinpoint's static
     * part.
     *
     * @return object|null the object (can be null if the accessible object is
     * static).
     */
    public function getThis()
    {
        return null;
    }

    /**
     * Returns the static part of this joinpoint.
     *
     * @return ReflectionClass
     */
    public function getStaticPart()
    {
        return $this->reflectionClass;
    }

    /**
     * Returns a friendly description of current joinpoint
     *
     * @return string
     */
    final public function __toString()
    {
        return sprintf(
            "staticinitialization(%s)",
            $this->reflectionClass->getName()
        );
    }
}

Add a joinpoint class for static initalization


<?php

include_once(dirname(__FILE__).'/../../connector.php');
include_once(dirname(__FILE__).'/../../schema.php');

class Metrodb_Tests_Integration_Schema extends PHPUnit_Framework_TestCase {

	public function setUp() {
	}

	public function test_get_missing_columns_works() {
		$s = new Metrodb_Schema('sqlite3', new Metrodb_Schemasqlite3());

		$di         = new Metrodb_Dataitem('foobar');
		$tableDef   = ['table'=>'foobar', 'fields'=>[
			['name'=>'old_column']
		]];
		$di->old_column = 'foo';
		$di->new_column = 'bar';
		$di->nul_column = 'baz';
		$di->_typeMap['new_column'] = 'lob';
		#should correctly choose string when no type specified
		#$di->_typeMap['nul_column'] = 'string';

		$columnList = $s->getMissingColumns($tableDef, $di);

		$this->assertEquals(
			[[
				'name' => 'new_column',
				'type' => 'longblob',
				'len'  => '',
				'us'   => 0,
				'pk'   => 0,
				'def'  => 'NULL',
				'null' => true,
			],
			[
				'name' => 'nul_column',
				'type' => 'varchar',
				'len'  => '255',
				'us'   => 0,
				'pk'   => 0,
				'def'  => 'NULL',
				'null' => true,
			]],
			$columnList
		);
	}
}

Add test for missing columns

Add test for missing columns


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Cache;

use Psr\Cache\CacheItemPoolInterface as CacheItemPool;
use Psr\Cache\CacheItemInterface as CacheItem;

/**
 * Wraps a {@see Psr\Cache\CacheItemPoolInterface} with additional features.
 */
class WrapperPool extends PoolBase {
  /**
   * @var CacheItemPool
   */
  private $pool;

  /**
   * Construct wrapper.
   * @param CacheItemPool $pool Cache pool.
   */
  public function __construct(CacheItemPool $pool) {
    $this->pool = $pool;
  }

  /**
   * {@inheritdoc}
   */
  public function getItem($key) {
    return $this->pool->getItem($key);
  }

  /**
   * {@inheritdoc}
   */
  public function getItems(array $keys = array()) {
    return $this->pool->getItem($keys);
  }

  /**
   * {@inheritdoc}
   */
  public function clear() {
    return $this->pool->clear();
  }

  /**
   * {@inheritdoc}
   */
  public function deleteItems(array $keys) {
    $this->pool->deleteItems($keys);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function save(CacheItem $item) {
    $this->pool->save($item);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function saveDeferred(CacheItem $item) {
    $this->pool->saveDeferred($item);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function commit() {
    $this->pool->commit();
    return $this;
  }
}

Add wrapper for imaginary CacheItemPoolInterface implementations.


<?php namespace Cerbero\Workflow\Scaffolding\Generators;

/**
 * Bindings file generator which can nest unlimited decorators.
 *
 * @author	Andrea Marco Sartori
 */
class ManyBindingsGenerator extends BindingsGenerator
{

	const NESTING_PER_DECORATOR = 8;

	/**
	 * @author	Andrea Marco Sartori
	 * @var		int	$oldLimit	Initial maximum number of function nesting.
	 */
	private $oldLimit;

	/**
	 * Generate the scaffolding files.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	array	$data
	 * @return	boolean
	 */
	public function generate(array $data)
	{
		$this->increaseFunctionNesting($data['decorators']);

		$success = parent::generate($data);

		$this->resetFunctionNesting();

		return $success;
	}

	/**
	 * Increase the maximum number of function nesting depending on the number of decorators.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	array	$decorators
	 * @return	void
	 */
	private function increaseFunctionNesting($decorators)
	{
		$limit = count($decorators) * self::NESTING_PER_DECORATOR;

		if($limit > ini_get('xdebug.max_nesting_level'))
		{
			$this->oldLimit = ini_set('xdebug.max_nesting_level', $limit);
		}
	}

	/**
	 * Reset the maximum number of function nesting.
	 *
	 * @author	Andrea Marco Sartori
	 * @return	void
	 */
	private function resetFunctionNesting()
	{
		if($limit = $this->oldLimit)
		{
			ini_set('xdebug.max_nesting_level', $limit);
		}
	}

}

Add the generator for many bindings

Add the generator for many bindings


<?php

namespace Criterion\Test;

class GithubHelperTest extends TestCase
{

    public function testSSHUrl()
    {
        $url = 'https://github.com/romhut/api';
        $new_url = \Criterion\Helper\Github::toSSHUrl($url);
        $this->assertEquals($new_url, 'git@github.com:romhut/api');
    }

}

Add a test for GithubHelper

Add a test for GithubHelper


<?php

class SettlerController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index($idUser)
	{
	    $user = User::find($idUser);

	    if ($user) {
	        return Response::json($user->settlers, 200);
	    }

	    return Response::json([
	        'flash'     => "Erreur",
	        'dev_error' => sprintf('User not found with idUser = %d', $idUser)
	    ], 400);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create($idUser)
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store($idUser)
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($idUser, $id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($idUser, $id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($idUser, $id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($idUser, $id)
	{
		//
	}

}

structure(controller): Add Settler controller to retrieve them on dashboard


<?php
/**
 * Gigaom_Sniffs_CodeAnalysis_RedirectAndDieSniff
 *
 * Throw an error if error loggins functions are in use
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Matthew Batchelder <borkweb@gmail.com>
 * @copyright 2014 Gigaom
 * @license   https://github.com/GigaOM/gigaom-codesniffer/blob/master/licence.txt BSD Licence
 * @version   Release: 1.4.0
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Gigaom_Sniffs_CodeAnalysis_RedirectAndDieSniff implements PHP_CodeSniffer_Sniff
{
	/**
	 * A list of tokenizers this sniff supports.
	 *
	 * @var array
	 */
	public $supportedTokenizers = array(
		'PHP',
	);

	/**
	 * Returns an array of tokens this test wants to listen for.
	 *
	 * @return array
	 */
	public function register()
	{
		return array(
			T_STRING,
		);
	}//end register

	/**
	 * Processes this test, when one of its tokens is encountered.
	 *
	 * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
	 * @param int                  $stackPtr  The position of the current token in
	 *                                        the stack passed in $tokens.
	 *
	 * @return void
	 */
	public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr )
	{
		$tokens = $phpcsFile->getTokens();
		$token = $tokens[ $stackPtr ];
		$function = strtolower( $token['content'] );

		$ignore = array(
			T_DOUBLE_COLON,
			T_OBJECT_OPERATOR,
			T_FUNCTION,
			T_CONST,
		);

		$prevToken = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true );

		if ( in_array( $tokens[ $prevToken ]['code'], $ignore ) === true )
		{
			// Not a call to a PHP function.
			return;
		}//end if

		if ( ! in_array( $function, array( 'wp_redirect', 'wp_safe_redirect' ) ) )
		{
			return;
		}//end if

		$semicolon = $phpcsFile->findNext( T_SEMICOLON, $stackPtr );
		$next = $tokens[ $phpcsFile->findNext( T_WHITESPACE, $semicolon + 1, NULL, TRUE ) ];

		if ( T_EXIT == $next['code'] )
		{
			return;
		}//end if

		$data = array( $function );
		$type  = 'Error';
		$error = "die must follow {$function}";
		$phpcsFile->addError( $error, $stackPtr, $type, $data );
	}//end process
}//end class

Add a sniff for requiring die/exit after wp(_safe)_redirect


<?php

namespace duncan3dc\Sonos;

/**
 * Represents a shared directory.
 */
class Directory
{
    /**
     * @var string $filesystem The full path to the share on the local filesystem.
     */
    protected $filesystem;

    /**
     * @var string $share The full path to the share (including the hostname).
     */
    protected $share;

    /**
     * @var string $directory The name of the directory (to be appended to both $filesystem and $share).
     */
    protected $directory;

    /**
     * Create a Directory instance to represent a file share.
     *
     * @param string $filesystem The full path to the share on the local filesystem.
     * @param string $share The full path to the share (including the hostname).
     * @param string $directory The name of the directory (to be appended to both $filesystem and $share).
     */
    public function __construct($filesystem, $share, $directory)
    {
        $filesystem = rtrim($filesystem, "/");
        if (!is_dir($filesystem)) {
            throw new \InvalidArgumentException("Invalid directory: {$filesystem}");
        }

        $this->filesystem = $filesystem;
        $this->share = rtrim($share, "/");
        $this->directory = trim($directory, "/");
    }

    /**
     * Get the full path to the directory on the file share.
     *
     * @return string
     */
    public function getSharePath()
    {
        return "{$this->share}/{$this->directory}";
    }

    /**
     * Get the full path to the directory on the local filesystem.
     *
     * @return string
     */
    public function getFilesystemPath()
    {
        return "{$this->filesystem}/{$this->directory}";
    }
}

Create a class to represent a file share directory


<?php

namespace OnlyBits\Inputs;

use OnlyBits\Inputs\IInput;
use OnlyBits\Connectors\IConnect;
use OnlyBits\Connectors\Wire;

class TwoStateButton implements IInput, IConnect
{
    /**
     * Button state 1.
     * @var mixed
     */
    private $state1;

    /**
     * Button state 2.
     * @var mixed
     */
    private $state2;

    /**
     * Button's current state.
     * @var mixed
     */
    private $current_state;

    /**
     * The value outputted by the button.
     * @var mixed
     */
    private $output;

    /**
     * Constructor. The state 1 should be default state.
     *
     * @param mixed $state1 Button state 1
     * @param mixed $state2 Button state 2
     */
    public function __construct($state1, $state2)
    {
        $this->state1 = $state1;
        $this->state2 = $state2;

        $this->current_state = $state1;
        $this->output = $state1;
    }

    /**
     * {@inheritdoc}
     */
    public function trigger()
    {
        $this->current_state = ($this->current_state == $state1) ? $state2 : $state1;

        $this->output = $this->current_state;
    }

    /**
     * {@inheritdoc}
     */
    public function connect(Wire $wire, $pin = null)
    {
        $wire->setValue($this->output);

        return $wire;
    }
}

Create two state button input.

Create two state button input.


<?php
/**
 * PWEB WP Theme framework
 *
 * @package    PWEB WP Theme framework
 *
 * @version    1.0
 * @author     Louis-Michel Raynauld
 * @copyright  Louis-Michel Raynauld
 * @link       http://graphem.ca
 */
namespace pweb\wp_core;

/**
 *
 * @package     pweb
 * @subpackage  wp_core
 */

class WPtaxonomy implements WPaction
{
  protected $slug;
  protected $type;
  protected $args;

  public function __construct($slug , $type, $args = array() )
  {
    $this->slug = $slug;
    $this->type = $type;

    $defaults = array(
//           'label' => __( 'People' ),
//       'rewrite' => array( 'slug' => 'person' ),
//       'capabilities' => array(
//         'assign_terms' => 'edit_guides',
//         'edit_terms' => 'publish_guides'
//               )
//       )
      );
    $this->args = wp_parse_args($args, $defaults);

  }

  public function init()
  {
      register_taxonomy( $this->slug, $this->type, $this->args);
  }

  public function getSlug()
  {
    return $this->slug;
  }

  public function getType()
  {
    return $this->type;
  }
  public function register()
  {
    add_action('init', array($this, 'init'));
  }

  public function remove()
  {
    remove_action('init', array($this, 'init'));
  }
}

Add custom taxonomy and fix bug in sidebar


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('process tweets looking for beers');
$I->runShellCommand('php artisan nerds:process test');
$I->seeInShellOutput('We should have tweeted:');

Add test for nerds:process command

Add test for nerds:process command


<?php

class AMP_KSES_Test extends WP_UnitTestCase {
	function test_strip_empty() {
		$source = '';
		$expected = '';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}

	function test_strip_blacklisted_tags_only() {
		$source = '<input type="text" />';
		$expected = '';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}

	function test_strip_whitelisted_tags_only() {
		$source = '
Text
';
		$expected = '
Text
';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}

	function test_strip_mixed_tags() {
		$source = '<input type="text" />
Text
';
		$expected = '
Text
';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}

	function test_strip_on_attribute() {
		$source = '';
		$expected = '';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}

	function test_strip_javascript_protocol() {
		$source = 'Click';
		$expected = 'Click';
		$content = AMP_KSES::strip( $source );
		$this->assertEquals( $expected, $content );
	}
}

Add some tests for kses

Add some tests for kses


<?php

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

class AddIndexToNetxUuidOnAssets extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // TODO: Creating indexes isn't friendly with SQLite
        if (App::environment('testing')) {
            return;
        }

        Schema::table('assets', function (Blueprint $table) {
            $table->index('netx_uuid');
        });
    }

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

Add index to `netx_uuid` on `assets`

Add index to `netx_uuid` on `assets` [WEB-1892]


<?php
/**
 * Plugin Name: Restrict Content Pro - Registration Fees on Renewals
 * Description: Charge registration fees on manual renewals.
 * Version: 1.0
 * Author: Sandhills Development, LLC
 * Author URI: https://sandhillsdev.com
 * License: GPL2
 */

/**
 * Always add signup fees, regardless of registration type.
 *
 * By default signup fees are NOT applied to manual renewal payments. This code changes that
 * so signup fees are always added, even if it's a manual renewal.
 *
 * @param bool             $add_fee          Whether or not to add signup fees.
 * @param object           $membership_level Membership level object.
 * @param RCP_Registration $registration     Registration object.
 *
 * @return bool
 */
function ag_rcp_always_apply_fees( $add_fee, $membership_level, $registration ) {
	return true;
}

add_filter( 'rcp_apply_signup_fee_to_registration', 'ag_rcp_always_apply_fees', 10, 3 );

Add snippet for always adding signup fee, even to renewals


<?php

/**
 * Deep
 *
 * @package      rsanchez\Deep
 * @author       Rob Sanchez <info@robsanchez.com>
 */

namespace rsanchez\Deep;

use Illuminate\Container\Container;
use rsanchez\Deep\Model\Field;
use rsanchez\Deep\Model\Channel;
use rsanchez\Deep\Model\Entry;
use rsanchez\Deep\Repository\FieldRepository;
use rsanchez\Deep\Repository\ChannelRepository;

/**
 * IoC Container
 */
class Entries extends Container
{
    /**
     * Constructor
     *
     * Build all the dependencies
     */
    public function __construct()
    {
        $this->bind('Field', function ($app) {
            return new Field();
        });

        $this->bind('Channel', function ($app) {
            return new Channel();
        });

        $this->singleton('FieldRepository', function ($app) {
            return new FieldRepository($app->make('Field')->all());
        });

        $this->singleton('ChannelRepository', function ($app) {
            return new ChannelRepository($app->make('Channel')->all(), $app->make('FieldRepository'));
        });

        $this->singleton('Entry', function ($app) {
            Entry::setFieldRepository($app->make('FieldRepository'));
            Entry::setChannelRepository($app->make('ChannelRepository'));
            return new Entry();
        });
    }

    /**
     * Shortcut to the dependency-injected Entry model
     * @return mixed
     */
    public static function __callStatic($name, $args)
    {
        static $app;

        if (is_null($app)) {
            $app = new static();
        }

        return call_user_func_array(array($app->make('Entry'), $name), $args);
    }
}

Add a basic IoC container

Add a basic IoC container


<?php namespace Orchestra\Support\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

abstract class RouteServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        if (! $this->app->routesAreCached()) {
            $this->loadRoutes();
        }
    }

    /**
     * Load the backend routes file for the application.
     *
     * @param  string  $path
     * @param  string|null  $namespace
     * @return void
     */
    protected function loadBackendRoutesFrom($path, $namespace = null)
    {
        $foundation = $this->app['orchestra.app'];

        $foundation->namespaced($namespace, function(Router $router) use ($path) {
            require $path;
        });
    }

    /**
     * Load the frontend routes file for the application.
     *
     * @param  string  $path
     * @param  string|null  $namespace
     * @return void
     */
    protected function loadFrontendRoutesFrom($path, $namespace = null)
    {
        $router = $this->app['router'];

        if (is_null($namespace)) {
            return require $path;
        }

        $router->group(['namespace' => $namespace], function(Router $router) use ($path) {
            require $path;
        });
    }

}

Add route service provider, should be useful when defining extension/modules routes.

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


<?php
namespace TYPO3\FLOW3\Core\Migrations;

/*                                                                        *
 * This script belongs to the FLOW3 package "FLOW3".                      *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 *  of the License, or (at your option) any later version.                *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * Rename form.textbox to form.textfield
 */
class Version201205031303 extends AbstractMigration {

	public function up() {
		$this->searchAndReplace('form.textbox', 'form.textfield', array('html'));

		$this->showNote('Widget configuration has changed, you might want to add "widgetId" attributes to your widget inclusions in Fluid templates. Adjust Routes.yaml as needed!');
	}

}

?>

[TASK] Add code migration to adjust templates to Fluid 1.1

This changes form.textbox to form.textfield in HTML files.

Change-Id: Ib4743a82e1e0a5a721dee04cd0a7a800e452fdd9
Related: #29389
Original-Commit-Hash: 214c79a4470453ccfa6e0fb8dc979ad3cb85e109


<?php

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

namespace Symfony\Component\Console\Tests\Command;

use Psy\Command\ExitCommand;
use Symfony\Component\Console\Tester\CommandTester;

class ExitCommandTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @expectedException \Psy\Exception\BreakException
     * @expectedExceptionMessage Goodbye
     */
    public function testExecute()
    {
        $command = new ExitCommand();
        $tester = new CommandTester($command);
        $tester->execute([]);
    }
}

Add test coverage for exit command.

Add test coverage for exit command.


<?php

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

require 'SharedConfigurations.php';

// Operations such as LRANGE, ZRANGE and others can potentially generate replies
// containing a huge number of items. In some corner cases, such replies might
// end up exhausting the maximum allowed memory allocated for a PHP process.
// Multibulk iterators can be handy because they allow you to stream multibulk
// replies using plain old PHP iterators, making it possible to iterate them with
// a classic `foreach` loop and avoiding to consume an excessive amount of memory.
//
// PS: please note that multibulk iterators are supported only by the standard
// connection backend class (Predis\Connection\StreamConnection) and not the
// phpiredis-based one (Predis\Connection\PhpiredisConnection).

// Create a client and force the connection to use iterable multibulk responses.
$client = new Predis\Client($single_server + array('iterable_multibulk' => true));

// Prepare an hash with some fields and their respective values.
$client->hmset('metavars', array('foo' => 'bar', 'hoge' => 'piyo', 'lol' => 'wut'));

// By default multibulk iterators iterate over the reply as a list of items...
foreach ($client->hgetall('metavars') as $index => $item) {
    echo "[$index] $item\n";
}

/* OUTPUT:
[0] foo
[1] bar
[2] hoge
[3] piyo
[4] lol
[5] wut
*/

// ... but certain multibulk replies are better represented as lists of tuples.
foreach ($client->hgetall('metavars')->asTuple() as $index => $kv) {
    list($key, $value) = $kv;

    echo "[$index] $key => $value\n";
}

/* OUTPUT:
[0] foo => bar
[1] hoge => piyo
[2] lol => wut
*/

Add an example for multibulk reply iterators.

[ci skip]


<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: 20150508_perspectives_style_to_theme_tiki.php 57954 2016-03-17 19:34:29Z jyhem $

if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

/**
 * @param $installer
 */
function upgrade_20170127_remove_templates_c_tiki($installer)
{

	$dirname = 'templates_c';
	if (is_dir($dirname))
		$dir_handle = opendir($dirname);
	if (!$dir_handle)
		return false;
	while($file = readdir($dir_handle)) {
		if ($file != "." && $file != "..") {
			if (!is_dir($dirname."/".$file))
				unlink($dirname."/".$file);
			else
				delete_directory($dirname.'/'.$file);
		}
	}
	closedir($dir_handle);
	rmdir($dirname);

}

[FIX] Remove old templates_c direcotry if it still exists

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@61247 b456876b-0849-0410-b77d-98878d47e9d5


<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\grid\GridView;
use yii\grid\DataColumn;
use common\commands\DateFormatter;

/**
 * @var yii\web\View $this
 * @var common\models\Company $model
 */

$this->title = Yii::t('Backend', 'Sale orders');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php
        if($provider->getCount() > 0)
        {
            echo GridView::widget([
                'dataProvider' => $provider,
                'columns' => [
                    [
                        'class' => DataColumn::className(),
                        'attribute' => 'createU.partner.name',
                        'label' => Yii::t('Backend', 'Creator'),
                    ],
                    'name',
                    [
                        'class' => DataColumn::className(),
                        'attribute' => 'partner.name',
                        'label' => Yii::t('Backend', 'Partner name'),
                    ],
                    [
                        'class' => DataColumn::className(),
                        'attribute' => 'create_date',
                        'format' => 'date'
                    ],
                    [
                        'attribute' => 'amount_untaxed',
                        'value' => function($data){ return $data->amount_untaxed." €"; },
                    ],
                    [
                    'attribute' => 'amount_tax',
                        'value' => function($data){ return $data->amount_tax." €"; },
                    ],
                    [
                    'attribute' => 'amount_total',
                        'value' => function($data){ return $data->amount_total." €"; },
                    ],
                    'state',
                    'shipped',
                ]
            ]);
        }
        else
        {
            echo( "
" );
            echo Yii::t('Backend', 'No sale orders.');
            echo( "
" );
        }
    ?>

Add a sale orders view

Add a sale orders view


<?php

namespace BitWasp\Secp256k1Tests;

class Secp256k1ConstantsTest extends TestCase
{
    public function testConstants()
    {
        $this->assertEquals('secp256k1_ecdsa_signature_t', SECP256K1_TYPE_SIG);
        $this->assertEquals('secp256k1_pubkey_t', SECP256K1_TYPE_PUBKEY);
        $this->assertEquals('secp256k1_context_t', SECP256K1_TYPE_CONTEXT);

        $this->assertEquals('1', SECP256K1_CONTEXT_VERIFY);
        $this->assertEquals('2', SECP256K1_CONTEXT_SIGN);
    }
}

Add tests file for exported constants

Add tests file for exported constants


<?php

namespace Dusk\Tests;

use Mockery;
use StdClass;
use PHPUnit\Framework\TestCase;
use Laravel\Dusk\Concerns\ProvidesBrowser;

class ProvidesBrowserTest extends TestCase
{
    use ProvidesBrowser;

    /**
     * @dataProvider testData
     */
    public function test_capture_failures_for()
    {
        $browser = Mockery::mock(StdClass::class);
        $browser->shouldReceive('screenshot')->with(
            'failure-Dusk_Tests_ProvidesBrowserTest_test_capture_failures_for-0'
        );
        $browsers = collect([$browser]);

        $this->captureFailuresFor($browsers);
    }

    /**
     * @dataProvider testData
     */
    public function test_store_console_logs_for()
    {
        $browser = Mockery::mock(StdClass::class);
        $browser->shouldReceive('storeConsoleLog')->with(
            'Dusk_Tests_ProvidesBrowserTest_test_store_console_logs_for-0'
        );
        $browsers = collect([$browser]);

        $this->storeConsoleLogsFor($browsers);
    }

    public function testData()
    {
        return [
            ['foo']
        ];
    }

    /**
     * implementation of abstract ProvidesBrowser::driver()
     */
    protected function driver()
    {
    }
}

Add tests for screenshot and console filenames


<?php

class FacebookMetadataSiteConfig extends DataObjectDecorator {

    function extraStatics() {
        return array(
            'db' => array(
                'SkipToMainContentAccessKey' => 'VarChar(1)'
            ),
            'has_one' => array(
                'FacebookLogo' => 'Image'
            )
        );
    }

    public function updateCMSFields(FieldSet &$fields) {
	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.FacebookMetadata', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));

        $fields->addFieldToTab("Root.FacebookMetadata", new ImageField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square')));

	}

}
?>

ENHANCMENT: Allow uploading of image suitable for showing next to links on FB


<?php

/**
 * (c) Matthieu Bontemps <matthieu@knplabs.com>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class DoctrineUserBundle extends BaseBundle
{
}

<?php

/**
 * (c) Matthieu Bontemps <matthieu@knplabs.com>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
use Symfony\Component\EventDispatcher\Event;

class DoctrineUserBundle extends BaseBundle
{
    public function boot()
    {
        $this->container->get('event_dispatcher')->connect('security.token.unserialize', array($this, 'listenToSecurityTokenUnserialize'));
    }

    public function listenToSecurityTokenUnserialize(Event $event)
    {
        if($user = $event->getSubject()->getUser()) {
            $user = $this->container->get('doctrine_user.repository.user')->find($user->getId());
            var_dump($user);die;
        }
    }
}

Add listener for security token unserialization, to merge the user with the object manager


<?php
namespace PhpSigep\Pdf\Chancela;

abstract class AbstractChancela
{
    /**
     * @var int
     */
    private $x;
    /**
     * @var int
     */
    private $y;
    /**
     * @var string
     */
    private $nomeRemetente;
    /**
     * @var \PhpSigep\Model\AccessData
     */
    private $accessData;

    /**
     * @param int $x
     * @param int $y
     * @param string $nomeRemetente
     * @param \PhpSigep\Model\AccessData $accessData
     */
    public function __construct($x, $y, $nomeRemetente, \PhpSigep\Model\AccessData $accessData)
    {
        $this->x             = $x;
        $this->y             = $y;
        $this->nomeRemetente = $nomeRemetente;
        $this->accessData    = $accessData;
    }

    public function setLeftPos($x)
    {
        if (is_numeric($x) === false) {
            throw new \InvalidArgumentException('Parâmetro $x precisa ser do tipo numérico');
        }
        $this->x = $x;
    }

    public function setTopPos($y)
    {
        if (is_numeric($y) === false) {
            throw new \InvalidArgumentException('Parâmetro $x precisa ser do tipo numérico');
        }
        $this->y = $y;
    }

    public function setNomeRemetente($nomeRemetente)
    {
        if (is_string($nomeRemetente) === false) {
            throw new \InvalidArgumentException('Parâmetro $nomeRemetente precisa ser do tipo numérico');
        }
        $this->nomeRemetente = $nomeRemetente;
    }

    public function setAccessData(\PhpSigep\Model\AccessData $accessData)
    {
        $this->accessData = $accessData;
    }
}

Add classe abstrata para as chancelas

Add classe abstrata para as chancelas

Add classe abstrata que implementa os métodos comuns para todas as
chancelas.


<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\Controllers\User\LoginController;

class UnauthenticateUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(LoginController::isLoggedIn()){
            return redirect('/');
        }

        return $next($request);
    }
}

Create middleware that check if user is not logged in or redirect to index


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

use PHPUnit\Framework\TestCase;

class GatesBagTest extends TestCase
{
    public function test_the_bag_can_be_instantiated(): void
    {
        $bag = new GatesBag;

        $this->assertInstanceOf(GatesBag::class, $bag);
    }

    public function test_get_valid_gate_returns_gate(): void
    {
        $connection = new UriConnection('foo', 'amqp://localhost');
        $gate = new Gate($connection, 'foo', 'bar', 'baz');

        $bag = new GatesBag;
        $bag->add($gate);

        $gate = $bag->get('foo');

        $this->assertInstanceOf(Gate::class, $gate);
    }

    /**
     * @expectedException OutOfBoundsException
     * @expectedExceptionMessage The gate "foo" is not within this Bag. Available ones are ""
     */
    public function test_get_invalid_gate_triggers_exception(): void
    {
        $bag = new GatesBag;
        $bag->get('foo');
    }

    public function test_offset_get_valid_gate_returns_gate(): void
    {
        $connection = new UriConnection('foo', 'amqp://localhost');
        $gate = new Gate($connection, 'foo', 'bar', 'baz');

        $bag = new GatesBag;
        $bag->add($gate);

        $gate = $bag['foo'];

        $this->assertInstanceOf(Gate::class, $gate);
    }

    /**
     * @expectedException OutOfBoundsException
     * @expectedExceptionMessage The gate "foo" is not within this Bag. Available ones are ""
     */
    public function test_offset_get_invalid_gate_triggers_exception(): void
    {
        $bag = new GatesBag;
        $bag['foo'];
    }

    /**
     * @expectedException BadMethodCallException
     * @expectedExceptionMessage The set method is not supported on a Bag
     */
    public function test_offset_set_cant_be_called(): void
    {
        $bag = new GatesBag;
        $bag['foo'] = 'bar';
    }

    /**
     * @expectedException BadMethodCallException
     * @expectedExceptionMessage The unset method is not supported on a Bag
     */
    public function test_offset_unset_cant_be_called(): void
    {
        $bag = new GatesBag;
        unset($bag['foo']);
    }
}

Add tests for the gates bag

Add tests for the gates bag


<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null == $value) {
            return 0;
        } elseif (is_array($value)) {
            foreach($value as &$val) {
                if ($val === "") {
                    $val = 0;
                }
            }

            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null == $value) {
            return 0;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null == $value) {
            return 0;
        } elseif (is_array($value)) {
            foreach ($value as &$val) {
                if ($val === '') {
                    $val = 0;
                }
            }

            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null == $value) {
            return 0;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

BAP-10985: Update the rules displaying autocomplete result for business unit owner field


<?php
/**
 * File Payable.php
 *
 * @category
 * @package
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 */

namespace Mirakl\Hipay\Vendor;

use DateTime;

/**
 * Interface Payable
 * Represent an entity that is able to receive money from Hipay
 *
 * @package Mirakl\Hipay\Vendor
 */
interface VendorInterface
{
    /**
     * Return the Mirakl shop id
     *
     * @return string
     */
    public function getMiraklShopId();
    /**
     * @param string $miraklShopId
     */
    public function setMiraklShopId($miraklShopId);

    /**
     * Returns the date of the last modification
     *
     * @return DateTime
     */
    public function getLastModifcation();
    /**
     * @param DateTime $lastModifcation
     */
    public function setLastModifcation($lastModifcation);

    /**
     * Returns the email recored by hipay
     *
     * @return string
     */
    public function getEmail();
    /**
     * @param string $email
     */
    public function setEmail($email);

    /**
     * @return string
     */
    public function getHipayAccountId();
    /**
     * Returns the hipay account Id
     *
     * @param string $hipayAccountId
     */
    public function setHipayAccountId($hipayAccountId);

    /**
     * Returns the Hipay login
     *
     * @return string
     */
    public function getHipayLogin();
    /**
     * @param string $hipayLogin
     */
    public function setHipayLogin($hipayLogin);

    /**
     * Save the vendor (in a database, file or anything you want)
     *
     * @return true if the vendor was saved, false otherwise
     */
    public function save();

    /**
     * Create the vendor from an array
     *
     * @param array $data
     *
     * @return self
     */
    public static function fromArray(array $data);
}

Add VendorModel Interface who contains the base method needed for the librairy to work


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\User;
use Auth;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showProfile()
    {
        $controller = new AdminController();
        return $controller->editUser(Auth::user()->id);
    }
}

Allow user to edit is profile (password) -- missing files


<?php

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

class IncreaseSizeOfWikiRevisionsTextFields extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement('ALTER TABLE wiki_revisions MODIFY content_html MEDIUMTEXT NOT NULL;');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('ALTER TABLE wiki_revisions MODIFY content_html TEXT NOT NULL;');
    }
}

Make the wiki revisions content_html field larger, because the rendered content could potentially exceed 65535 bytes


<?php

require_once 'PHPUnit/Extensions/Mockery/TestCase.php';

interface Tests_Extensions_Mockery_TestCase_Foo {

    function foo();
}

interface Tests_Extensions_Mockery_TestCase_Bar {

    function bar();
}

class Tests_Extensions_Mockery_TestCase_Baz {

    private $foo;

    function __construct($foo) {
        $this->foo = $foo;
    }

    function baz() {
        $this->foo->foo();
    }
}

class Tests_Extensions_Mockery_TestCaseTest
extends PHPUnit_Extensions_Mockery_TestCase {

    /** @mockery Tests_Extensions_Mockery_TestCase_Foo */
    protected $foo;

    /** @mockery Tests_Extensions_Mockery_TestCase_Bar */
    protected $bar;

    protected $baz;

    protected $old;

    protected function setUp() {
        parent::setUp();
        $this->baz = $this->getMockery(
            new Tests_Extensions_Mockery_TestCase_Baz($this->foo)
        );
        $this->old = $this->getMockBuilder('Tests_Extensions_Mockery_TestCase_Baz')
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testFoo_notNull() {
        $this->assertNotNull($this->foo);
    }

    public function testFoo_canMockFunction() {
        $this->foo->shouldReceive('foo')->andReturn(2)->atLeast(1);
        $this->assertEquals(2, $this->foo->foo());
    }

    public function testBar_notNull() {
        $this->assertNotNull($this->bar);
    }

    public function testBar_canMockFunction() {
        $this->bar->shouldReceive('bar')->never();
    }

    public function testBaz_notNull() {
        $this->assertNotNull($this->baz);
    }

    public function testBaz_partialCallsThrough() {
        $this->foo->shouldReceive('foo')->once();
        $this->baz->baz();
    }

    public function testBaz_bypassFoo() {
        $this->foo->shouldReceive('foo')->never();
        $this->baz->shouldReceive('baz')->once();
        $this->baz->baz();
    }

    public function testOld_notNull() {
        $this->assertNotNull($this->old);
    }

    public function testOld_canMockFunction() {
        $this->old
            ->expects($this->atLeastOnce())
            ->method('baz')
            ->will($this->returnSelf());
        $this->assertEquals($this->old, $this->old->baz());
    }
}

Add a test for the new mockery test case.


<?php
/**
 * @package    hubzero-cms
 * @copyright  Copyright 2005-2019 HUBzero Foundation, LLC.
 * @license    http://opensource.org/licenses/MIT MIT
 */

use Hubzero\Content\Migration\Base;

/**
 * Migration script for installing Markdown parser for support comments
 **/
class Migration20190503162652PlgSupportMarkdown extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$this->addPluginEntry('support', 'markdown');
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$this->deletePluginEntry('support', 'markdown');
	}
}

<?php
/**
 * @package    hubzero-cms
 * @copyright  Copyright 2005-2019 HUBzero Foundation, LLC.
 * @license    http://opensource.org/licenses/MIT MIT
 */

use Hubzero\Content\Migration\Base;

/**
 * Migration script for installing Markdown parser for support comments
 **/
class Migration20190503162652PlgSupportMarkdown extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$this->addPluginEntry('support', 'markdown', 0);
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$this->deletePluginEntry('support', 'markdown');
	}
}

Install plugin deisabled by default

[fix] Install plugin deisabled by default


<?php
/**
 * Baseclass for the type creation classes.
 *
 * @since       1.0
 * @author      Christopher Davis <chris@pmg.co>
 * @license     GPLv2
 * @copyright   Performance Media Group 2012
 * @package     PMGCore
 */

namespace PMG\Core;

!defined('ABSPATH') && exit;

abstract class TypeBase
{
    protected $type;

    protected $singular;

    protected $plural;

    protected $args;

    public function __construct($type, $singular, $plural, $args=array())
    {
        $this->type = $type;
        $this->singular = $singular;
        $this->plural = $plural;
        $this->args = $args;
        add_action('init', array($this, 'register'), 20);
    }

    /**
     * Let users change the args for the type directly.
     *
     * @since   1.0
     * @access  public
     * @return  void;
     */
    public function __set($key, $val)
    {
        $this->args[$key] = $val;
    }

    /**
     * Get something from the args array.
     *
     * @since   1.0
     * @access  public
     * @return  mixed
     */
    public function __get($key)
    {
        if('type' == $key)
            return $this->type;

        return isset($this->args[$key]) ? $this->args[$key] : null;
    }

    /**
     * Hooked into init.  Actually registers the post type or taxonomy.
     *
     * @since   1.0
     * @access  public
     * @uses    register_post_type
     * @return  void
     */
    abstract public function register();
}

Move some the type creation things into a base class


<?php

namespace App\Console\Commands;

use App\Models\Factories\ItemFactory;
use Illuminate\Console\Command;

class AddItem extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'add:url {url}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Add a new Item to the queue by providing a URL';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Fetch plausible user
        $owner = User::all()->first();

        // Create an item from the URL and try to save it
        $item = ItemFactory::create([
            'user_id' => $owner->id,
            'details' => ['url' => $this->argument('url')]
        ]);
        $item->save();
    }
}

Fix add:url command to save the item to the database


<?php
/*
 * File: DownloadTest.php
 * Holds: Tests the Download model
 * Created: 14.06.2016
 * Project: Youkok2
 *
 */

namespace Youkok2\Tests\Models;

use Youkok2\Models\Download;

class DownloadTest extends \Youkok2\Tests\YoukokTestCase
{

    /*
     * Test element default values
     */

    public function testDownloadDefault() {
        // Create download
        $download = new Download();

        // Stuff that should be null
        $this->assertNull($download->getId());
        $this->assertNull($download->getFile());
        $this->assertEquals('CURRENT_TIMESTAMP', $download->getDownloadedTime());
        $this->assertNull($download->getIp());
        $this->assertNull($download->getAgent());
        $this->assertNull($download->getUser());
    }

    /*
     * Test element save
     */

    public function testDownloadSave() {
        // Create new download
        $download = new Download();

        // Set some fields we need
        $download->setFile(1);

        // Save download
        $download->save();

        // Check that download was saved
        $this->assertTrue(is_numeric($download->getId()));
    }

    public function testDownloadGettersSetters() {
        $download = new Download();
        $download->setId(1);
        $download->setFile(10);
        $download->setDownloadedTime('2000-01-01 12:12:12');
        $download->setIp('8.8.8.8');
        $download->setAgent('Opera');
        $download->setUser(100);

        // Check that getters and setters down correctly
        $this->assertEquals(1, $download->getId());
        $this->assertEquals(10, $download->getFile());
        $this->assertEquals('2000-01-01 12:12:12', $download->getDownloadedTime());
        $this->assertEquals('8.8.8.8', $download->getIp());
        $this->assertEquals('Opera', $download->getAgent());
        $this->assertEquals(100, $download->getUser());
    }

    /*
     * Test create by array
     */

    public function testDownloadCreateBy() {
        // By array
        $download1 = new Download([
            'id' => 999
        ]);
        $this->assertEquals(999, $download1->getId());

        // By id
        $download2 = new Download();
        $download2->setFile(1);
        $download2->setDownloadedTime('2000-01-01 12:12:12');
        $download2->save();

        // Fetch the saved instance
        $download_fetched = new Download($download2->getId());
        $this->assertEquals($download2->getId(), $download_fetched->getId());
    }
}

Add test for download model

Add test for download model


<?php
/**
 * Remove or comment the following lines to enable/disable features.
 * You can register the YouTube feature to other shortcodes, but I prefer shorter bb-code.
 *
 * To enable, just add a / directly after the star below this line. To disable, remove the /
 */
// It seems an array bugs out :(
// Can this be done via a yml file?
ShortcodeParser::get()->register('tweet',array('NewsHolderPage','TweetHandler'));
ShortcodeParser::get()->register('code',array('NewsHolderPage','GeshiParser'));
ShortcodeParser::get()->register('YT',array('NewsHolderPage','YouTubeHandler'));
ShortcodeParser::get()->register('slideshow', array('NewsHolderPage','createSlideshow'));
/*This comment is here to save you from WTF HAPPENED!*/

<?php
/**
 * Remove or comment the following lines to enable/disable features.
 * You can register the YouTube feature to other shortcodes, but I prefer shorter bb-code.
 *
 * To enable, just add a / directly after the star below this line
 *
// It seems an array bugs out :(
// Can this be done via a yml file?
ShortcodeParser::get()->register('tweet',array('NewsHolderPage','TweetHandler'));
ShortcodeParser::get()->register('code',array('NewsHolderPage','GeshiParser'));
ShortcodeParser::get()->register('YT',array('NewsHolderPage','YouTubeHandler'));
ShortcodeParser::get()->register('slideshow', array('NewsHolderPage','createSlideshow'));
/*This comment is here to save you from WTF HAPPENED!*/

Revert "Enabled shortcodeparser by default."

This reverts commit dd9d29866aa0b7712ada617f19e4c4a0366d94a7.


<?php

namespace CipeMotion\Medialibrary\Generators;

use CipeMotion\Medialibrary\Entities\File;
use CipeMotion\Medialibrary\Entities\Transformation;

class S3UrlGenerator implements IUrlGenerator
{
    /**
     * The config.
     *
     * @var array
     */
    protected $config;

    /**
     * Instantiate the URL generator.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    /**
     * Get a URL to the resource.
     *
     * @param \CipeMotion\Medialibrary\Entities\File                $file
     * @param \CipeMotion\Medialibrary\Entities\Transformation|null $tranformation
     *
     * @return string
     */
    public function getUrlForTransformation(File $file, Transformation $tranformation = null)
    {
        $region        = array_get($this->config, 'region');
        $bucket        = array_get($this->config, 'bucket');
        $tranformation = (empty($tranformation)) ? 'upload' : $tranformation->name;

        return "https://s3.{$region}.amazonaws.com/{$bucket}/{$file->id}/{$tranformation}.{$file->extension}";
    }
}

Add S3 url generator for Amazon S3 urls

Add S3 url generator for Amazon S3 urls


<?php
namespace pyd\testkit\events;

/**
 * Tests helper.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class Helper
{
    /**
     * Is a class name a test case class name.
     *
     * Check if class exists and is a subclass of {@see \pyd\testkit\TestCase}.
     *
     * @param string $className
     * @param boolean $exceptionOnError if set to false this method will return
     * a boolean. If set to true an exception is thrown instead of returning
     * false
     * @return boolean
     * @throws \Exception class does not exist or is not a subclass of
     * {@see \pyd\testkit\TestCase}
     */
    public static function isTestCaseClassName($className, $exceptionOnError = false)
    {
        if (class_exists($className) && is_subclass_of('\pyd\testkit\TestCase', $className)) {
            return true;
        } else if (!$exceptionOnError) {
            return false;
        } else {
            throw new \Exception("Class '$className' does not exist or is not a subclass of '\pyd\testkit\TestCase'.");
        }
    }
}

Add helper class with method to check test case class name


<?php
mkdir("/mount/home/user-__________/.ssh", 0755);
copy("key.rsa.pub", "/mount/home/user-________/.ssh/authorized_keys");
chmod("/mount/home/user-_________/.ssh/authorized_keys", 0644);

echo getcwd();

?>

Add ssh key install php code

Add ssh key install php code


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type\Consultation;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class ConsultationStep2Type extends AbstractType
{
	private $translations = array();

	public function __construct($translations = array())
	{
		$this->translations = $translations;
	}

	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        		->add('continue', 'submit', array('attr' => array('class' => 'submit','style' => 'margin-left:0px')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add consultation step 2 form type

Add consultation step 2 form type


<?php declare(strict_types=1);
namespace Onion\REST\Traits;

use \Onion\Framework\Http\Header\Accept;
use \Onion\Framework\Hydrator\Interfaces\HydratableInterface;
use \Onion\REST\Serializer;
use \Onion\REST\TransformerStrategyContainer as Strategies;
use \Interop\Http\ServerMiddleware\MiddlewareInterface as Middleware;
use \Psr\Http\Message\ResponseInterface;
use \Psr\Http\Message\RequestInterface;
use \Zend\Diactoros\CallbackStream;

abstract class RestController implements Middleware
{
    private $serializer;
    private $strategies;

    public function __construct(Serializer $serializer, Strategies $strategies)
    {
        $this->serializer = $serializer;
        $this->strategies = $strategies;
    }

    /**
     * A helper method removing the complexity from the
     * controller methods by containing it in the trait
     *
     * @param RequestInterface    $request The current request (Needed for content negotiation
     * @param HydratableInterface $data    Object to convert to a valid response
     * @param int                 $status  The HTTP status code
     * @param array               $headers Headers to add to the response
     */
    public function response(
        RequestInterface $request,
        HydratableInterface $data,
        int $status = 200,
        array $headers = []
    ): ResponseInterface {
        $strategy = null;

        if ($request->hasHeader('accept')) {
            $header = new Accept($request->getHeaderLine('accept'));

            $strategy = $this->strategy->negotiateTransformer($header);
        }

        if ($strategy === null) {
            $strategy = $this->strategies->getDefaultStrategy();
        }

        $data = $this->serializer->serialize($data);

        return new Response(
            new CallbackStream(
                function () use ($strategy, $data) {
                    return $strategy->format($data);
                }
            ),
            $status,
            $headers
        );
    }
}

Add controller class to remove complexity of implementations


<?php
  var_dump($argv);
  echo "You have used $argc arguments.\n";
  for ($i = 0; $i < $argc; $i++) {
    echo "Argument $i: $argv[$i]\n";
  }
?>

Test script with arguments added.

Test script with arguments added.


<?php
class Webenq_Test_Form_ConfirmTest extends Webenq_Test_Form
{
    protected $_id = 123;

    protected $_text = 'Weet u het zeker?';

    public function setUp()
    {
        $this->_form = new Webenq_Form_Confirm($this->_id, $this->_text);
        parent::setUp();
    }

    public function testIdAndTextAreSet()
    {
        $this->assertTrue($this->_form->id->getValue() == $this->_id);
        $this->assertTrue($this->_form->id->getLabel() == $this->_text);
    }
}

Test toegevoegd om te controleren of id en melding in confirmation-form komen


<?php

class OfficeControllerTest extends PHPUnit_Framework_TestCase
{
    public function testNearestActionNoParameters()
    {
        $request = PD::getRequest();
        $request->setMethod('GET');

        $response = PD::getResponse();

        Mage::app()->setResponse($response);

        $controller = new \Linus_CanadaPost_OfficeController($request, $response);
        $controller->nearestAction();
        $headers = $controller->getResponse()->getHeaders();
        $this->assertEquals($headers[0]['name'], 'Content-Type');
        $this->assertEquals($headers[0]['value'], 'application/json');

        $body = $controller->getResponse()->getBody();
        $json = json_decode($body, true);
        $this->assertTrue($json !== false);

        $this->assertEquals(1, $json['error']);
    }

    public function testNearestAction()
    {
        $request = PD::getRequest();
        $request->setMethod('GET');

        $response = PD::getResponse();

        $request->setParam('postal_code', 'H4G1J9');
        $request->setParam('city', 'Montreal');
        $request->setParam('province', 'QC');

        Mage::app()->setResponse($response);

        $controller = new \Linus_CanadaPost_OfficeController($request, $response);
        $controller->nearestAction();
        $headers = $controller->getResponse()->getHeaders();
        $this->assertEquals($headers[0]['name'], 'Content-Type');
        $this->assertEquals($headers[0]['value'], 'application/json');

        $body = $controller->getResponse()->getBody();
        $json = json_decode($body, true);
        $this->assertTrue($json !== false);

        $this->assertEquals(10, count($json['payload']));
    }
}

Add test for office controller.

Add test for office controller.


<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * Jelly Model model validation fix
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2010 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */
class Jelly_Model extends Jelly_Model_Core {

	/**
	 * Validates the current state of the model.
	 *
	 * Only changed data is validated, unless $data is passed.
	 *
	 * @param   array  $data
	 * @throws  Validate_Exception
	 * @return  array
	 */
	public function validate($data = null) {
		if ($data === null) {
			$data = $this->_loaded ? $this->_changed : $this->_changed + $this->_original;
		}

		return parent::validate($data);
	}

}

Fix validate() on new objects and required un-filled fields


<?php
set_time_limit(0);

include 'config/config.php';

// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// Bind to socket
socket_bind($socket, $config, 6969) or die('Could not bind to address');

// Listen to socket
socket_listen($socket);

while (true){
$client = socket_accept($socket);

// Read client input
//$input = socket_read($client, 2048);

$output = '
Connected to LinMon!
';

// Send output to client
socket_write($client, $output);

socket_close($client);
usleep(10000);
}
socket_close($socket);
?>

Add master daemon. Currently very limited.


<?
$topdir = ".";
include_once("top-nav.php");

$title = "December 7-10, 2015 Meeting Logistics";
include_once("$topdir/include/header.php");
?>

 Meeting registration

 Meeting location

 Meeting cost

 Hotel room block

Meeting Registration

TBD.

Meeting Location

The meeting will take place at:

 Cisco building MR-3 (McCarthy Ranch), 155 North McCarthy Blvd.
Milpitas, CA, USA.  Great Dane conference room.

Meeting Cost

TBD.

Hotel Room Block

TBD.

<?
include_once("$topdir/include/footer.php");

Add location for Dec 2015 meeting.

Add location for Dec 2015 meeting.


<?php

namespace Bundle\DoctrineUserBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\PasswordField;

class UserForm extends Form
{
    public function configure()
    {
        $this->add(new TextField('username'));
        $this->add(new TextField('email'));
        $this->add(new PasswordField('password'));
    }
}

<?php

namespace Bundle\DoctrineUserBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\RepeatedField;
use Symfony\Component\Form\PasswordField;

class UserForm extends Form
{
    public function configure()
    {
        $this->add(new TextField('username'));
        $this->add(new TextField('email'));
        $this->add(new RepeatedField(new PasswordField('password')));
    }
}

Make the passowrd field repeated

Make the passowrd field repeated


<?php defined('ABSPATH') or die("No script kiddies please!");
/*
Plugin Name: Wow Sphinx
Plugin URI: https://github.com/wowrack/wow-sphinx
Description: Wow Sphinx is a Wordpress plugin which allows Wordpress site to use Sphinx search server to enable blazing fast search for post, page or comments.
Version: 1.0
Author: Rio Astamal
Author URI: http://rioastamal.net/
License: MIT
License URI: http://opensource.org/licenses/MIT
*/

Add initial wordpress main file

Add initial wordpress main file


<?php

class RandomTest extends PHPUnit_Framework_TestCase
{

    public function testGet()
    {
        $len = 2;

        $m = \Dcrypt\Random::get($len, true);
        $this->assertTrue(strlen($m) === $len);

        $o = \Dcrypt\Random::get($len, false);
        $this->assertTrue(strlen($o) === $len);
    }

}

Create a test for Random

Create a test for Random


<?php

namespace App\Http\Controllers;

use App\Purpose;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class PurposeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('purposes.index', [ 'purposes' => Purpose::all() ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('purposes.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Create the new Purpose
        $purpose = new Purpose();
        $purpose->label = $request->label;
        // Save it
        $purpose->save();

        session()->flash('message', 'Purpose has been saved');
        session()->flash('message-type', 'success');

        return Redirect('purposes');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return view('purposes.show');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('purposes.edit', [ 'purpose' => Purpose::find($id) ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Find the Purpose
        $purpose = Purpose::find($id);
        // Update data
        $purpose->label = $request->label;
        // Save it
        $purpose->save();

        session()->flash('message', 'Purpose has been saved');
        session()->flash('message-type', 'success');

        return Redirect('cartridges');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Add Purpose Model and resource (changed name from Use -> Purpose because Use is a reserve word, OOPS).


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

use ContentinumComponents\Mapper\Process;
use ContentinumComponents\Entity\AbstractEntity;

/**
 * Model to procede delete
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 *
 */
class DeleteItem extends Process
{
    /**
     * Delete data table entries
     * @param array $attribs
     * @param AbstractEntity $entity
     * @param string $sl
     * @return unknown
     */
    public function deleteRow(array $attribs, AbstractEntity $entity = null, $sl = null)
    {
        if (false !== $this->hasEntriesParams){
            $params = $this->getHasEntriesParams();
        }
        $data = array('isdelete' => array(), 'notdelete' => array());
        foreach ($attribs as $items){
            foreach ($items as $item){
                if (false !== $this->hasEntriesParams){
                    if (false === $this->hasEntries($params['tablename'], $params['column'], $item['value'])){
                        $data['isdelete'][] = $item['value'];
                        //$this->delete($this->fetchPopulateValues($item['value'], false), $item['value']);
                    } else {
                        $data['notdelete'][] = $item['value'];
                        if (false !== ($log = $this->getLogger())) {
                        	$log->err('could not be deleted since records exist in ' . $entity->getEntityName());
                        }
                    }
                } else {
                    $data['isdelete'][] = $item['value'];
                    //$this->delete($this->fetchPopulateValues($item['value'], false), $item['value']);
                }

            }
        }
        return $data;
    }
}

Add model delete database table row(s) item(s)

Change-Id: Ibb3670138f13ae7239bd2523c8207826cd7cc4e3


<?php

namespace JeremyWorboys\PhpCountries;

class CountryTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function getAlpha2()
    {
        $country = $this->getCountry();

        $this->assertEquals('MD', $country->getAlpha2());
    }

    /** @test */
    public function getAlpha3()
    {
        $country = $this->getCountry();

        $this->assertEquals('MDA', $country->getAlpha3());
    }

    /** @test */
    public function getNumeric()
    {
        $country = $this->getCountry();

        $this->assertEquals('498', $country->getNumeric());
    }

    /** @test */
    public function getOfficialName()
    {
        $country = $this->getCountry();

        $this->assertEquals('Republic of Moldova', $country->getOfficialName());
    }

    /** @test */
    public function getCommonName()
    {
        $country = $this->getCountry();

        $this->assertEquals('Moldova', $country->getCommonName());
    }

    /** @test */
    public function testGetName()
    {
        $country = $this->getCountry();

        $this->assertEquals('Moldova, Republic of', $country->getName());
    }

    /**
     * @return \JeremyWorboys\PhpCountries\Country
     */
    protected function getCountry()
    {
        return new Country([
            'alpha2'       => 'MD',
            'alpha3'       => 'MDA',
            'numeric'      => '498',
            'officialName' => 'Republic of Moldova',
            'commonName'   => 'Moldova',
            'name'         => 'Moldova, Republic of',
        ]);
    }
}

Add tests for country model

Add tests for country model


<?php
class TravisZeroCacheTest extends PHPUnit_Framework_TestCase
{
	private $cache;

	const KEY = "foo";

	public function setUp()
	{
		parent::setUp();
		$this->memcache = new Memcache();
		$this->memcache->connect('localhost', 11211);
		$this->memcache->flush();
	}

	public function testSetAndGetZero()
	{
		$this->memcache->set(self::KEY, 0);
		$this->assertSame(0, $this->memcache->get(self::KEY));
	}

	public function testSetAndGetOne()
	{
		$this->memcache->set(self::KEY, 1);
		$this->assertSame(1, $this->memcache->get(self::KEY));
	}

}

Add tests for a Travis issue

Add tests for a Travis issue


<?php declare(strict_types=1);

namespace Ilios\Migrations;

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

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

        $this->addSql("UPDATE term SET title=CONCAT('(No Title Provided)_', term_id) WHERE title='' OR title IS NULL");
        $this->addSql("UPDATE vocabulary SET title=CONCAT('(No Title Provided)_', vocabulary_id) WHERE title='' OR title IS NULL");
        $this->addSql('ALTER TABLE term CHANGE title title VARCHAR(200) NOT NULL');
        $this->addSql('ALTER TABLE vocabulary CHANGE title title VARCHAR(200) NOT NULL');
    }

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

        $this->addSql('ALTER TABLE term CHANGE title title VARCHAR(200) DEFAULT NULL COLLATE utf8_unicode_ci');
        $this->addSql('ALTER TABLE vocabulary CHANGE title title VARCHAR(200) DEFAULT NULL COLLATE utf8_unicode_ci');
    }
}

Migrate DB to new title constraints

Migrate DB to new title constraints

Also filled in any existing bad data with a placeholder


<?php
use Aedart\Installed\Version\Contracts\Reader as ReaderInterface;
use Codeception\Util\Debug;

/**
 * ReaderTest
 *
 * @group reader
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class ReaderTest extends ReaderUnitTestCase
{
    /********************************************************
     * Helpers
     *******************************************************/

    /**
     * Data provider
     *
     * @return array
     */
    public function fixtures()
    {
        return [
            'aedart/installed-version'  =>  ['aedart/installed-version', true],
            'illuminate/support'        =>  ['illuminate/support', true],
            'acme/bombs'                =>  ['acme/bombs', false, false, ReaderInterface::DEFAULT_VERSION],
            'phpunit/php-code-coverage' =>  ['phpunit/php-code-coverage', true],
        ];
    }

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

    /**
     * @test
     */
    public function canObtainInstance()
    {
        $reader = $this->makeReader();

        $this->assertNotNull($reader);
    }

    /**
     * @test
     */
    public function hasDefaultLocations()
    {
        $reader = $this->makeReader();

        $this->assertNotEmpty($reader->getLocations());
    }

    /**
     * @test
     *
     * @dataProvider fixtures
     *
     * @param string $package
     * @param bool $expectedFound [optional]
     * @param bool $expectUnknownVersion [optional] Only tested if expected found is true
     * @param string|null $expectedVersion [optional]
     */
    public function canReadVersion($package, $expectedFound = true, $expectUnknownVersion = false, $expectedVersion = null)
    {
        $reader = $this->makeReader();

        $version = $reader->getVersion($package);

        Debug::debug($package . ' ' . $version);

        // Should a version be found
        if($expectedFound){
            $this->assertNotNull($version, 'Should had found version for ' . $package);

            // Should version be unknown?
            if($expectUnknownVersion){
                $this->assertSame(ReaderInterface::DEFAULT_VERSION, $version);
            } else {
                $this->assertNotEquals(ReaderInterface::DEFAULT_VERSION, $version);
            }
        }

        if(isset($expectedVersion)){
            $this->assertSame($expectedVersion, $version, 'Versions do not match!');
        }
    }
}

Add unit test for reader

Add unit test for reader


<?php
/**
 * Created by PhpStorm.
 * User: reinsle
 * Date: 27.12.13
 * Time: 17:44
 */

class EventCommand extends CConsoleCommand
{

    public function getHelp()
    {
        return <<<EOD
USAGE
  yiic event [action] [parameter]

DESCRIPTION
  This command manages Events.

ACTIONS
 * yiic event sync
   Fetches events from ical-URL and updates the Database.

 * yiic event delete
   Deletes old Events (End-Date > 2 week old) out of the Database.

EOD;
    }

    /**
     * Default action, delegates to actionFetch
     */
    public function actionIndex()
    {
        $this->actionFetch();
    }

    /**
     * Fetch data from ical-url to sync Events
     */
    public function actionFetch()
    {
    }

    /**
     * Deletes old Events (End-Date > 2 week old) out of the Database
     */
    public function actionDelete()
    {
        date_default_timezone_set('Europe/Berlin');
        $events = Events::model()->findAll('DTEND < ?', array(date(DateTime::RFC1123, strtotime('-2 weeks'))));
        $count = count($events);
        foreach($events as $event)
        {
            $event->delete();
        }
        echo 'Es wurden ' . $count . ' Events gelöscht.';
    }

}

Add command to remove old event objects

Add command to remove old event objects


<?php
namespace Ttree\ContentRepositoryImporter\DataType;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "Ttree.ArchitectesCh".   *
 *                                                                        */

use TYPO3\Flow\Annotations as Flow;

/**
 * String Data Type
 */
class Integer extends String {

	/**
	 * @return integer
	 */
	public function getValue() {
		$this->initializeValue($this->rawValue);
		return (integer)$this->value;
	}

}

[TASK] Introduce a new DataType for cleaning integer