<?php

require_once "vendor/autoload.php";
require_once 'example_helpers.php';

/*
  The following snippet shows an example of how to search for people using the autocomplete endpoint and ensure these people still have a member
  role to a specific organization (eg. branch)

  The script is broken down into two separate API calls:

  1. Use the autocomplete endpoint in order to find people matching a specific term, this query will match on names (partial supported), membership number, primary email and phone numbers.
  2. A follow-up request using the results from step one in order to fetch more details (roles) about the people.

*/

$client = wicket_api_client();

// Autocomplete is limited to 100 results total.
$max_results = 25;
$branch_organization_id = 'fa957ab0-89bf-484b-91b4-9d8cdd7fbf7c';

$autocomplete_results = $client->get('/search/autocomplete', [
  'query' => [
    // Autocomplete lookup query, can filter based on name, membership number, email etc.
    'query' => 'Laker',
    // Skip side-loading of people for faster request time.
    'include' => '',
    'filter' => [
      // Limit autocomplete results to only people resources
      'resource_type' => 'people'
    ],
    'page' => [
      'size' => $max_results
    ]
  ]
]);

$autocomplete_person_uuids = array_map(function ($result) {
  return $result['relationships']['resource']['data']['id'];
}, (array)$autocomplete_results['data']);

$matching_people = [];

if (!empty($autocomplete_uuids)) {
  // Work around PHP limitation when serializing array query parameters. Wicket expects
  // arrays parameters to be formatted without numbers eg. param[]=1
  $people_query = preg_replace('/\%5B\d+\%5D/', '%5B%5D', http_build_query([
    'include' => 'emails,roles',
    'filter' => [
      'uuid_in' => $autocomplete_person_uuids
    ],
    'page' => [
      'size' => $max_results
    ]
  ]));

  $people_lookup_results = $client->get('/people', ['query' => $people_query]);
  $response_helper = new \Wicket\ResponseHelper($people_lookup_results);
  $matching_people = array_filter($response_helper->data, function ($person) use ($response_helper, $branch_organization_id) {
    $has_branch_member_role = false;
    $branch_resource_id = ['type' => 'organizations', 'id' => $branch_organization_id];

    $roles = (array)$response_helper->getIncludedRelationship($person, 'roles');

    foreach ($roles as $role) {
      if ($role['attributes']['name'] == 'member' && $role['relationships']['resource']['data'] == $branch_resource_id) {
        $has_branch_member_role = true;
        break;
      }
    }

    return $has_branch_member_role;
  });
}

foreach ($matching_people as $person) {
  echo "Person Name: " . $person['attributes']['full_name'] . PHP_EOL;
}

Add advanced autocomplete search example.


<?php
/**
 * Panada session Handler.
 *
 * @package	Resources
 * @link	http://panadaframework.com/
 * @license	http://www.opensource.org/licenses/bsd-license.php
 * @author	Iskandar Soesman <k4ndar@yahoo.com>
 * @since	Version 0.1
 */
namespace Resources;

class Session {

    private $driver, $config;

    public function __construct($connection = 'default'){

        $this->config = Config::session();
	$this->config = $this->config[$connection];
	$driverNamespace = 'Drivers\Session\\'.ucwords($this->config['driver']);
        $this->driver = new $driverNamespace($this->config);
    }

    /**
     * Use magic method 'call' to pass user method
     * into driver method
     *
     * @param string @name
     * @param array @arguments
     */
    public function __call($name, $arguments){

        return call_user_func_array(array($this->driver, $name), $arguments);
    }

    public function __get($name){

        return $this->driver->$name;
    }

    public function __set($name, $value){

        $this->driver->$name = $value;
    }
}

<?php
/**
 * Panada session Handler.
 *
 * @package	Resources
 * @link	http://panadaframework.com/
 * @license	http://www.opensource.org/licenses/bsd-license.php
 * @author	Iskandar Soesman <k4ndar@yahoo.com>
 * @since	Version 0.1
 */
namespace Resources;

class Session {

    private $driver, $config;

    public function __construct($connection = 'default'){

        $this->config = Config::session();
	$this->config = $this->config[$connection];

    }

    /**
     * Overrider for session config option located at file app/config/session.php
     *
     * @param array $option The new option.
     * @return void
     * @since version 1.0
     */
    public function setOption( $option = array() ){

	$this->config = array_merge($this->config, $option);
    }

    /**
     * Use magic method 'call' to pass user method
     * into driver method
     *
     * @param string @name
     * @param array @arguments
     */
    public function __call($name, $arguments){

	$this->init();

        return call_user_func_array(array($this->driver, $name), $arguments);
    }

    /**
     * Magic getter for properties
     *
     * @param string
     * @return mix
     */
    public function __get($name){

        return $this->driver->$name;
    }

    /**
     * Magic setter for properties
     *
     * @param string
     * @param mix
     * @return mix
     */
    public function __set($name, $value){

        $this->driver->$name = $value;
    }

    /**
     * Instantiate the driver class
     *
     * @return void
     * @since version 1.0
     */
    private function init(){

	$driverNamespace = 'Drivers\Session\\'.ucwords($this->config['driver']);
        $this->driver = new $driverNamespace($this->config);
    }
}

Add dynamic option setter for session resource


<?php

namespace Hateoas\Tests\Factory;

use Hateoas\Factory\Config\ArrayConfig;
use Hateoas\Factory\Definition\RouteLinkDefinition;
use Hateoas\Factory\RouteAwareFactory;
use Hateoas\Tests\TestCase;

class RouteAwareFactoryTest extends TestCase
{
    public function testGetResourceDefinition()
    {
        $factory = new RouteAwareFactory(new ArrayConfig(array(
            'foobar' => array(
                array('rel' => 'foo', 'type' => 'bar', 'route' => 'foo.get')
            ),
        ), array()));

        $def = $factory->getResourceDefinition('foobar');
        $this->assertInstanceOf('Hateoas\Factory\Definition\ResourceDefinition', $def);
        $this->assertEquals('foobar', $def->getClass());

        $links = $def->getLinks();
        $this->assertCount(1, $links);
        $this->assertInstanceOf('Hateoas\Factory\Definition\RouteLinkDefinition', $links[0]);
        $this->assertEquals('foo', $links[0]->getRel());
        $this->assertEquals('bar', $links[0]->getType());
        $this->assertEquals('foo.get', $links[0]->getRoute());
    }

    public function testGetResourceDefinitionWithLinkDefinition()
    {
        $linkDef = new RouteLinkDefinition('foo.bar',  array(), 'foo', 'bar');
        $factory = new RouteAwareFactory(new ArrayConfig(array(
            'foobar' => array(
                $linkDef,
            ),
        )));

        $def = $factory->getResourceDefinition('foobar');
        $this->assertInstanceOf('Hateoas\Factory\Definition\ResourceDefinition', $def);
        $this->assertEquals('foobar', $def->getClass());

        $links = $def->getLinks();
        $this->assertCount(1, $links);
        $this->assertInstanceOf('Hateoas\Factory\Definition\RouteLinkDefinition', $links[0]);
        $this->assertEquals('foo', $links[0]->getRel());
        $this->assertEquals('bar', $links[0]->getType());
        $this->assertEquals('foo.bar', $links[0]->getRoute());

        $this->assertSame($linkDef, $links[0]);
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage A link definition should define a "route" value.
     */
    public function testGetResourceDefinitionWithoutRoute()
    {
        $factory = new RouteAwareFactory(new ArrayConfig(array(
            'foobar' => array(
                array('rel' => 'foo', 'type' => 'bar')
            ),
        ), array()));

        $factory->getResourceDefinition('foobar');
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage A link definition should define a "rel" value.
     */
    public function testGetResourceDefinitionWithoutRel()
    {
        $factory = new RouteAwareFactory(new ArrayConfig(array(
            'foobar' => array(
                array('route' => 'foo', 'type' => 'bar')
            ),
        ), array()));

        $factory->getResourceDefinition('foobar');
    }
}

Add tests for the RouteAwareFactory

Add tests for the RouteAwareFactory


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

namespace Darvin\BotDetectorBundle\DataFixtures\ORM\DetectedBot;

use Darvin\BotDetectorBundle\Entity\DetectedBot;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Faker\Factory;
use Faker\Generator;
use Vipx\BotDetect\Metadata\MetadataInterface;

/**
 * Detected bot data fixture
 */
class LoadDetectedBotData implements FixtureInterface
{
    const COUNT = 100;

    /**
     * @var array
     */
    private static $botTypes = array(
        MetadataInterface::TYPE_BOT,
        MetadataInterface::TYPE_CRAWLER,
        MetadataInterface::TYPE_RSS,
        MetadataInterface::TYPE_SPAMBOT,
        MetadataInterface::TYPE_SPIDER,
        MetadataInterface::TYPE_VALIDATOR,
    );

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $faker = Factory::create();

        for ($i = 0; $i < self::COUNT; $i++) {
            $manager->persist($this->createDetectedBot($faker));
        }

        $manager->flush();
    }

    /**
     * @param \Faker\Generator $faker Faker
     *
     * @return \Darvin\BotDetectorBundle\Entity\DetectedBot
     */
    private function createDetectedBot(Generator $faker)
    {
        $detectedBot = new DetectedBot();
        $detectedBot->setBotType(self::$botTypes[array_rand(self::$botTypes)]);
        $detectedBot->setDate($faker->dateTimeThisYear);
        $detectedBot->setIp($faker->ipv4);
        $detectedBot->setResponseCode($faker->numberBetween(100, 511));
        $detectedBot->setUrl($faker->url);

        return $detectedBot;
    }
}

Implement detected bot data fixture.

Implement detected bot data fixture.


<?php

namespace duncan3dc\Exceptions;

class Catcher
{
    /**
     * @param \Throwable[] $exceptions An array of caught exceptions.
     */
    private $exceptions = [];

    /**
     * Run some code and catch any exceptions thrown.
     *
     * The exception will be stored to be thrown later.
     *
     * @param callable $code The code to be run
     *
     * @return mixed The return value of the callable is passed back, or null if an exception was thrown
     */
    public function try(callable $code)
    {
        try {
            return $code();
        } catch (\Exception $e) {
            $this->exceptions[] = $e;
        } catch (\Throwable $e) {
            $this->exceptions[] = $e;
        }
    }

    /**
     * Get any caught exceptions.
     *
     * @return \Throwable[]
     */
    public function getExceptions()
    {
        return $this->exceptions;
    }

    /**
     * Discard any caught exceptions.
     *
     * @return void
     */
    public function clear()
    {
        $this->exceptions = [];
    }

    /**
     * Throw any caught exceptions.
     *
     * @return void
     */
    public function throw()
    {
        if (count($this->exceptions) < 1) {
            return;
        }

        $finalException = array_pop($this->exceptions);

        foreach ($this->exceptions as $key => $e) {
            echo $e->__toString();
            unset($this->exceptions[$key]);
        }

        throw $finalException;
    }

    /**
     * Ensure any caught exceptions are thrown.
     */
    public function __destruct()
    {
        $this->throw();
    }
}

Create a basic catcher class

Create a basic catcher class


<?php
/*
* This file is part of pssht.
*
* (c) François Poirotte <clicky@erebot.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Clicky\Pssht;

/**
 * Runtime "patches" for PHP.
 */
class Patches
{
    /**
     * Apply runtime patches to PHP.
     */
    public static function apply()
    {
        if (!defined('MCRYPT_MODE_CTR')) {
            define('MCRYPT_MODE_CTR', 'ctr');
        }
    }
}

Add missing file from previous commit.

Add missing file from previous commit.


<?php

  include "init.inc";

  import_request_variables("cpg","rvar_");

  header('Cache-Control: max-age=0, must-revalidate, no-cache, no-store');
  header('Content-Type: text/plain');

  $user = sanitize_word($rvar_user);
  $file = sanitize_path($rvar_file);
  $root_dir = "./db/";

  if(!is_dir("$root_dir$user")) {
    header('HTTP/1.0 404 Not Found');
    die;
  }

  if(!is_file("$root_dir$user/$file")) {
    header('HTTP/1.0 404 Not Found');
    die;
  }

  readfile("$root_dir$user/$file");

?>

Send via code, not direct through apache.


<?php

namespace Leezy\PheanstalkBundle\Command;

use Leezy\PheanstalkBundle\Proxy\PheanstalkProxy;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class KickJobCommand extends ContainerAwareCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('leezy:pheanstalk:kick-job')
            ->addArgument('job', InputArgument::REQUIRED, 'The job to kick.')
            ->addArgument('pheanstalk', InputArgument::OPTIONAL, 'Pheanstalk name.')
            ->setDescription('Kick the specified job if it has a valid buried status, regardless of what tube it is in.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $jobId = $input->getArgument('job');
        $pheanstalkName = $input->getArgument('pheanstalk');

        $pheanstalkLocator = $this->getContainer()->get('leezy.pheanstalk.pheanstalk_locator');
        $pheanstalk = $pheanstalkLocator->getPheanstalk($pheanstalkName);

        if (null === $pheanstalkName) {
            $pheanstalkName = 'default';
        }

        if (null === $pheanstalk) {
            $output->writeln('Pheanstalk not found : <error>' . $pheanstalkName . '</error>');
            return;
        }

        if (!$pheanstalk->getPheanstalk()->getConnection()->isServiceListening()) {
            $output->writeln('Pheanstalk not connected : <error>' . $pheanstalkName . '</error>');
            return;
        }

        try
        {
            $job = $pheanstalk->peek($jobId);
            $pheanstalk->kickJob($job);

            $output->writeln('Pheanstalk : <info>' . $pheanstalkName . '</info>');
            $output->writeln(sprintf('The job #%d has been kicked.', $jobId));

        }
        catch(Pheanstalk_Exception_PheanstalkException $e)
        {
            $output->writeln('Pheanstalk : <info>' . $pheanstalkName . '</info>');
            $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
        }
    }
}

Add a command to kick a specific job id

Add a command to kick a specific job id


<?php
header('Content-Type: application/xml; charset=utf-8'); // Necessary to do “real” XHTML.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<title>An XHTML 1.0 Strict standard template</title>

     <textarea />

Load via instantclick.

Hovering over the link gives an error. This XHTML business is madness, so this won’t get fixed.

Add (failed) test for XHTML

Add (failed) test for XHTML


<?php
namespace Trackops;

use Trackops\Api\GuzzleRequest;

class Trackops
{
    protected $subdomain;

    protected $username;

    protected $token;

    public function __construct($subdomain, $username, $token)
    {
        $this->subdomain = $subdomain;
        $this->username = $username;
        $this->token = $token;
    }

    public function createRequest()
    {
        return new GuzzleRequest($this->subdomain, $this->username, $this->token);
    }
}

Add base class to capture credentials once


Add a PHP script to handle form submissions.


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\DoctrineBundle\Command;

use Doctrine\ORM\Mapping\MappingException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Show information about mapped entities
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
class InfoDoctrineCommand extends DoctrineCommand
{
    protected function configure()
    {
        $this
            ->setName('doctrine:mapping:info')
            ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command.')
            ->setDescription('Show basic information about all mapped entities.')
            ->setHelp(<<<EOT
The <info>doctrine:mapping:info</info> shows basic information about which
entities exist and possibly if their mapping information contains errors or not.

  <info>./app/console doctrine:mapping:info</info>

If you are using multiple entitiy managers you can pick your choice with the <info>--em</info> option:

  <info>./app/console doctrine:mapping:info --em=default</info>
EOT
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $entityManagerName = $input->getOption('em') ?
            $input->getOption('em') :
            $this->container->getParameter('doctrine.orm.default_entity_manager');
-
        $entityManagerService = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName);

        /* @var $entityManager Doctrine\ORM\EntityManager */
        $entityManager = $this->container->get($entityManagerService);

        $entityClassNames = $entityManager->getConfiguration()
                                          ->getMetadataDriverImpl()
                                          ->getAllClassNames();

        $output->write(sprintf("Found %d entities mapped in entity manager '%s':",
            count($entityClassNames), $entityManagerName), true);

        foreach ($entityClassNames AS $entityClassName) {
            try {
                $cm = $entityManager->getClassMetadata($entityClassName);
                $output->write("<info>[OK]</info>   " . $entityClassName, true);
            } catch(MappingException $e) {
                $output->write("<error>[FAIL]</error> " . $entityClassName, true);
                $output->write("<comment>" . $e->getMessage()."</comment>", true);
                $output->write("", true);
            }
        }
    }
}

[DoctrineBundle] Add new Command doctrine:mapping:info that allows to check what entities are mapped and if their metadata is specified correctly. Added exception when a mapping/bundle directory does not exist.


<?php

namespace Commands;

use Telegram\Bot\Commands\Command;
use Base\DB;
use Base\Meetup;
/**
 * Class ShareCommand.
 */
class ShareCommand extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'share';

    /**
     * @var string Command Description
     */
    protected $description = 'Share your tokens with another person';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        $message = $this->update->getMessage();

        $reply_markup = Keyboard::make([
            'force_reply' => true
        ]);

        $this->telegram->sendMessage([
            'chat_id' => $this->update->getMessage()->getFrom()->getId(),
            'text' => 'Share the <code>@username</code> or contact of telegram account of person when you want share yours tokens.',
            'reply_markup' => $reply_markup,
            'parse_mode' => 'html'
        ]);
    }
}

Add start of implementation of Share command


<?php
/**
 * Kenjis.Contact
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2014 Kenji Suzuki
 * @link       https://github.com/kenjis/Kenjis.Contact
 */

namespace Kenjis\Contact\Resource\Page;

use BEAR\Resource\ResourceObject;
use Ray\Di\Di\Inject;
use Kenjis\Contact\Service\SwiftMailerFactory;

class Contact extends ResourceObject
{
    /**
     * @Inject
     */
    public function __construct(SwiftMailerFactory $mailer)
    {
        $this->mailer = $mailer;
    }

    public function onGet()
    {
        $data = [
            'name'    => 'BEAR.Sunday',
            'email'   => 'bear@example.jp',
            'comment' => 'テストメールです。',
        ];

        $mailer = $this->mailer->create();
        $mailer->setSubject('テストメール')
            ->setFrom($data['email'], $data['name'])
            ->setTo('admin@example.org', '管理者')
            ->setTemplate('mailer/contact_form.twig', $data);

        echo '<pre>'
            . htmlspecialchars($mailer, ENT_QUOTES, 'UTF-8')
            . '</pre>';

        $result = $mailer->send();
        return (string) $result;
    }
}

Add a page resource for sending mail test


<?php

namespace Bolt\Provider;

use Bolt\Database\LoggerHandler;
use Monolog\Logger;
use Silex\Application;
use Silex\ServiceProviderInterface;

/**
 * Monolog provider for Bolt system logging entries
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class LoggerSystemServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['logger.system'] = $app->share(function ($app) {
            $log = new Logger('logger.system');

            $log->pushHandler(new LoggerHandler($app, 'system'));

            return $log;
        });
    }

    public function boot(Application $app)
    {
    }
}

Add a system level logging service provider


<?php
namespace Bolt\Extensions\TestVendor\TestExt;

class GumLeaves
{
    protected $dropBear = 'Koala Power!';

    public function __construct()
    {
    }

    public function getDropBear()
    {
        return $this->dropBear;
    }
}

[Tests] Add a namespaced class to testvendor/testext


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')) || PHP_SAPI === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Use PHP_SAPI instead of php_sapi_name()

Use PHP_SAPI instead of php_sapi_name()


<?php
namespace ProjectRena\Task;

use ProjectRena\RenaApp;
use Cilex\Command\Command;
use ProjectRena\Lib;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use ZMQ;
use ZMQContext;

/**
 * Receives killmail data from stomp
 */
class StompReceiveTask extends Command
{

    /**
     */
    protected function configure()
    {
        $this->setName('stomp:run')->setDescription('Receives killmail data from stomp');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        //Init rena
        $app = RenaApp::getInstance();

        $run = true;
        $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp"));
        $stomp->subscribe("/topic/kills", array("id" => "projectRena", "persistent" => "true", "ack" => "client", "prefetch-count" => 1));

        do
        {
            $frame = $stomp->readFrame();

            if(!empty($frame))
            {
                $killdata = json_decode($frame->body, true);
                if(!empty($killdata))
                {
                    if(isset($killdata["_stringValue"]))
                        unset($killdata["_stringValue"]);

                    // Fix the killID
                    $killdata["killID"] = (int) $killdata["killID"];

                    $json = json_encode($killdata);
                    $hash = hash("sha256", ":" . $killdata["killTime"] . ":" . $killdata["solarSystemID"] . ":" . $killdata["moonID"] . "::" . $killdata["victim"]["characterID"] . ":" . $killdata["victim"]["shipTypeID"] . ":" . $killdata["victim"]["damageTaken"] . ":");

                    $inserted = $app->Db->execute("INSERT IGNORE INTO killmails (killID, hash, source, kill_json) VALUES (:killID, :hash, :source, :kill_json)", array(":killID" => $killdata["killID"], ":hash" => $hash, ":source" => "stomp", ":kill_json" => $json));
                    if($inserted > 0)
                    {
                        // Push it over zmq to the websocket
                        $context = new ZMQContext();
                        $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena");
                        $socket->connect("tcp://localhost:5555");
                        $socket->send($json);

                        $app->StatsD->increment("stompReceived");
                    }
                }
                $stomp->ack($frame->headers["message-id"]);
            }
        } while($run == true);
    }
}

Add the stomp receive task.. too many tasks to run now.. way too many.. fuck


Add new changes from jedi academy

Add new changes from jedi academy

Master


<?php

namespace Bolt\Composer\Action;

class DumpAutoload
{
    /**
     * @param $io       Composer\IO\BufferIO
     * @param $composer Composer\Composer
     * @param $options  array
     */
    public function __construct($io, $composer, $options)
    {
        $this->options = $options;
        $this->io = $io;
        $this->composer = $composer;
    }

    /**
     * Dump autoloaders
     */
    public function execute()
    {
        $installationManager = $this->composer->getInstallationManager();
        $localRepo = $this->composer->getRepositoryManager()->getLocalRepository();
        $package = $this->composer->getPackage();
        $config = $this->composer->getConfig();

        if ($this->options['optimizeautoloader']) {
            // Generating optimized autoload files
        } else {
            // Generating autoload files
        }

        $generator = $this->composer->getAutoloadGenerator();
        $generator->setDevMode(!$this->options['nodev']);
        $generator->dump($config, $localRepo, $package, $installationManager, 'composer', $this->options['optimizeautoloader']);
    }
}

Add Composer class to dump autoloader

Add Composer class to dump autoloader


<?php

namespace Bolt\Database\Migration\Input;

use Bolt\Database\Migration\Import;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Interface for migration import files
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
interface InputFileInterface
{
    /**
     * Constructor.
     *
     * @param Import       $import
     * @param \SplFileInfo $file
     */
    public function __construct(Import $import, \SplFileInfo $file);

    /**
     * Read an import file.
     *
     * @return string
     */
    public function readFile();
}

Add interface for migration import files


<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

	$log->pushHandler(new StreamHandler('php://stdout', Logger::WARNING));

	if(empty($username)) {
		$log->addError("Empty username, please fill one.");
		exit;
	}

	$cache_keys = array(
		'artist_data' => 'artist.data.',
	);
	$cache_expiration_time = 60*60*24*7;

// 	$artist_data = $cache->get($cache_keys['artist_data'] . $username);
	$artist_data = FALSE;
	if(!empty($artist_data)) {
		$log->addInfo("The user is on the cache.");
		$data = get_streamchart_data($artist_data);
		echo json_encode($data['data']);
		exit;
	}

	$from_ts = strtotime("2014-01-01");
	$to_ts = strtotime("2015-12-01");

	$log->addInfo("The user is NOT on the cache, retrieving...");
	$last_stream = new LastStream($cache, $last_fm_key, $last_fm_secret);
	$artist_data = $last_stream->get_artist_data($username, $from_ts, $to_ts);

	$cache->put($cache_keys['artist_data'] . $username, $artist_data, $cache_expiration_time);
	$log->addInfo("Done");
// 	echo json_encode(get_streamchart_data($artist_data));
	exit;

	function get_streamchart_data($artist_data) {
		$date_data = array();
		$stream_chart_data = array(
			'fields' => array(),
			'data' => array(),
			'options' => array(
				'chart_types' => array(),
				'colors' => array(),
				'timeFormat' => "unix-timestamp",
				'dataFrequency' => 'hourly'	//TODO: change to 'weekly'
			)
		);

		foreach($artist_data AS $name => $artist_data_points) {
			$stream_chart_data['fields'][] = $name;
			$stream_chart_data['options']['chart_types'][] = 'streamGraph';

			$ts_data = array();
			foreach($artist_data_points AS $data_point) {
				$date_data[$data_point['date']][$name] = (int)$data_point['count'];
			}
		}

		ksort($date_data);

		foreach($date_data AS $ts => $artists) {
// 			foreach($stream_chart_data['fields'] AS $artist) {
// 				if(!isset($artists[$artist])) {
// 					$artists[$artist] = 0;
// 				}
// 			}
			$stream_chart_data['data'][] = array('date' => $ts, 'data' => $artists);
		}
		return $stream_chart_data;
	}

Add first cli controller for retrieving a user's info.


<?php
namespace Icicle\Benchmarks\Concurrent;

use Athletic\AthleticEvent;

/**
 * Profiles sending and receiving serialized data across a local TCP socket.
 */
class SocketPairEvent extends AthleticEvent
{
    private $sockets;

    public function classSetUp()
    {
        $this->sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
    }

    public function classTearDown()
    {
        fclose($this->sockets[0]);
        fclose($this->sockets[1]);
    }

    /**
     * @iterations 1000
     */
    public function writeBool()
    {
        $this->write(true);
        $this->read();
    }

    /**
     * @iterations 1000
     */
    public function writeInt()
    {
        $this->write(2);
        $this->read();
    }

    /**
     * @iterations 1000
     */
    public function writeString()
    {
        $this->write('world');
        $this->read();
    }

    /**
     * @iterations 1000
     */
    public function writeObject()
    {
        $this->write(new \stdClass());
        $this->read();
    }

    private function read()
    {
        $buffer = '';

        while (true) {
            $char = fgetc($this->sockets[1]);
            if ($char !== chr(0)) {
                $buffer .= $char;
            }
            break;
        }

        return unserialize($buffer);
    }

    private function write($value)
    {
        fwrite($this->sockets[0], serialize($value) . chr(0));
    }
}

Add benchmark for socket pairs

Add benchmark for socket pairs


<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

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

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

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }
}

Test that you need to be authenticated to edit a tag


<?php

/*
    Copyright (c) 2012 - 2013, Open Source Solutions Limited, Dublin, Ireland
    All rights reserved.

    Contact: Barry O'Donovan - barry (at) opensolutions (dot) ie
    http://www.opensolutions.ie/

    This file is part of the OSS_SNMP package.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Open Source Solutions Limited 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Following block works with sysDescr such as:
//
// 'FS728TP'

// THIS IS JUST FOR TESTING AGAINST A SHITE SWITCH IN THE OFFICE
//
// DO NOT USE THIS AS A TEMPLATE!!!

if( $sysDescr == 'FS728TP' )
{
    preg_match( '/LX Console Manager,\ss\/w\sversion=([0-9a-zA-Z\.]+)$/',
            $sysDescr, $matches );

    $this->setVendor( 'Netgear' );
    $this->setModel( $sysDescr );
    $this->setOs( 'Netgear' );
    $this->setOsVersion( $this->getSNMPHost()->get( '.1.3.6.1.4.1.4526.17.2.4.0' ) );
    $this->setOsDate( null );
}

Test vendor file for Netgear

[IM] Test vendor file for Netgear

We have two of these shite switches in the office and this
is purely for development / testing purposes. This should
not be used as a template for other vendor files!


<?php

namespace Analog\Handler;

/**
 * Send the log message to the specified email address using WordPress wp_mail.
 *
 * You can also specify a template in your theme to style how the email looks like.
 *
 * Usage:
 *
 *     Analog::handler (Analog\Handler\WPMail::init (
 *         'you@example.com',       // to
 *         'Subject line',          // subject
 *         'no-reply@example.com',  // from
 *         'log-email-template.php' // email template in theme
 *     ));
 */
class WPMail {
	public static function init ($to, $subject, $from, $template='') {
		return function ($info, $buffered = false) use ($to, $subject, $from, $template) {
			$body = ($buffered)
				? "Logged:\n" . $info
				: vsprintf ("Machine: %s\nDate: %s\nLevel: %d\nMessage: %s", $info);

			$log_template = locate_template( $template );

			if ( ! empty( $log_template ) ) {
				ob_start();
				include_once $log_template;
				$body = ob_get_clean();
			} else {
				$body = wordwrap( $body, 70 );
			}

			add_filter( 'wp_mail_content_type', array( __CLASS__, 'set_email_content_type' ) );

			wp_mail( $to, $subject, $body );

			remove_filter( 'wp_mail_content_type', array( __CLASS__, 'set_email_content_type' ) );

		};
	}

	public static function set_email_content_type() {
		return 'text/html';
	}
}

Add Handler for sending emails from WordPress


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Service / SearchImage
 */

namespace PH7\Test\Unit\Framework\Security;

use PH7\Framework\Service\SearchImage\Google as GoogleImage;
use PH7\Framework\Service\SearchImage\Url as ImageUrl;
use PHPUnit_Framework_TestCase;

class GoogleTest extends PHPUnit_Framework_TestCase
{
    /** @var GoogleImage */
    private $oGoogleImage;

    protected function setUp()
    {
        $oUrl = new ImageUrl('http://localhost/data/system/modules/user/avatar/img/paul/8-400.jpg');
        $this->oGoogleImage = new GoogleImage($oUrl);
    }

    public function testProviderLink()
    {
        $sExpectedUrl = 'https://www.google.com/searchbyimage?image_url=';
        $this->assertSame($sExpectedUrl, $this->oGoogleImage->getProviderUrl());
    }

    public function testSearchImageUrl()
    {
        $sExpectedUrl = 'https://www.google.com/searchbyimage?image_url=http%3A%2F%2Flocalhost%2Fdata%2Fsystem%2Fmodules%2Fuser%2Favatar%2Fimg%2Fpaul%2F8-400.jpg';
        $this->assertSame($sExpectedUrl, $this->oGoogleImage->getSearchImageUrl());
    }
}

Add unit tests for SearchImage

Add unit tests for SearchImage


<?php

use SlimController\SlimController;
use rmatil\cms\Constants\HttpStatusCodes;
use rmatil\cms\Entities\User;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\DBALException;
use DateTime;

class RegistrationController extends SlimController {

    public function updateUserAction() {
        // if ($userObject->getPlainPassword() === null ||
        //     $userObject->getPlainPassword() === '') {
        //     $now = new DateTime();
        //     $this->app->log->error(sprintf('[%s]: %s', $now->format('d-m-Y H:i:s'), 'Ein Passwort muss angegeben werden'));
        //     $this->app->response->setStatus(HttpStatusCodes::CONFLICT);
        //     return;
        // } else {
        //     // hash provided plaintext password
        //     if (function_exists('password_hash')) {
        //         $hash = password_hash($userObject->getPlainPassword(), PASSWORD_DEFAULT);
        //     } else {
        //         $hash = hash('sha512', sprintf("%s", $userObject->getPlainPassword()));
        //     }

        //     $userObject->setPasswordHash($hash);
        // }
    }
}

Add stub for registration controller

Add stub for registration controller


<?php
/**
 * Created by PhpStorm.
 * User: thomas
 * Date: 31/05/15
 * Time: 17:05
 */

namespace BitWasp\Bitcoin\Tests\JsonRpc;

use BitWasp\Bitcoin\JsonRpc\JsonRpcClient;
use BitWasp\Bitcoin\Tests\AbstractTestCase;

class JsonRpcTest extends AbstractTestCase
{
    public function getResult()
    {
        return [
            [
                1,
                ['error' => ['code'=> 1, 'message' => '']]
            ],
            [
                1,
                ['error' => ['code'=> -32601, 'message' => '']]
            ],
            [
                1,
                ['error' => ['code'=> -32601, 'message' => '']]
            ],
            [
                0,
                ['result' => []]
            ],
        ];
    }

    /**
     * @dataProvider getResult
     * @param $payload
     */
    public function testGetResult($flag, $payload)
    {
        $json = new JsonRpcClient('127.0.0.1', 99999);
        if ($flag == 1) {
            try {
                $json->getResult($payload);
                $this->fail('very fail');
            } catch (\Exception $e) {
                $this->assertTrue(!!$e);
            }
            // should fail
        } else {
            try {
                $result = $json->getResult($payload);
            } catch (\Exception $e) {
                $this->fail('very fail');
            }
            $this->assertTrue(!isset($e));
            // should produce array
        }
    }
}

Add json RPC test to cover our additions


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

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

# Vendor Ricoh

$get_oid_details = function ($ip, $credentials, $oid) {
    $details = new stdClass();
    $details->type = 'router';
    $details->manufacturer = 'Vyatta';
    $details->model = 'Vyatta Router';
    $details->os_group = 'Vyatta';
    $details->os_family = 'Vyatta VyOS';
    $details->os_name = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.1.0");
    $details->os_version = str_replace('Vyatta VyOS ', '', $details->os_name);
    $details->hostname = my_snmp_get($ip, $credentials, '1.3.6.1.2.1.1.5.0');
    return($details);
};

Add SNMP helper for Vyatta.

Add SNMP helper for Vyatta.


<?php
/**
 * ownCloud
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Pellaeon Lin <pellaeon@cnmc.tw>
 * @copyright Pellaeon Lin, 2014
 */

namespace OCA\Registration\Wrapper;

class Mail {

	/**
	 * send an email
	 * @param string $toaddress
	 * @param string $toname
	 * @param string $subject
	 * @param string $mailtext
	 * @param string $fromaddress
	 * @param string $fromname
	 * @param int $html
	 * @param string $altbody
	 * @param string $ccaddress
	 * @param string $ccname
	 * @param string $bcc
	 */
	public function sendMail( $toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
		$html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
			// call the internal mail class
			\OCP\Util::sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
				$html, $altbody, $ccaddress, $ccname, $bcc);
		}
}

Add Mail wrapper for public API

Add Mail wrapper for public API


<?php

namespace Rainbow\Tests\Converter;

use Rainbow\Converter\RgbToHexConverter;
use Rainbow\Hex;
use Rainbow\Rgb;

class RgbToHexConverterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider colorDataProvider
     * @param $expected
     * @param $color
     */
    public function testConvertShouldReturnSameColor($expected, $color)
    {
        $converter = new RgbToHexConverter($color);

        $this->assertEquals($expected, $converter->convert());
    }

    public function colorDataProvider()
    {
        return array(
            array(new Hex("#000000"), new Rgb(0, 0, 0)),
            array(new Hex("#ff0000"), new Rgb(255, 0, 0)),
            array(new Hex("#00ff00"), new Rgb(0, 255, 0)),
            array(new Hex("#0000ff"), new Rgb(0, 0, 255)),
            array(new Hex("#3296fa"), new Rgb(50, 150, 250)),
        );
    }
}

Test rgb to hex conversions

Test rgb to hex conversions


<?php

$title_singular = 'Address';
$title_plural = 'Addresses';
$table_name = 'Address';
$table_name_lower = 'track';
$reference_implementation = 'http://www.php-intro.com/exams/fin-f15-address';

$fields = array(
    array('Name', 'name', false),
    array('Address', 'addr', false),
    array('City', 'city', false),
    array('State', 'state', 2, 2,10),
    array('Zip', 'zip', 'i',false,10)
);

require_once "final.php";

Move all the files under docs

Move all the files under docs


<?php

namespace Inventory\Model\Validate;

use Zend\Validator\AbstractValidator;
use Zend\Validator\Regex;

class SearchPattern extends AbstractValidator
{
    public function isValid($value)
    {
        $val = new Regex(array('pattern'=>'/[\s\S]*?/i'));
        if (!$val->isValid($value))
			return false;

        return true;
    }
}

Revert "Tue Aug 13 23:09:09 MDT 2013"

Revert "Tue Aug 13 23:09:09 MDT 2013"

This reverts commit 5679872f4e219e6e4fd57a265cb1e2f65ee2b81f.


<?php
/**
 * Test the GeometryBuilder class
 * @author  Rob Ingram <robert.ingram@ccc.govt.nz>
 */
require_once 'src/GeoJSON/GeometryBuilder.php';
use PHPUnit\Framework\TestCase;

class GeometryBuilderTest extends TestCase
{
  /**
   * Parameters to conversion
   * @var array
   */
  protected $params = [
    'geom' => [
      'Point' => ['lat', 'lng']
    ]
  ];

  /**
   * test that the goemetry is built correctly from the source data
   * @param  array $source   Source object containing geometry in generic formats
   * @param  array $expected Expected converted value
   * @dataProvider geometryDataProvider
   */
  public function testItBuildsGeometry($source, $expected)
  {
    $builder = new GeoJSON\GeometryBuilder($this->params);
    $result = $builder->build($source);

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

  /**
   * Provide data for `testitBuildsGeometry`
   * @return array
   */
  public function geometryDataProvider()
  {
    return [
      [
        ['name' => 'Location A', 'category' => 'Store', 'lat' => 39.984, 'lng' => -75.343, 'street' => 'Market'],
        [
          'type' => 'Point',
          'coordinates' => [
            -75.343,
            39.984,
          ]
        ],
        ['name' => 'Location B', 'category' => 'House', 'lat' => 39.284, 'lng' => -75.833, 'street' => 'Broad'],
        [
          'type' => 'Point',
          'coordinates' => [
            -75.343,
            39.984,
          ]
        ],
        ['name' => 'Location C', 'category' => 'Office', 'lat' => 39.123, 'lng' => -74.534, 'street' => 'South'],
        [
          'type' => 'Point',
          'coordinates' => [
            -75.343,
            39.984,
          ]
        ],
      ],
    ];
  }
}

Add point tests for geometry builder

Add point tests for geometry builder


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

namespace Zend\Validator;

use Traversable;
use Zend\Stdlib\ArrayUtils;
use Zend\Validator\AbstractValidator;

class IsInstanceOf extends AbstractValidator
{

    const NOT_INSTANCE_OF = 'notInstanceOf';

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $messageTemplates = array(
        self::NOT_INSTANCE_OF => "The input is not an instance of '%className%'"
    );

    /**
     * Additional variables available for validation failure messages
     *
     * @var array
     */
    protected $messageVariables = array(
        'className' => 'className'
    );

    /**
     * Class name
     *
     * @var string
     */
    protected $className;

    /**
     * Sets validator options
     *
     * @param  array|Traversable $options
     * @throws Exception\InvalidArgumentException
     */
    public function __construct($options = null)
    {
        if ($options instanceof Traversable) {
            $options = ArrayUtils::iteratorToArray($options);
        }
        if (!is_array($options)) {
            $options = func_get_args();

            $tmpOptions = array();
            $tmpOptions['classname'] = array_shift($options);

            $options = $tmpOptions;
        }

        if (!array_key_exists('className', $options)) {
            throw new Exception\InvalidArgumentException("Missing option 'className'");
        }

        $this->setClassName($options['className']);

        parent::__construct($options);
    }

    /**
     * Get class name
     *
     * @return string
     */
    public function getClassName()
    {
        return $this->className;
    }

    /**
     * Set class name
     *
     * @param  string $className
     * @return self
     */
    public function setClassName($className)
    {
        $this->className = $className;
        return $this;
    }

    /**
     * Returns true if $value is instance of $this->className
     *
     * @param  mixed $value
     * @return boolean
     */
    public function isValid($value)
    {
        if($value instanceof $this->className) {
            return true;
        }
        $this->error(self::NOT_INSTANCE_OF);
        return false;
    }
}

Add new validator to check if input is instance of a certain class

Change-Id: I6365cf9a6652ca42a1f6897002e5abe455ed4f44


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / Include / Class
 */

namespace PH7;

class DbTableNameName
{
    const ADMIN = 'admins';

}

Add class to store DB table names

Add class to store DB table names


<?php

namespace Tests\Regis\Application\CommandHandler\Webhook;

use Regis\Application\Repository\Repositories;
use Regis\Application\Command;
use Regis\Application\CommandHandler;
use Regis\Application\Entity;
use Regis\Github\Client as GithubClient;

class CreateTest extends \PHPUnit_Framework_TestCase
{
    private $githubClient;
    private $repositoriesRepo;
    /** @var CommandHandler\Webhook\Create */
    private $handler;

    public function setUp()
    {
        $this->githubClient = $this->getMockBuilder(GithubClient::class)->disableOriginalConstructor()->getMock();
        $this->repositoriesRepo = $this->getMockBuilder(Repositories::class)->getMock();

        $this->handler = new CommandHandler\Webhook\Create($this->githubClient, $this->repositoriesRepo);
    }

    public function testItCallsGithub()
    {
        $command = new Command\Webhook\Create('K-Phoen', 'test', 'http://callback.url');
        $repository = $this->getMockBuilder(Entity\Repository::class)->getMock();
        $repository->expects($this->once())
            ->method('getSharedSecret')
            ->will($this->returnValue('shared secret'));

        $this->repositoriesRepo->expects($this->once())
            ->method('find')
            ->with('K-Phoen/test')
            ->will($this->returnValue($repository));

        $this->githubClient->expects($this->once())
            ->method('createWebhook')
            ->with('K-Phoen', 'test', 'http://callback.url', 'shared secret');

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

Add test for the Webhook Create command

Add test for the Webhook Create command


<?php

namespace Zend\Http\PhpEnvironment;

use Zend\Http\Response as HttpResponse,
    Zend\Stdlib\Parameters;

class Response extends HttpResponse
{
    protected $headersSent = false;

    protected $contentSent = false;

    public function __construct()
    {
    }

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

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

    public function sendHeaders()
    {
        if ($this->headersSent()) {
            return;
        }

        $version = $this->getVersion();
        $code    = $this->getStatusCode();
        $message = $this->getReasonPhrase();
        $status  = sprintf('HTTP/%s %d %s', $version, $code, $message);
        header($status);

        foreach ($this->headers() as $header) {
            header($header->toString());
        }

        $this->headersSent = true;
        return $this;
    }

    public function sendContent()
    {
        if ($this->contentSent()) {
            return;
        }
        echo $this->getContent();
        $this->contentSent = true;
        return $this;
    }

    public function send()
    {
        $this->sendHeaders()
             ->sendContent();
        return $this;
    }

}

<?php

namespace Zend\Http\PhpEnvironment;

use Zend\Http\Header\MultipleHeaderDescription,
    Zend\Http\Response as HttpResponse,
    Zend\Stdlib\Parameters;

class Response extends HttpResponse
{
    protected $headersSent = false;

    protected $contentSent = false;

    public function __construct()
    {
    }

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

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

    public function sendHeaders()
    {
        if ($this->headersSent()) {
            return;
        }

        $version = $this->getVersion();
        $code    = $this->getStatusCode();
        $message = $this->getReasonPhrase();
        $status  = sprintf('HTTP/%s %d %s', $version, $code, $message);
        header($status);

        foreach ($this->headers() as $header) {
            if ($header instanceof MultipleHeaderDescription) {
                header($header->toString(), false);
                continue;
            }
            header($header->toString());
        }

        $this->headersSent = true;
        return $this;
    }

    public function sendContent()
    {
        if ($this->contentSent()) {
            return;
        }
        echo $this->getContent();
        $this->contentSent = true;
        return $this;
    }

    public function send()
    {
        $this->sendHeaders()
             ->sendContent();
        return $this;
    }

}

Allow PHP response to send MultipleHeaders safely

- Detect MultipleHeaderDescription
  - when found, pass boolean false as second argument to header()


<?php

namespace Chill\ReportBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class ChillReportExtensionTest extends KernelTestCase
{
    /*
     * Check if class Chill\ReportBundle\Entity\Report is in chill_custom_fields.customizables_entities
     */
    public function testDeclareReportAsCustomizable()
    {
        self::bootKernel(array('environment' => 'test'));
        $customizablesEntities = static::$kernel->getContainer()
                ->getParameter('chill_custom_fields.customizables_entities');

        $reportFounded = false;
        foreach ($customizablesEntities as $customizablesEntity) {
            if($customizablesEntity['class'] === 'Chill\ReportBundle\Entity\Report') {
                $reportFounded = true;
            }
        }

        if(! $reportFounded) {
            throw new Exception("Class Chill\ReportBundle\Entity\Report not found in chill_custom_fields.customizables_entities", 1);
        }
    }
}

Test : Check if class Chill\ReportBundle\Entity\Report is in chill_custom_fields.customizables_entities


<?php

namespace Application\Migrations;

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

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

        $this->addSql('ALTER TABLE items ADD activatedAt DATETIME DEFAULT NULL, ADD deletedAt DATETIME DEFAULT NULL, ADD deleted TINYINT(1) NOT NULL');
    }

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

        $this->addSql('ALTER TABLE items DROP activatedAt, DROP deletedAt, DROP deleted');
    }
}

Add new fields to Item entity

Add new fields to Item entity


<?php

namespace Project\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Project\AppBundle\Entity\Lesson;
use Symfony\Component\HttpFoundation\Response;

/**
 * Archive controller.
 *
 * @Route("/agenda")
 */
class AgendaController extends Controller
{

    /**
     * @Route("/add", name="agenda_add_lesson")
     * @Template()
     * @Method("POST")
     *
     * @return \Symfony\Component\HttpFoundation\Response (bool)
     */
    public function addAction($data)
    {
        // Change return header as json
        $response = new Response(json_encode(true));
        $response->headers->set('Content-Type', 'application/json');

        // Decode received data
        $data = json_decode($data);

        // Convert retrieve data to DateTime to avoid error
        $startDate = new \DateTime($data->startDate);
        $endDate = new \DateTime($data->endDate);

        // Fill the entity and save it
        $entity = new Lesson();
        $em = $this->getDoctrine()->getManager();

        $entity->setName($data->name);
        $entity->setStartDate($startDate);
        $entity->setEndDate($endDate);
        $entity->setTimecard(1);

        $em->persist($entity);
        $em->flush();

        return $response;
    }

    /**
     * @Route("/delete", name="agenda_delete_lesson")
     * @Template()
     * @Method("POST")
     *
     * @return \Symfony\Component\HttpFoundation\Response (bool)
     */
    public function deleteAction($id)
    {
        // Change return header as json
        $response = new Response(json_encode(true));
        $response->headers->set('Content-Type', 'application/json');

        // Execute select to find the Lesson
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('ProjectAppBundle:Lesson')->find($id);

        // Return false if the Lesson doesn't exists else remove it
        if (!$entity) {
            $response = new Response(json_encode(false));
        } else {
            $em->remove($entity);
            $em->flush();
        }

        return $response;
    }
}

Add a controller for Agenda

Add a controller for Agenda


<?php

namespace Frontend\Modules\Tags\Tests\Engine;

use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Tags\Engine\Model;
use Common\WebTestCase;

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

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

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

Add class to test frontend tags model

Add class to test frontend tags model


<?php
/**
 * @file include/environment.php
 * @brief Functions related to system/environment tasks.
 *
 * This file contains some functions to check the environment/system.
 */

/**
 * @brief Get some upload related limits from php.ini.
 *
 * This function returns values from php.ini like \b post_max_size,
 * \b max_file_uploads, \b upload_max_filesize.
 *
 * @return array associative array
 *   * \e int \b post_max_size the maximum size of a complete POST in bytes
 *   * \e int \b upload_max_filesize the maximum size of one file in bytes
 *   * \e int \b max_file_uploads maximum number of files in one POST
 *   * \e int \b max_upload_filesize min(post_max_size, upload_max_filesize)
 */
function getPhpiniUploadLimits() {
	$ret = array();

	// max size of the complete POST
	$ret['post_max_size'] = phpiniSizeToBytes(ini_get('post_max_size'));
	// max size of one file
	$ret['upload_max_filesize'] = phpiniSizeToBytes(ini_get('upload_max_filesize'));
	// catch a configuration error where post_max_size < upload_max_filesize
	$ret['max_upload_filesize'] = min(
			$ret['post_max_size'],
			$ret['upload_max_filesize']
			);
	// maximum number of files in one POST
	$ret['max_file_uploads'] = intval(ini_get('max_file_uploads'));

	return $ret;
}

/**
 * @brief Parses php_ini size settings to bytes.
 *
 * This function parses common size setting from php.ini files to bytes.
 * e.g. post_max_size = 8M ==> 8388608
 *
 * \note This method does not recognise other human readable formats like
 * 8MB, etc.
 *
 * @todo Make this function more universal useable. MB, T, etc.
 *
 * @param string $val value from php.ini e.g. 2M, 8M
 * @return int size in bytes
 */
function phpiniSizeToBytes($val) {
	$val = trim($val);
	$unit = strtolower($val[strlen($val)-1]);
	switch($unit) {
		case 'g':
			$val *= 1024;
		case 'm':
			$val *= 1024;
		case 'k':
			$val *= 1024;
	}

	return (int)$val;
}

Add functions to parse and get some values from php.ini.

Get upload limits from php.ini. These functions will be used for checking
against upload limits and to give information in the frontend.
Wasn't sure in which file to put these functions, so I created a new
one include/environment.php.


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

class ModulesTest extends WebTestCase
{
    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/extensions/modules');

        // we should get redirected to authentication with a reference to blog index in our url
        self::assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fextensions%2Fmodules',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testIndexHasModuels(): void
    {
        $client = static::createClient();
        $this->login($client);

        $client->request('GET', '/private/en/extensions/modules');
        self::assertContains(
            'Installed modules',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Not installed modules',
            $client->getResponse()->getContent()
        );

        self::assertContains(
            'Upload module',
            $client->getResponse()->getContent()
        );

        self::assertContains(
            'Find modules',
            $client->getResponse()->getContent()
        );
    }
}

Add tests for the extentions modules page


<?php

namespace AdobeConnectClient\Traits;

use \AdobeConnectClient\Helper\StringCaseTransform;

trait EntityTrait
{
    /**
     * Set the attributes using an Associative Array
     * @param array $attributes
     */
    public function setAttributes(array $attributes)
    {
        foreach ($attributes as $attr => $value) {
            if (is_array($value)) {
                $this->setAttributes($value);
                continue;
            }
            $attributeSetMethod = 'set' . StringCaseTransform::toUpperCamelCase($attr);

            if (method_exists($this, $attributeSetMethod)) {
                $this->$attributeSetMethod($value);
            }
        }
    }
}

Add a trait to help Entity

Add a trait to help Entity


<?php

namespace AmpProject\Optimizer\Transformer;

use AmpProject\Dom\Document;
use AmpProject\Optimizer\Configuration\RewriteAmpUrlsConfiguration;
use AmpProject\Optimizer\ErrorCollection;
use AmpProject\Optimizer\Exception\InvalidConfiguration;
use AmpProject\Tests\TestCase;

/**
 * Test the RewriteAmpUrls transformer.
 *
 * @covers \AmpProject\Optimizer\Transformer\RewriteAmpUrls
 * @package ampproject/amp-toolbox
 */
final class RewriteAmpUrlsTest extends TestCase
{

    public function testThrowsOnMutuallyExclusiveFlags()
    {
        $this->expectException(InvalidConfiguration::class);
        $this->expectExceptionMessage(
            "The configuration flags 'lts' and 'rtv' are mutually exclusive and cannot be set at the same time."
        );
        $configuration = new RewriteAmpUrlsConfiguration(
            [
                'lts' => true,
                'rtv' => true
            ]
        );

        $transformer = new RewriteAmpUrls($configuration);
        $transformer->transform(new Document(), new ErrorCollection());
    }
}

Add test for mutually exclusive flags

Add test for mutually exclusive flags


<?php include "conf.php"; /* load a local configuration */ ?>
<?php include "modulekit/loader.php"; /* loads all php-includes */ ?>
<?
$f = fopen("http://data.wien.gv.at/daten/geo?service=WFS&request=GetFeature&version=1.1.0&typeName=ogdwien:BAUMOGD&srsName=EPSG:4326&outputFormat=csv&maxFeatures=50", "r");
$headers = fgetcsv($f);

while($r = fgetcsv($f)) {
  $r = array_map("utf8_encode", $r);
  $data = array_combine($headers, $r);
  print_r($data);
}

Load CSV lines from Open Data

Load CSV lines from Open Data


<?php

namespace Tests\Sylake\SyliusConsumerPlugin\Functional;

use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManagerInterface;
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
use PHPUnit\Framework\Assert;
use Sylius\Component\Product\Model\ProductAssociationTypeInterface;
use Sylius\Component\Product\Repository\ProductAssociationTypeRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class AssociationTypeSynchronizationTest extends KernelTestCase
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var ProductAssociationTypeRepositoryInterface
     */
    private $associationTypeRepository;

    /**
     * @var ConsumerInterface
     */
    private $consumer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        self::bootKernel();

        $this->entityManager = static::$kernel->getContainer()->get('doctrine')->getManager();
        $this->associationTypeRepository = static::$kernel->getContainer()->get('sylius.repository.product_association_type');
        $this->consumer = static::$kernel->getContainer()->get('rabbitmq_simplebus.consumer');

        (new ORMPurger($this->entityManager))->purge();
    }

    /**
     * @test
     */
    public function it_adds_new_association_type_from_akeneo_message()
    {
        $this->consumer->execute(new AMQPMessage('{"type":"akeneo_association_type_created","payload":{"code":"SUBSTITUTION","labels":{"de_DE":"Ersatz","en_US":"Substitution","fr_FR":"Remplacement"}},"recordedOn":"2017-05-22 12:51:29"}'));

        /** @var ProductAssociationTypeInterface|null $associationType */
        $associationType = $this->associationTypeRepository->findOneBy(['code' => 'SUBSTITUTION']);

        Assert::assertNotNull($associationType);
        Assert::assertSame('Ersatz', $associationType->getTranslation('de_DE')->getName());
        Assert::assertSame('Substitution', $associationType->getTranslation('en_US')->getName());
        Assert::assertSame('Remplacement', $associationType->getTranslation('fr_FR')->getName());
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        $this->entityManager->clear();
        $this->entityManager = null;
    }
}

Test adding a new association type with translations


<?php
/**
 * BBC_Service_Bamboo_Models_Programme
 *
 *
 * @category BBC
 * @package BBC_Service
 * @subpackage BBC_Service_Bamboo_Models
 * @author Craig Taub <craig.taub@bbc.co.uk>
 * @copyright Copyright (c) 2013 BBC (http://www.bbc.co.uk)
 */
class BBC_Service_Bamboo_Models_Programme extends BBC_Service_Bamboo_Models_Element
{
    // @codingStandardsIgnoreStart
    protected $_initial_child_episodes = array();
    protected $_child_episode_count = 0;
    // @codingStandardsIgnoreEnd

    public function getEpisodeCount()
    {
        // @codingStandardsIgnoreStart
        return $this->_child_episode_count;
        // @codingStandardsIgnoreEnd
    }

    public function getLatestAvailableEpisode()
    {
        // @codingStandardsIgnoreStart
        return $this->_initial_child_episodes[0];
        // @codingStandardsIgnoreEnd
    }
}

<?php
/**
 * BBC_Service_Bamboo_Models_Programme
 *
 *
 * @category BBC
 * @package BBC_Service
 * @subpackage BBC_Service_Bamboo_Models
 * @author Craig Taub <craig.taub@bbc.co.uk>
 * @copyright Copyright (c) 2013 BBC (http://www.bbc.co.uk)
 */
class BBC_Service_Bamboo_Models_Programme extends BBC_Service_Bamboo_Models_Element
{
    // @codingStandardsIgnoreStart
    protected $_initial_child_episodes = array();
    protected $_child_episode_count = 0;
    // @codingStandardsIgnoreEnd

    public function getEpisodeCount()
    {
        // @codingStandardsIgnoreStart
        return $this->_child_episode_count;
        // @codingStandardsIgnoreEnd
    }

    public function getLatestAvailableEpisode()
    {
        if (isset($this->_initial_child_episodes[0])) {
            // @codingStandardsIgnoreStart
            return $this->_initial_child_episodes[0];
            // @codingStandardsIgnoreEnd
        }
        return "";
    }
}

Fix for programme model getLatestAvailEp


<?php

class m130409_175500_drug_table_changes extends CDbMigration {

	public function up() {
		$this->alterColumn('drug','default_route_id','int(10) unsigned DEFAULT NULL');
		$this->alterColumn('drug','default_frequency_id','int(10) unsigned DEFAULT NULL');
		$this->alterColumn('drug','default_duration_id','int(10) unsigned DEFAULT NULL');
		$this->addColumn('drug_route','display_order','int(10) unsigned DEFAULT 0');
	}

	public function down() {
		$this->dropColumn('drug_route','display_order');
		$this->alterColumn('drug','default_route_id','int(10) unsigned NOT NULL');
		$this->alterColumn('drug','default_frequency_id','int(10) unsigned NOT NULL');
		$this->alterColumn('drug','default_duration_id','int(10) unsigned NOT NULL');
	}

}

Allow nullable foreign keys in drug table


<?php

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

namespace Surfnet\Stepup\Tests\Configuration\Value;

use PHPUnit_Framework_TestCase as UnitTest;
use Surfnet\Stepup\Configuration\Value\Institution;

class InstitutionTest extends UnitTest
{
    /**
     * @test
     * @group domain
     * @dataProvider nonStringOrNonEmptyStringProvider
     * @expectedException \Surfnet\Stepup\Exception\InvalidArgumentException
     *
     * @param mixed $invalidValue
     */
    public function an_institution_cannot_be_created_with_anything_but_a_nonempty_string($invalidValue)
    {
        new Institution($invalidValue);
    }

    /**
     * @test
     * @group domain
     */
    public function two_institutions_with_the_same_value_are_equal()
    {
        $institution       = new Institution('a');
        $theSame           = new Institution('a');
        $theSameWithSpaces = new Institution('  a ');
        $different         = new Institution('A');

        $this->assertTrue($institution->equals($theSame));
        $this->assertTrue($institution->equals($theSameWithSpaces));
        $this->assertFalse($institution->equals($different));
    }

    public function nonStringOrNonEmptyStringProvider()
    {
        return [
            'empty string' => [''],
            'blank string' => ['   '],
            'array'        => [[]],
            'integer'      => [1],
            'float'        => [1.2],
            'object'       => [new \StdClass()],
        ];
    }
}

Add test for Institution in Configuration


<?php

namespace Oro\Bundle\LocaleBundle\Form\Type;

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

class CurrencyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'choices' => Intl::getCurrencyBundle()->getCurrencyNames('en'),
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'currency';
    }

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

<?php

namespace Oro\Bundle\LocaleBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Intl\Intl;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CurrencyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'choices' => Intl::getCurrencyBundle()->getCurrencyNames('en'),
                'restrict' => false
            )
        );

        $resolver->setDefined('restrict');
        $resolver->setAllowedTypes('restrict', 'bool');
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'currency';
    }

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

BB-3348: Create validator for System Allowed Currencies restriction


<?php

/**
 * @file
 * Tests for oblist collections.
 */

namespace Itafroma\Zork\Tests;

use Itafroma\Zork\State\Oblist;
use Itafroma\Zork\State\OblistCollection;

class OblistCollectionTest extends ZorkTest
{
    /**
     * Tests Itafroma\Zork\State\OblistCollection::get() when the oblist exists.
     *
     * @covers Itafroma\Zork\State\OblistCollection::get
     * @dataProvider oblistCollectionProvider
     */
    public function testGetOblistExists($oblist_collection, $name, $oblist)
    {
        $this->setPrivateProperty($oblist_collection, 'atoms', [$name => $oblist]);

        $this->assertEquals($oblist, $oblist_collection->get($name));
    }

    /**
     * Tests Itafroma\Zork\State\OblistCollection::get() when the oblist does not exist.
     *
     * @covers Itafroma\Zork\State\OblistCollection::get
     * @dataProvider oblistCollectionProvider
     */
    public function testGetOblistDoesNotExist($oblist_collection, $name)
    {
        $this->assertEquals(null, $oblist_collection->get($name));
    }

    /**
     * Provides data for testing oblist collections.
     */
    public function oblistCollectionProvider()
    {
        return [
            [new OblistCollection(), 'ZorkTest-name', new Oblist()],
        ];
    }
}

Add test coverage for OblistCollection::get().


<?php
namespace Sil\DevPortal\components;

/**
 * Trait to add utility functions for getting a model's errors formatted for
 * various contexts.
 *
 * @author Matt Henderson
 */
trait FormatModelErrorsTrait
{
	public function getErrorsAsFlatHtmlList()
    {
        $modelErrors = $this->getErrors();
        $htmlListItems = array();

        foreach ($modelErrors as $attributeName => $attributeErrors) {
            foreach ($attributeErrors as $attributeError) {
                $htmlListItems[] = sprintf(
                    '
%s
',
                    \CHtml::encode($attributeError)
                );
            }
        }

        return '
' . implode(' ', $htmlListItems) . '
';
    }

    public function getErrorsForConsole()
    {
        $modelErrors = $this->getErrors();
        $output = '';

        foreach ($modelErrors as $attributeName => $attributeErrors) {
            $output .= ' * ' . $attributeName . PHP_EOL;
            foreach ($attributeErrors as $attributeError) {
                $output .= '   - ' . $attributeError . PHP_EOL;
            }
        }

        return $output;
    }

    abstract public function getErrors($attribute = null);
}

Add helper functions (via trait) for formatting model errors.


<?php

namespace UWDOEM\Framework\Filter;

class FilterControls {

    static public function getControl($handle, $key, $default = null) {
        return array_key_exists("$handle-$key", $_GET) ? $_GET["$handle-$key"] : $default;
    }
}

Add static class for accessing filter control options from GET vars.


<?php

namespace AppBundle\API\Edit;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class UpdateProject extends Webservice
{
    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $em = $this->getManagerFromQuery($query);
        if(!$query->has('biom') || !$query->has('project_id')){
            return array('error' => 'Missing parameter "biom" or "project_id"');
        }
        if($user == null){
            return array('error' => 'User not logged in');
        }
        $webuser = $user->getWebuser($em);
        if($webuser === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project = $em->getRepository('AppBundle:WebuserData')->findOneBy(array('webuser' => $webuser, 'webuserDataId' => $query->get('project_id')));
        if($project === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project->setProject(json_decode($query->get('biom'), true));
        $em->flush();
        return array('error' => null);
    }
}

<?php

namespace AppBundle\API\Edit;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class UpdateProject extends Webservice
{
    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $em = $this->getManagerFromQuery($query);
        if(!$query->has('biom') || !$query->has('project_id')){
            return array('error' => 'Missing parameter "biom" or "project_id"');
        }
        if($user == null){
            return array('error' => 'User not logged in');
        }
        $webuser = $user;
        if($webuser === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project = $em->getRepository('AppBundle:WebuserData')->findOneBy(array('webuser' => $webuser, 'webuserDataId' => $query->get('project_id')));
        if($project === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project->setProject(json_decode($query->get('biom'), true));
        $em->flush();
        return array('error' => null);
    }
}

Remove unused function call in order to make updating of projects pass


Add template mtgox API config file.

Add template mtgox API config file.


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

use Zend\Test\PHPUnit\Util\ModuleLoader;

class ModuleLoaderTest extends ModuleLoader
{
    public function testCanLoadModule()
    {
        require_once __DIR__ . '/../../_files/Baz/Module.php';

        $this->loadModule('Baz');

        $baz = $this->getModule('Baz');
        $this->assertTrue($baz instanceof \Baz\Module);
    }

    public function testCanLoadModuleWithPath()
    {
        $this->loadModule(array('Baz' => __DIR__ . '/../../_files/Baz'));
    }

    public function testCanLoadModules()
    {
        require_once __DIR__ . '/../../_files/Baz/Module.php';
        require_once __DIR__ . '/../../_files/modules-path/with-subdir/Foo/Module.php';

        $this->loadModules(array('Baz', 'Foo'));
    }

    public function testCanLoadModulesWithPath()
    {
        $this->loadModules(array(
            'Baz' => __DIR__ . '/../../_files/Baz',
            'Foo' => __DIR__ . '/../../_files/modules-path/with-subdir/Foo',
        ));

        $fooObject = $this->getServiceManager()->get('FooObject');
        $this->assertTrue($fooObject instanceof \stdClass);
    }

    public function testCanLoadModulesFromConfig()
    {
        $config = include __DIR__ . '/../../_files/application.config.php';
        $this->loadModulesFromConfig($config);
    }
}

Add tests on the module loader helper

Add tests on the module loader helper


<?php

/**
 * Background Session Management
 * @author M2Mobi, Heinz Wiesinger
 */
class SessionManager
{

    /**
     * Lifetime of a session instance
     * @var Integer
     */
    private $lifetime;

    /**
     * Reference to UsersModel
     * @var UsersModel
     */
    private $umodel;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->lifetime = ini_get("session.gc_maxlifetime");

        session_set_save_handler (
            array(&$this, 'open'),
            array(&$this, 'close'),
            array(&$this, 'read'),
            array(&$this, 'write'),
            array(&$this, 'destroy'),
            array(&$this, 'gc')
        );

        require_once("model.users.inc.php");
        $this->umodel = new UsersModel();
    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Prepare for session usage.
     * Since we use a database to store the data, we
     * don't really need to do anything here.
     * @param String $path Path to store the session file
     * @param String $name Session name
     * @return Boolean $return Returns always true
     */
    public function open($path, $name)
    {
        global $session_save_path;
        $session_save_path = $path;
        return TRUE;
    }

    /**
     * Close access to session file.
     * Sine we do not use file for session dara storage
     * we don't need to do anything here.
     * @return Boolean $return Returns always true
     */
    public function close()
    {
        return TRUE;
    }

    /**
     * Read session data from the database
     * @param String $id Session ID
     * @return mixed $return Session data on success, False on failure
     */
    public function read($id)
    {
        return $this->umodel->read_session_data($id);
    }

    /**
     * Save session data into the database
     * @param String $id Session ID
     * @param String $data Session Data
     * @return Boolean $return Returns always true
     */
    public function write($id, $data)
    {
        $this->umodel->write_session_data($id, $data, time() + $this->lifetime);
        return TRUE;
    }

    /**
     * End currently active session
     * @param String $id Session ID
     * @return Boolean $return Returns always true
     */
    public function destroy($id)
    {
        $this->umodel->delete_session($id);
        return TRUE;
    }

    /**
     * Clean up expired sessions
     * @return Boolean $return Returns always true
     */
    public function gc()
    {
        $this->umodel->session_gc();
        return TRUE;
    }

}

?>

Add low-level session manager class

application: Add low-level session manager class


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2022, Pierre-Henry Soria. All Rights Reserved.
 * @license          MIT License; See LICENSE.md and COPYRIGHT.md in the root directory.
 * @package          PH7 / Test / Unit / Framework / Navigation
 */

declare(strict_types=1);

namespace PH7\Test\Unit\Framework\Navigation;

use PH7\Framework\Navigation\Pagination;
use PHPUnit\Framework\TestCase;

final class PaginationTest extends TestCase
{
    private const TOTAL_ITEMS = 80;
    private const CURRENT_PAGE = 0;

    public function testPaginationHtmlCode(): void
    {
        $oPagination = new Pagination(self::TOTAL_ITEMS, self::CURRENT_PAGE, Pagination::REQUEST_PARAM_NAME,);

        $sExpected = <<<HTML

1

2

3

›

»

HTML;
        $sActual = $oPagination->getHtmlCode();

        $this->assertSame($sExpected, $sActual);
    }
}

Test the generated pagination HTML code

Test the generated pagination HTML code


<?php
namespace App\Test\TestCase\Command;

use Cake\TestSuite\ConsoleIntegrationTestTrait;
use Cake\Console\Command;
use App\Model\Table\SentencesListsTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

class CorrectNumberOfSentencesCommandTest extends TestCase {
    use ConsoleIntegrationTestTrait;

    public $fixtures = array(
        'app.sentences',
        'app.users',
        'app.sentences_lists',
        'app.sentences_sentences_lists',
    );

    function setUp() {
        parent::setUp();
        $this->UseCommandRunner();
        $this->SentencesLists = TableRegistry::getTableLocator()->get('SentencesLists');
    }

    function tearDown() {
        unset($this->SentencesLists);
        parent::tearDown();
    }

    function testExecute_CorrectNumberIsWritten() {
        $sentencesLists = $this->SentencesLists->find('all')->toList();
        $originalListsAndCounts = array_combine(array_column($sentencesLists, 'id'), array_column($sentencesLists, 'numberOfSentences'));
        debug($originalListsAndCounts);
        foreach($sentencesLists as $sentencesList) {
            $sentencesList->numberOfSentences = 99;
            $this->SentencesLists->save($sentencesList);
        }

        $this->exec("correct_number_of_sentences");

        $sentencesLists = $this->SentencesLists->find('all')->toList();
        $newListsAndCounts = array_combine(array_column($sentencesLists, 'id'), array_column($sentencesLists, 'numberOfSentences'));
        debug($newListsAndCounts);
        $this->assertEquals($newListsAndCounts[1], 3);
        $this->assertEquals($newListsAndCounts[2], 0);
        $this->assertEquals($newListsAndCounts[3], 1);
        $this->assertEquals($newListsAndCounts[4], 2);
        $this->assertEquals($newListsAndCounts[5], 0);
        $this->assertEquals($newListsAndCounts[6], 1);
    }
}

Add test for CorrectNumberOfSentences Command


<?php

namespace Rcm\Tests\Base;

use Rcm\Entity\Country;
use Rcm\Entity\Language;

class PluginTestCase extends DoctrineTestCase
{
    public function setUp()
    {
        parent::setUp();

    }

    public function createDefaultSiteInstance()
    {
        $country = $this->getDefaultCountry();
        $language = $this->getDefaultLanguage();

    }

    public function getDefaultCountry()
    {
        $country = new Country();
        $country->setCountryName('United States');
        $country->setIso2('US');
        $country->setIso3('USA');
        $this->entityManager->persist($country);
        $this->entityManager->flush();

        return $country;
    }

    public function getDefaultLanguage()
    {
        $language = new Language();
        $language->setLanguageName('English');
        $language->setIso6391('en');
        $language->setIso6392b('eng');
        $language->setIso6392t('eng');

        $this->entityManager->persist($language);
        $this->entityManager->flush();

        return $language;
    }
}

Fix for VIP code call. / Added Unit test for profile script


<?php
/**
 * Database migration class
 *
 * @author David Vandemaele <david@tigron.be>
 */

use \Skeleton\Database\Database;

class Migration_20201019_160607_Extractor_default_values extends \Skeleton\Database\Migration {

	/**
	 * Migrate up
	 *
	 * @access public
	 */
	public function up() {
		$db = Database::get();
		$db->query("
			ALTER TABLE `extractor_bank_account_statement_transaction`
			CHANGE `fingerprint_message` `fingerprint_message` varchar(255) COLLATE 'utf8_unicode_ci' NULL AFTER `name`,
			CHANGE `fingerprint_other_account_name` `fingerprint_other_account_name` varchar(128) COLLATE 'utf8_unicode_ci' NULL AFTER `fingerprint_message`,
			CHANGE `fingerprint_other_account_number` `fingerprint_other_account_number` varchar(128) COLLATE 'utf8_unicode_ci' NULL AFTER `fingerprint_other_account_name`,
			CHANGE `eval` `eval` text COLLATE 'utf8_unicode_ci' NULL AFTER `fingerprint_other_account_number`,
			CHANGE `updated` `updated` datetime NULL AFTER `created`;
		", []);
	}

	/**
	 * Migrate down
	 *
	 * @access public
	 */
	public function down() {

	}
}

Set mysql default values for extractor_bank_account_statement_transaction


<?php
/**
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package GitServiceMove\Command\BitBucket\Repository\Issue
 */
namespace GitServiceMove\Command\BitBucket\Repository\Issue;

use GitServiceMove\Command\BitBucket\BaseCommand;
use GitServiceMove\Command\WithResultInterface;
use GitServiceMove\Command\WithResultTrait;
use GitServiceMove\Model\Collection;
use GitServiceMove\Model\Issue;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Bitbucket\API\Repositories\Issues;
use Buzz\Message\Response;

/**
 * Retrieve status of BitBucket connection
 * @package GitServiceMove\Command\BitBucket\Repository\Issue
 */
class ListCommand extends BaseCommand implements WithResultInterface
{
    use WithResultTrait;

    protected $issues;
    protected $milestones;

    protected function configure()
    {
        parent::configure();
        $this->setDescription('List issues inside the selected repo');

        $this->addOption(
            'repository',
            'r',
            InputOption::VALUE_REQUIRED,
            'Repository slug to use for extract data'
        );

        $this->addOption(
            'limit',
            null,
            InputOption::VALUE_OPTIONAL,
            'Number of issues to retrieve',
            10
        );

        $this->addOption(
            'all',
            null,
            InputOption::VALUE_NONE,
            'Flag to tell if we need to retrieve all issues'
        );
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @return null|int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->issues = new Issues();
        $this->issues->setCredentials($this->getAuth());

        $list = $this->retrieveList(
            $input->getOption('repository'),
            new Collection,
            $input->getOption('limit'),
            $input->getOption('all')
        );
        $this->setResult($list);
    }

    private function retrieveList($repository, Collection $results, $limit, $all = false)
    {
        $response = $this->issues->all(
            getenv('BITBUCKET_ACCOUNT'),
            $repository,
            [ 'limit' => $limit, 'start' => count($results) ]
        );
        $data = json_decode($response->getContent());
        array_walk(
            $data->issues,
            function($item) use ($results) {
                $tmp = new Issue(
                    $item->local_id,
                    $item->title,
                    $item->content
                );
                $tmp->priority = $item->priority;
                $tmp->status = $item->status;
                $tmp->milestone = $item->metadata->milestone;
                $tmp->version = $item->metadata->version;

                $results->attach($tmp);
            }
        );
        if( count($results) < $limit || ($all === true && count($results) !== $data->count) ) {
            $this->retrieveList(
                $repository,
                $results,
                $limit,
                $all
            );
        }

        return $results;
    }
}

Add a command to list all issues

Add a command to list all issues


<?php
/**
 * Copyright (c) 2016 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCA\Files_Sharing\Tests\External;

use OC\AppFramework\Http;
use OC\Files\View;
use Test\Connector\Sabre\RequestTest\RequestTest;

class OwnerPropagation extends RequestTest {
	public function testBasicUpload() {
		$user = $this->getUniqueID();
		$userView = $this->setupUser($user, 'pass');

		$userView->mkdir('/a/b/share');

		$subView = new View('/' . $user . '/files/a/b/share');
		$this->assertTrue($subView->is_dir(''));

		$oldInfos = [
			$userView->getFileInfo(''),
			$userView->getFileInfo('a'),
			$userView->getFileInfo('a/b'),
			$userView->getFileInfo('a/b/share'),
		];

		$this->assertFalse($subView->file_exists('foo.txt'));
		$response = $this->request($subView, $user, 'pass', 'PUT', '/foo.txt', 'asd');

		$this->assertEquals(Http::STATUS_CREATED, $response->getStatus());
		$this->assertTrue($subView->file_exists('foo.txt'));
		$this->assertEquals('asd', $subView->file_get_contents('foo.txt'));

		$newInfos = [
			$userView->getFileInfo(''),
			$userView->getFileInfo('a'),
			$userView->getFileInfo('a/b'),
			$userView->getFileInfo('a/b/share'),
		];

		foreach($oldInfos as $i => $oldInfo) {
			$this->assertNotEquals($oldInfo->getEtag(), $newInfos[$i]->getEtag(), 'Etag for ' . $oldInfo->getPath());
		}
	}
}

Add test for owner etag propagation

Add test for owner etag propagation


<?php

use yii\db\Migration;

class m160616_135049_change_Materials extends Migration
{
    public function safeUp()
    {
        $this->dropColumn('Materials','Material');
        $this->addColumn('Materials','Material',
            $this->string(60)->notNull()->unique());
    }

    public function safeDown()
    {
        return FALSE;
    }

}

Migrate added table changed column in Materials


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

namespace ZendTest\Cache\Storage\Adapter;

use Zend\Cache;
use Zend\Cache\Storage\Adapter\Memory as MemoryStorage;
use Zend\Cache\Storage\Adapter\KeyListIterator;

/**
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage UnitTests
 * @group      Zend_Cache
 */
class KeyListIteratorTest extends \PHPUnit_Framework_TestCase
{

    public function testCount()
    {
        $keys = array('key1', 'key2', 'key3');
        $storage = $this->getMock('Zend\Cache\Storage\StorageInterface');
        $iterator = new KeyListIterator($storage, $keys);
        $this->assertEquals(3, $iterator->count());
    }
}

Test added for count() in KeyListIterator


<?php
/**
 * This file is part of the CleverAge/ProcessBundle package.
 *
 * Copyright (C) 2017-2019 Clever-Age
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CleverAge\ProcessBundle\Addon\Doctrine\Task\EntityManager;

use CleverAge\ProcessBundle\Model\ProcessState;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManagerInterface;

/**
 * Clean Doctrine entities from unit of work
 *
 * @author Madeline Veyrenc <mveyrenc@clever-age.com>
 */
class DoctrineCleanerTask extends AbstractDoctrineTask
{
    /**
     * @param ProcessState $state
     *
     * @throws \UnexpectedValueException
     * @throws \Doctrine\ORM\ORMInvalidArgumentException
     * @throws \InvalidArgumentException
     */
    public function execute(ProcessState $state)
    {
        $entity = $state->getInput();
        if (null === $entity) {
            throw new \RuntimeException('DoctrineWriterTask does not allow null input');
        }
        $class = ClassUtils::getClass($entity);
        $entityManager = $this->doctrine->getManagerForClass($class);
        if (!$entityManager instanceof EntityManagerInterface) {
            throw new \UnexpectedValueException("No manager found for class {$class}");
        }
        $entityManager->clear();
    }
}

Add doctrine entity manager cleaner

Add doctrine entity manager cleaner