<?php

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

class InsertNordicCurrencies extends Migration
{
    public function up(): void
    {
        DB::table('currencies')->insert([
            [
                'name' => 'Danish Krone',
                'symbol' => 'DKK'
            ],
            [
                'name' => 'Icelandic Krona',
                'symbol' => 'ISK'
            ],
            [
                'name' => 'Norwegian Krone',
                'symbol' => 'NOK'
            ],
            [
                'name' => 'Swedish Krona',
                'symbol' => 'SEK'
            ]
        ]);
    }

    public function down(): void
    {
        //
    }
}

Create migration that inserts Nordic currencies


<?php declare(strict_types=1);

namespace Mihaeu\PhpDependencies\Cli;

use Mihaeu\PhpDependencies\Util\Util;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;

/**
 * @covers Mihaeu\PhpDependencies\Cli\TestFeaturesCommand
 */
class TestFeaturesCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testSmokeTest()
    {
        $command = new TestFeaturesCommand();
        $output = new BufferedOutput();
        $command->run(new ArrayInput([]), $output);

        // this just checks if every line starts with an [
        // this is not more than a smoke test, but should suffice for the
        // purpose of this command
        $this->assertFalse(Util::array_once(explode(PHP_EOL, trim($output->fetch())), function (string $line) {
            return mb_strpos($line, '[') !== 0;
        }));
    }
}

Add tests for test command

Add tests for test command


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('autoVersion')) {
    function autoVersion($url){
        $path = pathinfo($url);
        $ver = filemtime(getcwd() . '/' .$url);
        return $path['dirname']. '/'. $path['filename'] . '.' . $ver . '.' . $path['extension'];
    }
}

Add filemtime to file name for .css and .js to force download of new files when file has changed


<?php namespace Nathanmac\Console;

use Illuminate\Console\Command;
use Nathanmac\InstantMessenger\Message;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class MessengerCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'messenger:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a simple instant message notification using the messaging service.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->laravel['messenger']->send(function(Message $message) {
            // Body of the message
            $message->body($this->argument('text'));

            // From field for the message
            $message->from($this->option('from'), $this->option('email'));

            // Icon for the message
            $message->icon($this->option('image'));
        });

        $this->info('Messenger: A message has been sent.');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['text', InputArgument::REQUIRED, 'The text/body of the message to be sent.'],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['from', 'f', InputOption::VALUE_OPTIONAL, 'Set the name of the sender of the message.', null],
            ['email', 'e', InputOption::VALUE_OPTIONAL, 'Set the email of the sender of the message.', null],
            ['image', 'i', InputOption::VALUE_OPTIONAL, 'Set the image/icon of the message.', null]
        ];
    }

}

Add messenger command to allow a message to be sent from the console.


<?php

error_reporting(E_ALL);
ini_set('display_errors', true);
$cols = array(
	'token',
    'team_id',
    'team_domain',
    'channel_id',
    'channel_name',
    'timestamp',
    'user_id',
    'user_name',
    'text',
    'trigger_word',
);
function asParam($x) { return ":$x"; }
$sql = "insert into messages ("
	. implode(', ', $cols)
	. ') values ('
	. implode(', ', array_map('asParam', $cols))
	. ')';

$dbfile = 'db/messages.sqlite';
$dbh = new PDO("sqlite:$dbfile");
$stmt = $dbh->prepare($sql) or die(json_encode($dbh->errorInfo()));
foreach($cols as $col) {
	$val = isset($_POST[$col]) ? $_POST[$col] : '';
	$stmt->bindValue(":$col", $val);
}
$stmt->execute();
?>

Save slack messages to sqlite db

Save slack messages to sqlite db


<?php

/*
 * This file is part of the PayumLimonetik package.
 *
 * (c) Alexandre Bacco
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace winzou\PayumLimonetik\Bridge\Symfony;

use Payum\Bundle\PayumBundle\DependencyInjection\Factory\Payment\AbstractPaymentFactory;
use Payum\Core\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

class LimonetikPaymentFactory extends AbstractPaymentFactory
{
    /**
     * {@inheritdoc}
     */
    public function create(ContainerBuilder $container, $contextName, array $config)
    {
        if (false == class_exists('winzou\PayumLimonetik\LimonetikPaymentFactory')) {
            throw new RuntimeException('Cannot find Limonetik payment factory class. Have you installed winzou/payum-limonetik package?');
        }

        return parent::create($container, $contextName, $config);
    }

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

    /**
     * {@inheritdoc}
     */
    public function addConfiguration(ArrayNodeDefinition $builder)
    {
        parent::addConfiguration($builder);

        $builder
            ->children()
                ->scalarNode('merchant_id')->isRequired()->cannotBeEmpty()->end()
                ->scalarNode('key')->isRequired()->cannotBeEmpty()->end()
                ->booleanNode('sandbox')->defaultTrue()->end()
            ->end()
        ;
    }

    /**
     * {@inheritDoc}
     */
    protected function addApis(Definition $paymentDefinition, ContainerBuilder $container, $contextName, array $config)
    {
        $apiDefinition = new DefinitionDecorator('payum.limonetik.api.prototype');
        $apiDefinition->replaceArgument(0, array(
            'merchantId' => $config['merchant_id'],
            'key'        => $config['key'],
            'sandbox'    => $config['sandbox'],
        ));
        $apiDefinition->setPublic(true);

        $apiId = 'payum.context.'.$contextName.'.api';
        $container->setDefinition($apiId, $apiDefinition);

        $paymentDefinition->addMethodCall('addApi', array(new Reference($apiId)));
    }
}

Add PaymentFactory bridge for symfony bundle


<?php

namespace FireflyIII\Jobs;

use Illuminate\Bus\Queueable;

abstract class Job
{
    /*
    |--------------------------------------------------------------------------
    | Queueable Jobs
    |--------------------------------------------------------------------------
    |
    | This job base class provides a central location to place any logic that
    | is shared across all of your jobs. The trait included with the class
    | provides access to the "onQueue" and "delay" queue helper methods.
    |
    */

    use Queueable;
}

Update jobs after upgrade to Laravel 5.2


<?php

declare(strict_types=1);

namespace Application;

use phpDocumentor\Application\PipelineFactory;

final class PipelineFactoryTest extends \PHPUnit\Framework\TestCase
{
    public function test_creates_a_pipeline_with_the_given_series_of_stages()
    {
        $pipeline = PipelineFactory::create(
            function($value) { return $value + 1; },
            function($value) { return $value * 2; }
        );

        // can only test whether it worked by running the pipeline and
        // getting the expected output
        $this->assertSame(8, $pipeline(3));
    }
}

Add test for Pipeline Factory

Add test for Pipeline Factory


<?php
defined('TYPO3_MODE') or die();

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

<?php
defined('TYPO3_MODE') or die();

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

[BUGFIX] Use string to identify bootstrap_package for adding static template


<?php

namespace Emarref\Jwt\Encryption;

class SymmetricTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $algorithm;

    /**
     * @var Symmetric
     */
    private $encryption;

    public function setUp()
    {
        $this->algorithm = $this->getMockBuilder('Emarref\Jwt\Algorithm\Hs256')
            ->setConstructorArgs(['secret'])
            ->getMock();

        $this->encryption = new Symmetric($this->algorithm);
    }

    public function testEncrypt()
    {
        $value         = 'value';
        $computedValue = 'computed_value';

        $this->algorithm->expects($this->once())
            ->method('compute')
            ->with($value)
            ->will($this->returnValue($computedValue));

        $this->assertSame($computedValue, $this->encryption->encrypt($value));
    }

    public function testVerify()
    {
        $value        = 'value';
        $signature    = 'signature';

        $badValue     = 'bad_value';
        $badSignature = 'bad_signature';

        $this->algorithm->expects($this->exactly(2))
            ->method('compute')
            ->will($this->returnValueMap([
                [$value, $signature],
                [$badValue, 'wontverify'],
            ]));

        $this->assertTrue($this->encryption->verify($value, $signature));
        $this->assertFalse($this->encryption->verify($badValue, $badSignature));
    }
}

Add test for symmetric encryption

Add test for symmetric encryption


Add correctly named staging config file.


<?php

namespace SumoCoders\FrameworkMultiUserBundle\User;

use SumoCoders\FrameworkMultiUserBundle\Entity\User;

final class DoctrineUserRepository extends UserRepository
{
    /**
     * @param string $class
     *
     * @return bool
     */
    public function supportsClass($class)
    {
        return User::class === $class;
    }
}

Create a doctrine implementation of the default user repository


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for partialRight Mimic library function.
 *
 * @since 0.1.0
 */
class PartialRightFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testArraySum() {
		$expected = array_sum(1, 2, 3, 4, 5, 6);
		$callback = F\partialRight('array_sum', 1, 2, 3);
		$this->assertEquals($expected, $callback(4, 5, 6));
	}

	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testArrayMerge() {
		$expected = array(1, 2, 3, 4, 5, 6);
		$callback = F\partialRight('array_merge', array(1, 2, 3));
		$this->assertEquals($expected, $callback(4, 5, 6));
	}
}

Add partial right function test suite.

Add partial right function test suite.


<?php

namespace Orchestra\Database\Console\Migrations;

trait Packages
{
    /**
     * The path to the packages directory (vendor).
     *
     * @var string
     */
    protected $packagePath;

    /**
     * Set package path.
     *
     * @param  string  $packagePath
     *
     * @return $this
     */
    public function setPackagePath($packagePath)
    {
        $this->packagePath = $packagePath;

        return $this;
    }

    /**
     * Get the path to the package migration directory.
     *
     * @param  string  $package
     *
     * @return array
     */
    protected function getPackageMigrationPaths($package)
    {
        return collect($this->option('path') ?? 'resources/migrations')
                    ->map(function ($path) use ($package) {
                        return $this->packagePath.'/'.$package.'/'.$path;
                    })->all();
    }
}

<?php

namespace Orchestra\Database\Console\Migrations;

trait Packages
{
    /**
     * The path to the packages directory (vendor).
     *
     * @var string
     */
    protected $packagePath;

    /**
     * Set package path.
     *
     * @param  string  $packagePath
     *
     * @return $this
     */
    public function setPackagePath($packagePath)
    {
        $this->packagePath = $packagePath;

        return $this;
    }

    /**
     * Get the path to the package migration directory.
     *
     * @param  string  $package
     *
     * @return array
     */
    protected function getPackageMigrationPaths($package)
    {
        return collect($this->option('path') ?: 'resources/migrations')
                    ->map(function ($path) use ($package) {
                        return $this->packagePath.'/'.$package.'/'.$path;
                    })->all();
    }
}

Use ?: instead of ??

Use ?: instead of ??

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


<?php
require_once('class.FlipsideTicketRequest.php');
require_once('mpdf/mpdf.php');

class FlipsideTicketRequestPDF extends FlipsideMail
{
    private $request;
    public  $source;

    function __construct($request, $source = FALSE)
    {
        parent::__construct();
        if($request == FALSE)
        {
            $this->request = FlipsideTicketRequest::test_request();
        }
        else
        {
            $this->request = $request;
        }
        if($source == FALSE)
        {
            $this->source = FlipsideTicketDB::get_long_text('pdf_source');
        }
        else
        {
            $this->source = $source;
        }
    }

    function generatePDF()
    {
        $mpdf = new mPDF();
        $ticket_count   = count($this->request->tickets);
        $barcode        = '<barcode code="'.$this->request->request_id.'" type="C39"/>';
        $year           = $this->request->year;
        $request_id     = $this->request->request_id;
        $total_due      = $this->request->total_due;
        $open_date      = FlipsideTicketDB::get_var('mail_start_date');
        $close_date     = FlipsideTicketDB::get_var('request_stop_date');
        $address        = $this->request->getMailingAddress('<br/>');
        $ticket_table   = $this->request->getTicketsAsTable();
        $donation_table = $this->request->getDonationsAsTable();
        $requestor      = $this->request->givenName+' '+$this->request->sn;
        $email          = $this->request->mail;
        $phone          = $this->request->mobile;
        $request_date   = $this->request->modifiedOn;
        $vars           = array(
            '{$ticket_count}'   => $ticket_count,
            '{$barcode}'        => $barcode,
            '{$year}'           => $year,
            '{$request_id}'     => $request_id,
            '{$total_due}'      => $total_due,
            '{$open_date}'      => $open_date,
            '{$close_date}'     => $close_date,
            '{$address}'        => $address,
            '{$ticket_table}'   => $ticket_table,
            '{$donation_table}' => $donation_table,
            '{$requestor}'      => $requestor,
            '{$email}'          => $email,
            '{$phone}'          => $phone,
            '{$request_date}'   => $request_date
        );
        $html           = strtr($this->source, $vars);
        $mpdf->WriteHTML($html);
        $filename = '/var/www/secure/tickets/tmp/'.hash('sha512', json_encode($this->request)).'.pdf';
        $mpdf->Output($filename);
        return $filename;
    }
}
?>

Add PDF class that pulls source HTML from DB


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for either Mimic library function.
 *
 * @since 0.1.0
 */
class EitherFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array('something'),
			array(0),
			array(1),
			array(true),
			array(1.0),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\either
	 */
	public function testFirstCallbackValue($expected) {
		$left = function() use ($expected) { return $expected; };
		$right = function() { return false; };
		$this->assertEquals($expected, F\either($left, $right));
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\either
	 */
	public function testSecondCallbackValue($expected) {
		$left = function() { return false; };
		$right = function() use ($expected) { return $expected; };
		$this->assertEquals($expected, F\either($left, $right));
	}
}

Add either function test suite.

Add either function test suite.


<?php

use Interop\Container\ContainerInterface;
use Zend\Expressive\Application;

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

/** @var ContainerInterface $container */
$container = require __DIR__ . '/../app/container.php';

/** @var Application $app */
$app = $container[Application::class];
$app->pipeRoutingMiddleware();
$app->pipeDispatchMiddleware();
$app->run();

<?php

use Interop\Container\ContainerInterface;
use Zend\Expressive\Application;

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

/** @var ContainerInterface $container */
$container = require __DIR__ . '/../app/container.php';

/** @var Application $app */
$app = $container[Application::class];
$app->run();

Remove redundant method calls in front controller


<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_BILLING is valid.
	 */
	public function testShouldReceiveConstAddressBillingIsValid()
	{
		$address_billing = 'BILLING';
		$const_address_billing = constant('\Moip\Resource\Customer::ADDRESS_BILLING');

		$this->assertEquals($address_billing, $const_address_billing);
	}
}

<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_BILLING is valid.
	 */
	public function testShouldReceiveConstAddressBillingIsValid()
	{
		$address_billing = 'BILLING';
		$const_address_billing = constant('\Moip\Resource\Customer::ADDRESS_BILLING');

		$this->assertEquals($address_billing, $const_address_billing);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_SHIPPING is valid.
	 */
	public function testShouldReceiveConstAddressShippingIsValid()
	{
		$address_shipping = 'SHIPPING';
		$const_address_shipping = constant('\Moip\Resource\Customer::ADDRESS_SHIPPING');

		$this->assertEquals($address_shipping, $const_address_shipping);
	}
}


<?php

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

class AddForeignKeyToMessages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::disableForeignKeyConstraints();
        Schema::table('server_messages', function(Blueprint $table){
            $table->foreign('channel')->references('id')->on('channels')->onDelete("cascade");
        });
        Schema::enableForeignKeyConstraints();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::disableForeignKeyConstraints();
        Schema::table('server_messages', function(Blueprint $table){
            $table->dropForeign(['channel']);
        });
        Schema::enableForeignKeyConstraints();
    }
}

Add foreign key for "channel" on server messages column


<?php

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

class UpdateAssessmentsTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->char('score_comedy')->after('score_nuki')->nullable()->default('');
				$table->boolean('savable')->after('score_all')->nullable();
			});
		}
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		if(Schema::hasTable('assessments')) {
			Schema::table('assessments', function($table) {
				$table->dropColumn(['score_comedy', 'savable']);
			});
		}
	}
}

Add migration to update assessments table


<?php

use Illuminate\Database\Migrations\Migration;

class CreateUsersOfStudents extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //找出沒有使用者的學生
        /** @var \App\Student[]|\Illuminate\Database\Eloquent\Collection $students */
        $students = \App\Student::query()->whereNull('user_id')->get();
        foreach ($students as $student) {
            //建立使用者
            $email = $student->nid . '@fcu.edu.tw';
            /** @var \App\User $user */
            $user = \App\User::query()->updateOrCreate([
                'email' => $email,
            ], [
                'name'        => $student->name,
                'password'    => '',
                'confirm_at'  => \Carbon\Carbon::now(),
                'register_at' => \Carbon\Carbon::now(),
                'register_ip' => \Request::getClientIp(),
            ]);
            //綁定
            $user->student()->save($student);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Create user of exist student

Create user of exist student


<?php
/**
 * User: simon
 * Date: 13.04.2021
 */
namespace ShortPixel;

class SPTools {
    public static function trailingslashit($path) {
        return rtrim($path, '/') . '/';
    }
}

Fix errors with the new encoded URL and new persister line length


<?php

namespace Fhaculty\Graph\Algorithm;

use Fhaculty\Graph\Algorithm\BaseGraph;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Algorithm\Degree;

class Eulerian extends BaseGraph
{
    /**
     * check whether this graph has an eulerian cycle
     *
     * @return boolean
     * @uses Graph::isConnected()
     * @uses Degree::getDegreeVertex()
     * @todo isolated vertices should be ignored
     * @todo definition is only valid for undirected graphs
     */
    public function hasCycle()
    {
        if ($this->graph->isConnected()) {
            $alg = new Degree($this->graph);

            foreach ($this->graph->getVertices() as $vertex) {
                // uneven degree => fail
                if ($alg->getDegreeVertex($vertex) & 1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

<?php

namespace Fhaculty\Graph\Algorithm;

use Fhaculty\Graph\Algorithm\BaseGraph;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Algorithm\Degree;

class Eulerian extends BaseGraph
{
    /**
     * check whether this graph has an eulerian cycle
     *
     * @return boolean
     * @uses ConnectedComponents::isSingle()
     * @uses Degree::getDegreeVertex()
     * @todo isolated vertices should be ignored
     * @todo definition is only valid for undirected graphs
     */
    public function hasCycle()
    {
        $components = new ConnectedComponents($this->graph);
        if ($components->isSingle()) {
            $alg = new Degree($this->graph);

            foreach ($this->graph->getVertices() as $vertex) {
                // uneven degree => fail
                if ($alg->getDegreeVertex($vertex) & 1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

Fix outdated refernce to connected components


<?php

/*
 * This file is part of the Foxy package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Foxy;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;

/**
 * Composer plugin.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class Foxy implements PluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function activate(Composer $composer, IOInterface $io)
    {
    }
}

Add base of composer plugin

Add base of composer plugin


<?php
namespace Codeception\Lib\Connector;

class Symfony2 extends \Symfony\Component\HttpKernel\Client
{
    private static $hasPerformedRequest;

    public $persistentServices = [];

    protected function doRequest($request)
    {
        $services = [];
        if (self::$hasPerformedRequest) {
            $services = $this->persistServices();
            $this->kernel->shutdown();
        } else {
            self::$hasPerformedRequest = true;
        }
        $this->kernel->boot();

        $container = $this->kernel->getContainer();
        if ($this->kernel->getContainer()->has('profiler')) {
            $container->get('profiler')->enable();
        }

        $this->injectPersistedServices($services);

        return parent::doRequest($request);
    }

    /**
     * @param $services
     * @return array
     */
    protected function persistServices()
    {
        $services = [];
        foreach ($this->persistentServices as $serviceName) {
            if (!$this->kernel->getContainer()->has($serviceName)) {
                continue;
            }
            $services[$serviceName] = $this->kernel->getContainer()->get($serviceName);
        }
        return $services;
    }

    /**
     * @param $services
     * @param $container
     */
    protected function injectPersistedServices($services)
    {
        foreach ($services as $serviceName => $service) {
            $this->kernel->getContainer()->set($serviceName, $service);
        }
    }

}

<?php
namespace Codeception\Lib\Connector;

class Symfony2 extends \Symfony\Component\HttpKernel\Client
{
    private static $hasPerformedRequest;

    public $persistentServices = [];

    protected function doRequest($request)
    {
        $services = [];
        if (self::$hasPerformedRequest) {
            $services = $this->persistServices();
            $this->kernel = clone $this->kernel;
        } else {
            self::$hasPerformedRequest = true;
        }
        $this->kernel->boot();

        $container = $this->kernel->getContainer();
        if ($this->kernel->getContainer()->has('profiler')) {
            $container->get('profiler')->enable();
        }

        $this->injectPersistedServices($services);

        return parent::doRequest($request);
    }

    /**
     * @param $services
     * @return array
     */
    protected function persistServices()
    {
        $services = [];
        foreach ($this->persistentServices as $serviceName) {
            if (!$this->kernel->getContainer()->has($serviceName)) {
                continue;
            }
            $services[$serviceName] = $this->kernel->getContainer()->get($serviceName);
        }
        return $services;
    }

    /**
     * @param $services
     * @param $container
     */
    protected function injectPersistedServices($services)
    {
        foreach ($services as $serviceName => $service) {
            $this->kernel->getContainer()->set($serviceName, $service);
        }
    }

}

Fix doctrine issues after first request is made.


<?php

namespace RadDB\Http\Controllers;

use Illuminate\Http\Request;

class CTDailyQCRecordController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

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

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

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

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

Create controller for CT daily QC records


<?php
spl_autoload_register(function ($classname) {require ( $classname . ".php");});
$datalogin = Core::checkSessions();?>
<!doctype html>

<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="assets/img/reslim.ico">
<link rel="icon" type="image/png" sizes="96x96" href="assets/img/reslim.ico">
<link rel="canonical" href="<?php echo (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']?>" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1, user-scalable=0' name='viewport' />
<meta name="format-detection" content="telephone=no"/>
<title>Reader - <?php echo Core::getInstance()->title?></title>

<iframe src="<?php echo (empty($_GET['file'])?'':Core::getInstance()->basepath.'/plugins/pdf/viewer.php?file='.$_GET['file'])?>" type="application/pdf" allowFullScreen>

Your browser doesn't support iframes. For direct link viewer, just <a href="<?php echo (empty($_GET['file'])?'':$_GET['file'])?>">click here.

<?php include 'analytics.php';?>

Add new mobile reader for better reading in small devices


<?php

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

class MakeSignupIdInEventsTableNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('events', function (Blueprint $table) {
            $table->integer('signup_id')->nullable()->change();
        });
    }

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

Allow signup_id in the events table to be NULL

This way when this column is not set it will be NULL instead of 0.


<?php
require_once(__DIR__ . '/WebexXmlRequestHeader.class.php');
require_once(__DIR__ . '/WebexXmlRequestBody.class.php');
require_once(__DIR__ . '/WebexXmlSecurityContext.class.php');
require_once(__DIR__ . '/WebexXmlRequestBodyContent.class.php');

class WebexXmlRequest
{
	/**
	 * @var WebexXmlRequestHeader
	 */
	protected $header;

	/**
	 * @var WebexXmlRequestBody
	 */
	protected $body;

	/**
	 * @var string
	 */
	protected $contentType;

	public function __construct(WebexXmlSecurityContext $securityContext, WebexXmlRequestBodyContent $bodyContent)
	{
		$this->header = new WebexXmlRequestHeader($securityContext);
		$this->body = new WebexXmlRequestBody($bodyContent);
		$this->contentType = $bodyContent->getContentType();
	}

	public function __toString()
	{
		$xml = '<?xml version="1.0" encoding="UTF-8"?>';
		$xml .= '<serv:message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:serv="http://www.webex.com/schemas/2002/06/service">';
		$xml .= $this->header;
		$xml .= $this->body;
		$xml .= '</serv:message>';

		return $xml;
	}

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

Add webex xml request missing file

Add webex xml request missing file


<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Helper;

use Oro\Bundle\ActionBundle\Helper\ApplicationsHelperInterface;
use Oro\Bundle\WorkflowBundle\Helper\WorkflowApplicationsHelper;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;

class WorkflowApplicationsHelperTest extends \PHPUnit_Framework_TestCase
{
    use EntityTestCaseTrait;

    /** @var ApplicationsHelperInterface|\PHPUnit_Framework_MockObject_MockObject */
    protected $applicationHelper;

    /** @var ApplicationsHelperInterface */
    protected $workflowApplicationHelper;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->applicationHelper = $this->getMockBuilder('Oro\Bundle\ActionBundle\Helper\ApplicationsHelperInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $this->workflowApplicationHelper = new WorkflowApplicationsHelper($this->applicationHelper);
    }

    public function testGetSetRouteParam()
    {
        $parameters = [
            ['dialogRoute', 'url1'],
            ['executionRoute', 'url2'],
            ['widgetRoute', 'url3']
        ];

        $this->assertPropertyAccessors($this->workflowApplicationHelper, $parameters);
    }

    public function testIsApplicationsValid()
    {
        $this->applicationHelper->expects($this->once())
            ->method('isApplicationsValid')
            ->with(['data'])
            ->willReturn('test');

        $this->assertSame('test', $this->workflowApplicationHelper->isApplicationsValid(['data']));
    }

    public function testGetCurrentApplication()
    {
        $this->applicationHelper->expects($this->once())
            ->method('getCurrentApplication')
            ->willReturn('test');

        $this->assertSame('test', $this->workflowApplicationHelper->getCurrentApplication());
    }
}

BAP-12468: Update ApplicationsHelper and ActionApplicationsHelper
- added test for WorkflowApplicationHelper


<?php

namespace AppBundle\Controller;

use AppBundle\Services\ProjectService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;

class ProjectController extends Controller
{
    /**
     * @Route("/projeto/novo", name="new_project")
     */
    public function newAction(Request $request, ProjectService $projectService)
    {
        $requirements = [
            'skills' => [
                'php' => mt_rand(1, 3),
                'css' => mt_rand(1, 3),
                'html' => mt_rand(1, 3)
            ],
            'quantity' => mt_rand(2, 3)
        ];

        $project = [
            'title' => 'Projeto 1',
            'description' => 'Temos esse projeto pra fazer',
            'deadline' => new \DateTime('tomorrow'),
            'manager' => 1,
            'requirements' => $requirements
        ];

        $project = $projectService->create($project);

        if ($project instanceof Exception) {
            return $this->redirectToRoute('homepage', ['message' => $project->getMessage()]);
        }

        return $this->redirectToRoute('detail_project', ['id' => $project]);
    }

    /**
     * @Route("/projeto/{id}", name="detail_project")
     */
    public function detailAction(Request $request, $id, ProjectService $projectService)
    {
        $project = $projectService->findOneById($id);

        return $this->render('project/detail.html.twig', [
            'project' => $project
        ]);
    }
}

Add and view project actions added

Add and view project actions added


<?php

namespace PhpAbac\Manager;

use PhpAbac\Loader\YamlAbacLoader;

use Symfony\Component\Config\FileLocatorInterface;

class ConfigurationManager {
    /** @var FileLocatorInterface **/
    protected $locator;
    /** @var string **/
    protected $format;
    /** @var array **/
    protected $loaders;
    /** @var array **/
    protected $rules;
    /** @var array **/
    protected $attributes;

    /**
     * @param FileLocatorInterface $locator
     * @param string $format
     */
    public function __construct(FileLocatorInterface $locator, $format = 'yaml') {
        $this->locator = $locator;
        $this->format = $format;
        $this->loaders['yaml'] = new YamlAbacLoader($locator);
    }

    public function parseConfigurationFile() {
        $config = $this->loaders[$this->format]->load('policy_rules.yml');
        $this->attributes = $config['attributes'];
        $this->rules = $config['rules'];
    }

    /**
     * @return array
     */
    public function getAttributes() {
        return $this->attributes;
    }

    /**
     * @return array
     */
    public function getRules() {
        return $this->rules;
    }
}

Implement the configuration manager to read rules and attributes from configuration file


<?php

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

namespace Psy\Command;

use Psy\Output\ShellOutput;
use Psy\Command\ShellAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class NamespaceCommand extends ShellAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('namespace')
            ->setDefinition(array(
                new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace.'),
                new InputOption('clear', '',   InputOption::VALUE_NONE, 'Clear the current namespace.'),
            ))
            ->setDescription('Set (or clear) the current namespace.')
            ->setHelp(<<<EOF
Set (or clear) the current namespace.
EOF
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('clear')) {
            $this->shell->setNamespace(null);
            $output->writeln('<aside>Namespace cleared</aside>');
        } elseif ($namespace = $input->getArgument('namespace')) {
            $this->shell->setNamespace($namespace);
        } elseif ($namespace = $this->shell->getNamespace()) {
            $output->writeln(sprintf('<info>%s</info>', $namespace));
        }
    }
}

Add a namespace command to take advantage of awesome


<?php

use Risan\OAuth1\HttpClient;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client as Guzzle;
use Risan\OAuth1\HttpClientInterface;
use Psr\Http\Message\ResponseInterface;

class HttpClientTest extends TestCase
{
    private $guzzleStub;
    private $responseStub;
    private $httpClient;

    function setUp()
    {
        $this->guzzleStub = $this->createMock(Guzzle::class);
        $this->responseStub = $this->createMock(Response::class);
        $this->httpClient = new HttpClient($this->guzzleStub);
    }

    /** @test */
    function http_client_is_an_instance_of_http_client_interface()
    {
        $this->assertInstanceOf(HttpClientInterface::class, $this->httpClient);
    }

    /** @test */
    function http_client_can_get_guzzle_instance()
    {
        $this->assertInstanceOf(Guzzle::class, $this->httpClient->getGuzzle());
    }

    /** @test */
    function http_client_can_create_and_send_http_request()
    {
        $this->guzzleStub->expects($this->once())
            ->method('request')
            ->with('POST', 'http://example.com', ['foo' => 'bar'])
            ->willReturn($this->responseStub);

        $this->assertInstanceOf(
            ResponseInterface::class,
            $this->httpClient->request('POST', 'http://example.com', ['foo' => 'bar'])
        );
    }

    /** @test */
    function http_client_can_create_and_send_http_post_request()
    {
        $this->guzzleStub->expects($this->once())
            ->method('request')
            ->with('POST', 'http://example.com', ['foo' => 'bar'])
            ->willReturn($this->responseStub);

        $this->assertInstanceOf(
            ResponseInterface::class,
            $this->httpClient->post('http://example.com', ['foo' => 'bar'])
        );
    }
}

Add new test for HTTP client.

:white_check_mark: Add new test for HTTP client.


<?php
require_once '../../default.php';
echo test_folders(array("/tmp/", "/tmp/", "/tmp/"));

function secret_folder_is_secure($folder = "/tmp/") {
    $dirname = dirname($_SERVER["PHP_SELF"]);
    //This script lies within /src/php/ so therefore we have to move up by two levels:
    $dir_above1 = substr($dirname, 0, strrpos($dirname, "/"));
    $dir_above2 = substr($dirname, 0, strrpos($dir_above1, "/"));
    $filename = "http://" . $_SERVER["HTTP_HOST"] . $dir_above2 . $folder;

    list($response) = get_headers($filename);
    $response_code = substr($response, strpos($response, " "), (strrpos($response, " ") - strpos($response, " ")));
    if (200 == $response_code) {
        $error_message = "Error! The directory $filename is world visible. Please make sure that the directory is not accessible by the public!";
        return $error_message;
    } elseif (403 == $response_code) {
        return TRUE;
    } else {
        $error_message = "Error! We could not interpret the result. The server returned: '$response'. Please make sure that the directory is not accessible by the public!";
        return $error_message;
    }
}

function test_folders($Folders) {
    $error_message_html = "
\n";
    foreach ($Folders as $folder){
        $secure = secret_folder_is_secure($folder);
        if (TRUE !== $secure){
            $error_message_html .= build_error_message($secure);
            $error_message_exists = TRUE;
        }
    }
    $error_message_html .= "
\n";
    if($error_message_exists){
        require_once get_root_folder() . 'head.php';
        return $error_message_html;
    } else {
        return FALSE;
        echo "Alles ist gut.";
    }
}

function build_error_message($error_message_text) {
    $error_message_html = "
" . $error_message_text . "
\n";
    return $error_message_html;
}
?>

Test if secret directorys are secure from public viewing


<?php

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

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

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

Add missing content_type index, speeding up "top" search


<?php

class StripCheckboxes
{
	private $checkboxes	= array();
	private $strip		= array('sendpidget', 'hidepattern', 'anotostatement');

	public function addEventHandlers(RequestContext $ctx)
	{
		$ctx->addEventHandler(RendererEvent::XML, $this, 'stripFields');
	}

	public function stripFields(RendererEvent $event)
	{
		$xml = simplexml_load_file($event->file);

		foreach($xml->children as $node)
		{
			$nodename = (string) $node['name'];
			$nodetype = (string) $node['type'];

			if(in_array($nodetype, $this->strip))
			{
				$dom = dom_import_simplexml($node);
				$dom->parentNode->removeChild($dom);
			}

			if(in_array($nodename, $this->checkboxes))
			{
				g_Log(__METHOD__ . ':' . __CLASS__ . ': Removing group checkbox member "' . $nodename . '"');

				$dom = dom_import_simplexml($node);
				$dom->parentNode->removeChild($dom);
			}
		}

		file_put_contents($event->file, $xml->asXML());
	}

	public function __construct()
	{
		$path	= dirname(__FILE__);
		$file	= str_replace('custom', 'config.xml', $path);
		$config	= simplexml_load_file($file);

		foreach($config->Group as $group)
		{
			foreach($config->Widget as $widget)
			{
				if($widget['group'] == $group['name'])
				{
					$this->checkboxes[] = $widget['name'];
				}
			}
		}
	}
}

Rename folder to make it more useful

Rename folder to make it more useful


<?php

namespace Wallabag\CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RenameTagType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('label', TextType::class, [
                'required' => true,
                'attr' => [
                    'placeholder' => 'tag.rename.placeholder',
                ],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Wallabag\CoreBundle\Entity\Tag',
        ]);
    }

    public function getBlockPrefix()
    {
        return 'tag';
    }
}

Rename Tag : Add a new FormType

Rename Tag : Add a new FormType


<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class InvoicesTableSeeder extends Seeder {

	public function run()
	{
		$faker = Faker::create();

		foreach(range(1, 10) as $index)
		{
			$status = Status::orderByRaw("RAND()")->first();
			Invoice::create([
				'title' => $faker->word(),
				'due' => $faker->date(),
				'status_id' => $status->id,
				'amount' => $faker->randomFloat($nbMaxDecimals = 2)
			]);
		}
	}

}

<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class InvoicesTableSeeder extends Seeder {

	public function run()
	{
		$faker = Faker::create();

		foreach(range(1, 10) as $index)
		{
			$status = Status::orderByRaw("RAND()")->first();
			$user = User::orderByRaw("RAND()")->first();
			Invoice::create([
				'title' => $faker->word(),
				'due' => $faker->date(),
				'status_id' => $status->id,
				'amount' => $faker->randomFloat($nbMaxDecimals = 2),
				'owner_id' => $user->id
			]);
		}
	}

}

Add table seeder for invoices

Add table seeder for invoices


<?php
namespace SimpleSoftwareIO\SMS;

trait DoesNotReceive
{
    /**
     * Checks the server for messages and returns their results.
     *
     * @param array $options
     *
     * @return array
     */
    public function checkMessages(array $options = [])
    {
        throw new \RuntimeException('Receive methods are not support with the E-Mail driver.');
    }

    /**
     * Gets a single message by it's ID.
     *
     * @param string|int $messageId
     *
     * @throws \RuntimeException
     *
     */
    public function getMessage($messageId)
    {
        throw new \RuntimeException('Receive methods are not support with the E-Mail driver.');
    }

    /**
     * Receives an incoming message via REST call.
     *
     * @param mixed $raw
     *
     * @throws \RuntimeException
     */
    public function receive($raw)
    {
        throw new \RuntimeException('Receive methods are not support with the E-Mail driver.');
    }
}

Create DoesNotReceieve trait for drivers who do not support incoming messages


<?php
/**
 * Plugin Name: Restrict Content Pro - Renew Deactivated Membership Levels
 * Description: Allows deactivated membership levels to be renewed by customers with existing memberships.
 * Version: 1.0
 * Author: Restrict Content Pro team
 * License: GPL2
 */

add_filter( 'rcp_can_renew_deactivated_memberships', '__return_true' );

Add snippet for renewing deactivated membership levels.


<?php

namespace spec\MageTest\MagentoExtension\Context\Initializer;

use PHPSpec2\Specification;

class MagentoAwareInitializer implements Specification
{
    function described_with($bootstrap, $app, $config, $cache, $factory)
    {
        $bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
        $app->isAMockOf('Mage_Core_Model_App');
        $bootstrap->app()->willReturn($app);

        $cache->isAMockOf('MageTest\MagentoExtension\Service\CacheManager');
        $config->isAMockOf('MageTest\MagentoExtension\Service\ConfigManager');
        $factory->isAMockOf('MageTest\MagentoExtension\Fixture\FixtureFactory');

        $this->magentoAwareInitializer->isAnInstanceOf(
            'MageTest\MagentoExtension\Context\Initializer\MagentoAwareInitializer',
            array($bootstrap, $cache, $config, $factory)
        );
    }

    /**
     * @param Prophet $context mock of MageTest\MagentoExtension\Context\MagentoContext
     */
    function it_initialises_the_context($context, $app, $config, $cache, $factory)
    {
        // $context->setApp($app)->shouldBeCalled();
        // $context->setConfigManager($config)->shouldBeCalled();
        // $context->setCacheManager($cache)->shouldBeCalled();
        // $context->setFixtureFactory($factory)->shouldBeCalled();
        // $this->magentoAwareInitializer->initialize($context);
    }

}

<?php

namespace spec\MageTest\MagentoExtension\Context\Initializer;

use PHPSpec2\Specification;

class MagentoAwareInitializer implements Specification
{
    function described_with($bootstrap, $app, $config, $cache, $factory)
    {
        $bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
        $app->isAMockOf('Mage_Core_Model_App');
        $bootstrap->app()->willReturn($app);

        $cache->isAMockOf('MageTest\MagentoExtension\Service\CacheManager');
        $config->isAMockOf('MageTest\MagentoExtension\Service\ConfigManager');
        $factory->isAMockOf('MageTest\MagentoExtension\Fixture\FixtureFactory');

        $this->magentoAwareInitializer->isAnInstanceOf(
            'MageTest\MagentoExtension\Context\Initializer\MagentoAwareInitializer',
            array($bootstrap, $cache, $config, $factory)
        );
    }

    /**
     * @param Prophet $context mock of MageTest\MagentoExtension\Context\MagentoContext
     */
    function it_initialises_the_context($context, $app, $config, $cache, $factory)
    {
        $context->setApp($app)->shouldBeCalled();
        $context->setConfigManager($config)->shouldBeCalled();
        $context->setCacheManager($cache)->shouldBeCalled();
        $context->setFixtureFactory($factory)->shouldBeCalled();
        $this->magentoAwareInitializer->initialize($context);
    }

}

Fix the example that seemed to simply not work..


<?php

//Gets the name of the case for inclusion on the case detail tab. Returns json.

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

$id = $_GET['id'];

$query = $dbh->prepare("SELECT id,first_name,last_name,organization FROM cm WHERE id = ? LIMIT 1");

		$query->bindParam(1,$id);

		$query->execute();

		$r = $query->fetch(PDO::FETCH_ASSOC);

		$tab_data = json_encode($r);

		echo $tab_data;

Add script that return json data for names on case tabs.

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@908 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php
namespace Ob_Ivan\Cache\Driver;

trait ExpiryTrait
{
    protected function normalizeExpiry($expiry)
    {
        if ($expiry instanceof DateTime) {
            return $expiry;
        }
        if (! $expiry) {
            return new DateTime('+1000years');
        }
        if (is_numeric($expiry)) {
            return new DateTime(intval($expiry) . 'sec');
        }
        throw new Exception('Unknown expiry format. Integer value or DateTime object was expected.');
    }

    protected function isExpired($expiry)
    {
        return $this->normalizeExpiry($expiry) < (new DateTime);
    }
}

Create trait to simplify implementation of new expiry argument semantics


<?php

namespace ZendTest\Code\TestAsset;

class NullNullableDefaultHintsClass
{
    public function arrayParameter(?array $foo = null)
    {
    }

    public function callableParameter(?callable $foo = null)
    {
    }

    public function intParameter(?int $foo = null)
    {
    }

    public function floatParameter(?float $foo = null)
    {
    }

    public function stringParameter(?string $foo = null)
    {
    }

    public function boolParameter(?bool $foo = null)
    {
    }

    public function selfParameter(?self $foo = null)
    {
    }

    public function nullDefaultHintsClassParameter(?NullDefaultHintsClass $foo = null)
    {
    }
}

Test asset: class with default-null nullable method parameters


<?php

namespace Frontend\Core\Header;

use Common\Cookie;
use Common\ModulesSettings;

final class GoogleAnalytics
{
    /** @var ModulesSettings */
    private $modulesSettings;

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

    /**
     * @return bool
     */
    private function shouldAddGoogleAnalyticsHtml(): bool
    {
        $siteHTMLHeader = (string) $this->modulesSettings->get('Core', 'site_html_header', '');
        $siteHTMLFooter = (string) $this->modulesSettings->get('Core', 'site_html_footer', '');
        $webPropertyId = (string) $this->modulesSettings->get('Analytics', 'web_property_id', null);

        return $webPropertyId !== ''
               && mb_strpos($siteHTMLHeader, $webPropertyId) === false
               && mb_strpos($siteHTMLFooter, $webPropertyId) === false;
    }

    /**
     * @return bool
     */
    private function shouldAnonymize(): bool
    {
        return $this->modulesSettings->get('Core', 'show_cookie_bar', false) && !Cookie::hasAllowedCookies();
    }

    /**
     * @return string
     */
    private function getGoogleAnalyticsEvent(): string
    {
        if ($this->shouldAnonymize()) {
            return 'ga(\'send\', \'pageview\', {\'anonymizeIp\': true});';
        }

        return 'ga(\'send\', \'pageview\');';
    }

    /**
     * @return string
     */
    public function __toString()
    {
        if (!$this->shouldAddGoogleAnalyticsHtml()) {
            return '';
        }

        $webPropertyId = $this->modulesSettings->get('Analytics', 'web_property_id', null);

        $request = $this->get('request');
        $trackingCode = '<script>
                          (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){
                          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                          })(window,document,\'script\',\'//www.google-analytics.com/analytics.js\',\'ga\');
                          ga(\'create\', \'' . $webPropertyId . '\', \'' . $request->getHttpHost() . '\');
                        ';
        $trackingCode .= $this->getGoogleAnalyticsEvent();
        $trackingCode .= '</script>';

        return $trackingCode;
    }
}

Move the handling of google analytics into a separate class


<?php
namespace Neos\Flow\Tests\Unit\Http\Helper;

use Neos\Flow\Http\Helper\ArgumentsHelper;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Http\Request;
use Neos\Flow\Tests\UnitTestCase;

/**
 * Tests for the RequestInformationHelper
 */
class RequestInformationHelperTest extends UnitTestCase
{
    /**
     * @test
     */
    public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
    {
        $request = Request::createFromEnvironment()
            ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
            ->withAddedHeader('Authorization', 'Bearer SomeToken');

        $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
        self::assertNotContains('SomePassword', $renderedHeaders);
        self::assertNotContains('SomeToken', $renderedHeaders);
    }
}

TASK: Add test covering undisclosed credentials


#!/usr/bin/env php
<?php
require dirname(__DIR__).'/vendor/autoload.php';

use Icicle\Concurrent\Worker\TaskInterface;
use Icicle\Concurrent\Worker\WorkerThread;
use Icicle\Coroutine;
use Icicle\Loop;

class HelloTask implements TaskInterface
{
    public function run()
    {
        echo "Hello!\n";
        return 42;
    }
}

Coroutine\create(function () {
    $worker = new WorkerThread();
    $worker->start();

    $returnValue = (yield $worker->enqueue(new HelloTask()));
    yield $worker->shutdown();
});

Loop\run();

Add example for worker thread

Add example for worker thread


<?php
/**
 * This file is part of the BootstrapBundle project.
 *
 * (c) 2013 Philipp Boes <mostgreedy@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace P2\Bundle\BootstrapBundle\Tests\Themeing;

/**
 * UnitTest ThemeTest
 * @package P2\Bundle\BootstrapBundle\Tests\Themeing
 */
class ThemeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * set up
     */
    protected function setUp()
    {
        parent::setUp();
    }

    /**
     * tear down
     */
    protected function tearDown()
    {
        parent::tearDown();
    }

    /**
     * @covers P2\Bundle\BootstrapBundle\Themeing::getPrimaryColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getSuccessColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getWarningColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getDangerColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getInfoColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getBodyBackground
     * @covers P2\Bundle\BootstrapBundle\Themeing::getTextColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonDefaultColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonDefaultBackground
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonDefaultBorder
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonPrimaryColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonSuccessColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonWarningColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonDangerColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getButtonInfoColor
     * @covers P2\Bundle\BootstrapBundle\Themeing::getName
     * @group s
     */
    public function testGetter()
    {
        $mock = $this->getMockForAbstractClass('P2\Bundle\BootstrapBundle\Themeing\Theme');
        $mock->expects($this->any())->method('getName')->will($this->returnValue('theme'));

        $this->assertEquals('', $mock->getPrimaryColor());
        $this->assertEquals('', $mock->getSuccessColor());
        $this->assertEquals('', $mock->getWarningColor());
        $this->assertEquals('', $mock->getDangerColor());
        $this->assertEquals('', $mock->getInfoColor());
        $this->assertEquals('', $mock->getBodyBackground());
        $this->assertEquals('', $mock->getTextColor());
        $this->assertEquals('', $mock->getButtonDefaultColor());
        $this->assertEquals('', $mock->getButtonDefaultBackground());
        $this->assertEquals('', $mock->getButtonDefaultBorder());
        $this->assertEquals('', $mock->getButtonPrimaryColor());
        $this->assertEquals('', $mock->getButtonSuccessColor());
        $this->assertEquals('', $mock->getButtonWarningColor());
        $this->assertEquals('', $mock->getButtonDangerColor());
        $this->assertEquals('', $mock->getButtonInfoColor());
        $this->assertEquals('theme', $mock->getName());
    }
}

Add unit test for theme

Add unit test for theme


<?php

$isInnoDb = function ($tableName) {
	$result = CM_Db_Db::exec("SHOW TABLE STATUS WHERE name = '" . $tableName . "'")->fetch();
	return $result['Engine'] === 'InnoDB';
};

if (!$isInnoDb('cm_streamChannel')) {
	CM_Db_Db::exec("ALTER TABLE  `cm_streamChannel` ENGINE = INNODB");
}

if (!$isInnoDb('cm_stream_publish')) {
	CM_Db_Db::exec("TRUNCATE TABLE  `cm_stream_publish`");
	CM_Db_Db::exec("ALTER TABLE  `cm_stream_publish` ENGINE = INNODB");
	CM_Db_Db::exec("ALTER TABLE  `cm_stream_publish` ADD FOREIGN KEY (  `channelId` ) REFERENCES  `skadate`.`cm_streamChannel` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;");
}
if (!$isInnoDb('cm_stream_subscribe')) {
	CM_Db_Db::exec("TRUNCATE TABLE  `cm_stream_subscribe`");
	CM_Db_Db::exec("ALTER TABLE  `cm_stream_subscribe` ENGINE = INNODB");
	CM_Db_Db::exec("ALTER TABLE  `cm_stream_subscribe` ADD FOREIGN KEY (  `channelId` ) REFERENCES  `skadate`.`cm_streamChannel` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ;");
}

Add update script to change table to InnoDB


<?php

if (CM_Db_Db::existsTable('cm_language')) {
    CM_Db_Db::exec('RENAME TABLE cm_language TO cm_model_language');
}

if (CM_Db_Db::existsTable('cm_languageKey')) {
    CM_Db_Db::exec('RENAME TABLE cm_languageKey TO cm_model_languagekey');
}

Rename table names to model-based with update script


<?php

namespace Picqer\Financials\Exact;

/**
 * Class SyncStockPosition
 *
 * @package Picqer\Financials\Exact
 * @see https://start.exactonline.nl/docs/HlpRestAPIResourcesDetails.aspx?name=SyncInventoryStockPositions
 *
 * @property int64 $Timestamp Timestamp
 * @property float $CurrentStock Number of items in stock
 * @property int $Division Division code
 * @property float $FreeStock Quantity of available stock
 * @property string $ID Primary Key
 * @property string $ItemCode Code of the item
 * @property string $ItemDescription Description of the item
 * @property string $ItemId A guid that is the unique identifier of the item
 * @property float $PlanningIn Number of items that are planned to come in
 * @property float $PlanningOut Number of items that are planned to go out
 * @property float $ProjectedStock The quantity of stock projected given all planned future stock changes
 * @property float $ReorderPoint Quantity of items as an indication of when you need to reorder more stock for the warehouse
 * @property float $ReservedStock The quantity in a back to back order process which is already received from the purchase order, but not yet delivered for the sales order.
 * @property string $UnitCode Code of item unit
 * @property string $UnitDescription Description of the item unit
 * @property string $Warehouse A guid that is the unique identifier of the warehouse
 * @property string $WarehouseCode Code of warehouse
 * @property string $WarehouseDescription Description of warehouse
 */
class SyncStockPosition extends Model
{
    use Query\Findable;
    use Persistance\Storable;

    protected $primaryKey = 'Timestamp';

    protected $fillable = [
        'Timestamp',
        'CurrentStock',
        'Division',
        'FreeStock',
        'ID',
        'ItemCode',
        'ItemDescription',
        'ItemId',
        'PlanningIn',
        'PlanningOut',
        'ProjectedStock',
        'ReorderPoint',
        'ReservedStock',
        'UnitCode',
        'UnitDescription',
        'Warehouse',
        'WarehouseCode',
        'WarehouseDescription',
    ];

    protected $url = 'sync/Inventory/StockPositions';
}

Add new Sync endpoint for the stock positions


<?php
if(!isset($_)) {//also provide standalone error page
	require_once '../../lib/base.php';

	$tmpl = new OC_Template( '', '403', 'guest' );
	$tmpl->printPage();
	exit;
}
?>

		<?php p($l->t( 'Access forbidden' )); ?>

		<?php print_unescaped($l->t( 'Ce service n\'est pas encore ouvert à toutes les unités CNRS, merci de contacter le SI de votre délégation pour plus d\'informations.' )); ?>

<?php if(isset($_['file'])) p($_['file'])?>
<?php p($l->t( 'Error' ));?> 403

<a target="_blank" class="button" href="<?php print_unescaped(OC_Config::getValue('custom_knowledgebaseurl',''));?>"><?php p($l->t('Documentation'));?>

Add specific 403 error page for shibboleth deny.


<?php

class Denkmal_Component_EventTest extends CMTest_TestCase {

    protected function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testRender() {
        $venue = DenkmalTest_TH::createVenue('My Venue');
        $event = Denkmal_Model_Event::create($venue, 'My Event', true, true, new DateTime('2017-01-01'));
        $component = new Denkmal_Component_Event(['event' => $event]);
        $html = $this->_renderComponent($component);

        $this->assertComponentAccessible($component);
        $this->assertContains('My Venue', $html->find('.event-description .venue')->getText());
        $this->assertContains('My Event', $html->find('.event-description .details')->getText());
    }

    public function testRenderWithoutPersistence() {
        $venue = new Denkmal_Model_Venue();
        $venue->setName('My Venue');

        $event = new Denkmal_Model_Event();
        $event->setDescription('My Event');
        $event->setGenres(null);
        $event->setStarred(false);
        $event->setSong(null);
        $event->setFrom(new DateTime('2017-01-01 02:00'));
        $event->setUntil(null);

        $component = new Denkmal_Component_Event(['event' => $event, 'venue' => $venue]);
        $html = $this->_renderComponent($component);

        $this->assertComponentAccessible($component);
        $this->assertContains('My Venue', $html->find('.event-description .venue')->getText());
        $this->assertContains('My Event', $html->find('.event-description .details')->getText());
    }

}

Add rendering test for event component

Add rendering test for event component


<?php

use Git4p\GitUser;

class GitUserTest extends PHPUnit_Framework_TestCase {

    protected $gituser = false;

    public function setup() {
        $this->gituser = new GitUser();
        $this->gituser->setName('Some User');
        $this->gituser->setEmail('some.user@example.com');
        $this->gituser->setTimestamp('1374058686');
        $this->gituser->setOffset('+0100');
    }

    public function teardown() {
        $this->gituser = false;
    }

    public function testShouldHaveName() {
        $this->assertEquals($this->gituser->name(), 'Some User');
    }

    public function testShouldHaveEmail() {
        $this->assertEquals($this->gituser->email(), 'some.user@example.com');
    }

    public function testShouldHaveTimestamp() {
        $this->assertEquals($this->gituser->timestamp(), '1374058686');
    }

    public function testShouldHaveOffset() {
        $this->assertEquals($this->gituser->offset(), '+0100');
    }

}

Add simple tests for user

Add simple tests for user


<?php

use PragmaRX\Tracker\Support\Migration;

class FixAgentName extends Migration
{
    /**
     * Table related to this migration.
     *
     * @var string
     */
    private $table = 'tracker_agents';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function migrateUp()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->dropUnique('tracker_agents_name_unique');
                }
            );

            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->mediumText('name')->unique()->change();
                }
            );
        } catch (\Exception $e) {
            dd($e);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function migrateDown()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->string('name', 255)->change();
                    $table->unique('name');
                }
            );
        } catch (\Exception $e) {
        }
    }
}

Fix agent too long problem

Fix agent too long problem


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
/**
 * 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_Db
 */

namespace Zend\I18n\Translator;

use Zend\ServiceManager\FactoryInterface;

/**
 * Translator.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class TranslatorServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        return Translator::factory($config['translator']);
    }
}

Add a service manager factory for the translator


<?php

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

global $tikilib;
include_once('tiki-setup_base.php');

function upgrade_20100207_repair_file_galleries_tiki( $installer ) {

	$cant = $installer->getOne('SELECT COUNT(*) FROM `tiki_file_galleries` WHERE `parentId` = -1 and `type` <> \'system\';');

	if ($cant > 0) {
		$sysId = $installer->getOne('SELECT `galleryId` FROM `tiki_file_galleries` WHERE `type` = \'system\';');
		$pref = $installer->getOne('SELECT COUNT(*) FROM `tiki_preferences` WHERE `name` = \'fgal_root_id\';');
		if ($pref > 0) {
			$result = $installer->query('UPDATE `tiki_preferences` SET `value` = ? WHERE `name` = \'fgal_root_id\';', $sysId);
		} else {
			$result = $installer->query('INSERT INTO `tiki_preferences` (`name`, `value`) VALUES (\'fgal_root_id\', ? );', $sysId);
		}
		$result = $installer->query('UPDATE `tiki_file_galleries` SET `parentId` = ? WHERE `parentId` = -1 and `type` <> \'system\'', array($sysId));
	}
}

[FIX] Correct problems with disappearing file galleries caused by 20090811_filegals_container_tiki.sql when running on MySQL 4.1 (wish3000).

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


<?php
/**
 * Database migration class
 *
 */
namespace Skeleton\File\Picture;

use \Skeleton\Database\Database;

class Migration_20190516_093222_Extra_defaults_for_field extends \Skeleton\Database\Migration {

	/**
	 * Migrate up
	 *
	 * @access public
	 */
	public function up() {
		$db = Database::get();
		$db->query("ALTER TABLE `picture`
					CHANGE `crop_width` `crop_width` int(11) NULL AFTER `height`,
					CHANGE `crop_height` `crop_height` int(11) NULL AFTER `crop_width`,
					CHANGE `crop_offset_left` `crop_offset_left` int(11) NULL AFTER `crop_height`,
					CHANGE `crop_offset_top` `crop_offset_top` int(11) NULL AFTER `crop_offset_left`;");

	}

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

	}
}

Allow all fields in table to be NULL

Allow all fields in table to be NULL


<?php
namespace pyd\testkit\interfaces;

/**
 * Interface for class that manages Yii app as a fixture.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
interface InterfaceYiiAppManager
{
    public function createYiiApp();

    public function destroyYiiApp();
}

Add an interface for class managing Yii app as a fixture


<?php namespace Indikator\News\Updates;

use October\Rain\Database\Updates\Migration;
use Schema;

class ChangeColumnsType2 extends Migration
{
    public function up()
    {
        Schema::table('indikator_news_posts', function ($table) {
            $table->smallInteger('featured')->default(2)->change();
            $table->integer('category_id')->default(0)->change();
            $table->index('category_id')->change();
            $table->index('featured')->change();
            $table->index('published_at')->change();
            $table->index('slug')->change();
        });

        Schema::table('indikator_news_categories', function ($table) {
            $table->integer('sort_order')->default(1)->change();
            $table->index('sort_order')->change();
            $table->index('slug')->change();
        });
    }

    public function down()
    {
        Schema::table('indikator_news_posts', function ($table) {
            $table->dropIndex('indikator_news_posts_slug_index')->change();
            $table->dropIndex('indikator_news_posts_category_id_index')->change();
            $table->dropIndex('indikator_news_posts_published_at_index')->change();
            $table->dropIndex('indikator_news_posts_featured_index')->change();
            $table->string('featured', 1)->default(2)->change();
            $table->string('category_id', 3)->default(0)->change();
        });

        Schema::table('indikator_news_categories', function ($table) {
            $table->dropIndex('indikator_news_categories_slug_index');
            $table->dropIndex('indikator_news_categories_sort_order_index');
            $table->string('sort_order', 3)->default(1)->change();
        });
    }
}

Change columns type and add index

Change columns type and add index

Optimize tables indikator_news_posts and indikator_news_categories


<?php

namespace AppBundle\Command;

use AppBundle\Entity\Path;
use AppBundle\Entity\Point;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ImportChateauPathCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('app:ImportChateauPathCommand')
            ->setDescription('Import of the Demo Path');

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getManager();
        $file = fopen('csv/abords-du-chateau.csv','r');
        fgetcsv($file);

        $path = new Path();
        $path->setName('Visite du Chateau de Sedan');
        $allPoints = new ArrayCollection();
        $rank = 0;
        while($fields = fgetcsv($file)){

            $point = new Point($path);

            $point ->setName($fields[0]);
            $point ->setDescription($fields[1]);
            $point ->setImage($fields[2]);
            $point ->setLatitude($fields[3]);
            $point ->setLongitude($fields[4]);
            $point ->setMajor($fields[5]);
            $point ->setMinor($fields[6]);
            $point -> setRank($rank);

            $em->persist($point);
            $allPoints->add($point);
            $rank++;
        }

        $path->setPoints($allPoints);
        $em->persist($path);

        $em->flush();
        $output->writeln("Import Finish");
    }
}

Add Command using to import the demostrations data


<?php
use Phinx\Migration\AbstractMigration;

class CreateSocialProfiles extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('social_profiles');
        $table
            ->addColumn('user_id', 'integer', [
                'default' => null,
                'limit' => 11,
                'null' => true,
            ])
            ->addColumn('provider', 'string', [
                'default' => null,
                'limit' => 255,
                'null' => false,
            ])
            ->addColumn('identifier', 'string', [
                'default' => null,
                'limit' => 255,
                'null' => false,
            ])
            ->addColumn('email', 'string', [
                'default' => null,
                'limit' => 255,
                'null' => false,
            ])
            ->addColumn('created', 'datetime', [
                'default' => null,
                'null' => true,
            ])
            ->addColumn('modified', 'datetime', [
                'default' => null,
                'null' => true,
            ])
            ->addIndex(
                [
                    'user_id',
                ]
            )
            ->addForeignKey(
                'user_id',
                'users',
                'id',
                [
                    'update' => 'RESTRICT',
                    'delete' => 'RESTRICT'
                ]
            )
            ->create();
    }
}

Add migrations file for social_profiles table


<?php

/**
 *  Example scrapping slashdot. More at http://simplehtmldom.sourceforge.net/
 */

	// Find all article blocks
	foreach($html->find('div.article') as $article) {
		$item['title']     = $article->find('div.title', 0)->plaintext;
		$item['intro']    = $article->find('div.intro', 0)->plaintext;
		$item['details'] = $article->find('div.details', 0)->plaintext;
		$articles[] = $item;
	}

	$log->addInfo(print_r($articles, TRUE));

Add Chen's example for slashdot.

Add Chen's example for slashdot.


<?php
namespace BK2K\BootstrapPackage\UserFunc;

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

use TYPO3\CMS\Core\Utility\VersionNumberUtility;

/**
 * This TypoScript condition compares an integer to the current TYPO3 version
 *
 * = Example =
 * [userFunc = \BK2K\BootstrapPackage\UserFunc\Typo3VersionCondition::match(lessThan, 7000000)]
 *   page.6 = TEXT
 *   page.6.value = LOWER CMS 7
 *   page.6.wrap = <div>|</div>
 * [global]
 *
 * @author Benjamin Kott <info@bk2k.info>
 */
class Typo3VersionCondition {

	/**
	 * @param string $operator
	 * @param integer $value
	 * @return bool
	 */
	public function match($operator = NULL, $value = NULL) {
		$result = FALSE;
		$version = VersionNumberUtility::convertVersionNumberToInteger(TYPO3_version);
		if ($value) {
			if ($operator === "equals" && $version === $value) {
				$result = TRUE;
			} else if ($operator === "lessThan" && $version < $value) {
				$result = TRUE;
			} else if ($operator === "greaterThan" && $version > $value) {
				$result = TRUE;
			}
		}
		return $result;
	}

}

Add TypoScript TYPO3 version condition

[FEATURE] Add TypoScript TYPO3 version condition


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

namespace PH7\Test\Unit\Framework\Url;

use PH7\Framework\Url\Url;
use PHPUnit_Framework_TestCase;

class UrlTest extends PHPUnit_Framework_TestCase
{
    public function testEncode()
    {
        $sUrl = 'https://ph7cms.com/my-route & the new_2£POST!';
        $sExpected = 'https%3A%2F%2Fph7cms.com%2Fmy-route+%26+the+new_2%C2%A3POST%21';

        $this->assertSame($sExpected, Url::encode($sUrl));
    }

    public function testDecode()
    {
        $sUrl = 'https://ph7cms.com/my-route & the new_2£POST!';
        $sExpected = 'https://ph7cms.com/my-route & the new_2£POST!';

        $this->assertSame($sExpected, Url::decode($sUrl));
    }

    /**
     * @param string $sUrl
     * @param string $sExpected
     *
     * @dataProvider urlsProvider
     */
    public function testClean($sUrl, $sExpected)
    {
        $this->assertSame($sExpected, Url::clean($sUrl));
    }

    /**
     * @return array
     */
    public function urlsProvider()
    {
        return [
            ['https://ph7cms.com/my post is this one', 'https://ph7cms.com/my%20post%20is%20this%20one'],
            ['https://ph7cms.com/?myparam=var&var2=value and value2', 'https://ph7cms.com/?myparam=var&var2=value%20and%20value2']
        ];
    }
}

Add unit test for Url class

Add unit test for Url class


<?php

declare(strict_types=1);

namespace Voronkovich\SberbankAcquiring\HttpClient;

use Symfony\Contracts\HttpClient\HttpClientInterface as ClientInterface;

/**
 * Adapter for the Symfony's HTTP client.
 *
 * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
 * @see https://symfony.com/doc/current/http_client.html
 */
class SymfonyAdapter implements HttpClientInterface
{
    private $client;

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

    public function request(string $uri, string $method = HttpClientInterface::METHOD_GET, array $headers = [], string $data = ''): array
    {
        $requestUri = $uri;
        $options = [
            'headers' => $headers
        ];

        switch ($method) {
            case HttpClientInterface::METHOD_GET:
                $requestUri = $uri . '?' . $data;
                break;
            case HttpClientInterface::METHOD_POST:
                $options['body'] = $data;
                break;
            default:
                throw new \InvalidArgumentException(
                    sprintf(
                        'Invalid HTTP method "%s". Use "%s" or "%s".',
                        $method,
                        HttpClientInterface::METHOD_GET,
                        HttpClientInterface::METHOD_POST
                    )
                );
                break;
        }

        $response = $this->client->request($method, $requestUri, $options);

        $statusCode = $response->getStatusCode();
        $body = $response->getContent();

        return [$statusCode, $body];
    }
}

Add adapter for Symfony's HTTP client

Add adapter for Symfony's HTTP client


<?php
declare(strict_types=1);

namespace Xerkus\Neovim\MsgpackRpc;

/**
 * This class exists for the sole reason: let Session avoid using properties
 * and as such avoid thread sharing handlers and by extension everything they
 * reference
 */
final class MessageHandler
{
    private $stream;
    private $requestHandler;
    private $notificationHandler;
    private $responseHandler;
    private $unknownTypeHandler;

    public function __construct(
        Stream $stream,
        callable $requestHandler,
        callable $notificationHandler,
        callable $responseHandler,
        callable $unknownTypeHandler = null
    ) {
        $this->stream = $stream;
        $this->requestHandler = $requestHandler;
        $this->notificationHandler = $notificationHandler;
        $this->responseHandler = $responseHandler;
        if (null === $unknownTypeHandler) {
            $unknownTypeHandler = [$this, 'handleUnknownType'];
        }
        $this->unknownTypeHandler = $unknownTypeHandler;
    }

    public function handleMessage(array $message)
    {
        $msg = print_r($message, true);
        fwrite(STDERR, $msg);
        try {
            switch ($message[0]) {
                case Session::TYPE_REQUEST:
                    $this->handleRequest($message);
                    break;
                case Session::onNotification:
                    $this->handleNotification($message);
                    break;
                case Session::TYPE_RESPONSE:
                    $this->handleResponse($message);
                    break;
                default:
                    ($this->unknownTypeHandler)($message);
            }
        } catch (\Exception $e) {
            // stack trace from host thread is useless
            $error = $e->getMessage();
            $this->stream->send([Session::TYPE_RESPONSE, 0, $error, null]);
            // rethrow exception. If it got here it is bad enough to stop host
            throw $e;
        }
    }

    private function handleRequest(array $message)
    {
        $id = $message[1];
        $rpcMethod = $message[2];
        $args = $message[3];
        ($this->requestHandler)(
            $rpcMethod,
            $args,
            new Response($this->stream, $id)
        );
    }

    private function handleNotification(array $message)
    {
        $rpcMethod = $message[1];
        $args = $message[2];
        ($this->notificationHandler)(
            $rpcMethod,
            $args
        );

    }

    private function handleResponse(array $message)
    {
        $id = $message[1];
        $error = $message[2];
        $result = $message[3];
        ($this->responseHandler)(
            $id,
            $error,
            $result
        );
    }

    private function handleUnknownType(array $message)
    {
        $error = 'Received invalid message: ' . print_r($message, true);
        $this->stream->send([self::TYPE_RESPONSE, 0, $error, null]);
    }
}

Move session callbacks to separate object and do not store references to it to prevent threaded sharing


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

namespace Google\Site_Kit\Tests\Core\Util;

use Google\Site_Kit\Context;
use Google\Site_Kit\Core\Util\Reset_Persistent;
use Google\Site_Kit\Tests\TestCase;
use Google\Site_Kit\Tests\OptionsTestTrait;
use Google\Site_Kit\Tests\UserOptionsTestTrait;
use Google\Site_Kit\Tests\TransientsTestTrait;

/**
 * @group Util
 */
class ResetPersistentTest extends TestCase {
	use OptionsTestTrait, UserOptionsTestTrait, TransientsTestTrait;

	public function test_all() {
		$context = new Context( GOOGLESITEKIT_PLUGIN_MAIN_FILE );
		$this->assertFalse( $context->is_network_mode() );
		update_option( 'googlesitekitpersistentkeep', 'keep' );
		update_option( 'googlesitekitpersistent-keep', 'keep' );

		$this->run_reset( $context );

		// Ensure options that don't start with googlesitekitpersistent_ are not deleted.
		$this->assertEquals( 'keep', get_option( 'googlesitekitpersistentkeep' ) );
		$this->assertEquals( 'keep', get_option( 'googlesitekitpersistent-keep' ) );
	}

	/**
	 * @group ms-required
	 */
	public function test_network_mode_all() {
		$this->network_activate_site_kit();
		$context = new Context( GOOGLESITEKIT_PLUGIN_MAIN_FILE );
		$this->assertTrue( $context->is_network_mode() );

		$this->run_reset( $context );
	}

	protected function run_reset( Context $context ) {
		wp_load_alloptions();
		$this->assertNotFalse( wp_cache_get( 'alloptions', 'options' ) );

		$user_id         = $this->factory()->user->create();
		$reset           = new Reset_Persistent( $context );
		$is_network_mode = $context->is_network_mode();

		$this->init_option_values( $is_network_mode );
		$this->init_user_option_values( $user_id, $is_network_mode );
		$this->init_transient_values( $is_network_mode );

		$reset->all();

		// Ensure options cache is flushed (must check before accessing other options as this will re-prime the cache)
		$this->assertFalse( wp_cache_get( 'alloptions', 'options' ) );
		$this->assertOptionsDeleted( $is_network_mode );
		$this->assertUserOptionsDeleted( $user_id, $is_network_mode );
		$this->assertTransientsDeleted( $is_network_mode );
	}
}

Add test cases for Reset Persistent.

Add test cases for Reset Persistent.


<?php

namespace PageExperience\Tests\Engine\EventDispatcher;

use PageExperience\Engine\Event;
use PageExperience\Tests\TestCase;
use PageExperience\Engine\StoppableEvent;
use PageExperience\Engine\ListenerProvider;
use PageExperience\Engine\EventDispatcher\BaseEventDispatcher;

/**
 * Test the BaseEventDispatcher class.
 *
 * @package ampproject/px-toolbox-php
 */
final class BaseEventDispatcherTest extends TestCase
{
    /**
     * Test the class instance.
     */
    public function testItCanBeInstantiated()
    {
        $listenProvider  = $this->createMock(ListenerProvider::class);
        $eventDispatcher = new BaseEventDispatcher($listenProvider);

        self::assertInstanceOf(BaseEventDispatcher::class, $eventDispatcher);
    }

    /**
     * Test dispatching a StoppableEvent which is stopped propagating.
     */
    public function testDispatchingStoppableEvent()
    {
        $event           = $this->createMock(StoppableEvent::class);
        $listenProvider  = $this->createMock(ListenerProvider::class);
        $eventDispatcher = new BaseEventDispatcher($listenProvider);

        $event->method('isPropagationStopped')->willReturn(true);

        $event = $eventDispatcher->dispatch($event);

        self::assertInstanceOf(StoppableEvent::class, $event);
    }

    /**
     * Test dispatching a StoppableEvent which is still propagating.
     */
    public function testDispatchingStoppableEventStillPropagating()
    {
        $event           = $this->createMock(StoppableEvent::class);
        $listenProvider  = $this->createMock(ListenerProvider::class);
        $eventDispatcher = new BaseEventDispatcher($listenProvider);

        $event->method('isPropagationStopped')->willReturn(false);
        $listenProvider->method('getListenersForEvent')->willReturn([function () {}]);

        $event = $eventDispatcher->dispatch($event);

        self::assertInstanceOf(StoppableEvent::class, $event);
    }

    /**
     * Test dispatching a regular Event.
     */
    public function testDispatchingEventToEventListener()
    {
        $event           = $this->createMock(Event::class);
        $listenProvider  = $this->createMock(ListenerProvider::class);
        $eventDispatcher = new BaseEventDispatcher($listenProvider);

        $listenProvider->method('getListenersForEvent')->willReturn([function () {}]);

        $event = $eventDispatcher->dispatch($event);

        self::assertInstanceOf(Event::class, $event);
    }
}

Add test cases for BaseEventDispatcher

Add test cases for BaseEventDispatcher


<?php

namespace Heystack\GiftWrapping\Traits;

use Heystack\GiftWrapping\GiftWrappingHandler;

/**
 * Class HasGiftWrappingHandlerTrait
 * @package Heystack\GiftWrapping\Traits
 */
trait HasGiftWrappingHandlerTrait
{
    /**
     * @var \Heystack\GiftWrapping\GiftWrappingHandler
     */
    protected $giftWrappingHandler;

    /**
     * @param \Heystack\GiftWrapping\GiftWrappingHandler $giftWrappingHandler
     */
    public function setGiftWrappingHandler(GiftWrappingHandler $giftWrappingHandler)
    {
        $this->giftWrappingHandler = $giftWrappingHandler;
    }

    /**
     * @return \Heystack\GiftWrapping\GiftWrappingHandler
     */
    public function getGiftWrappingHandler()
    {
        return $this->giftWrappingHandler;
    }
}

Add new has gift wrapping handler trait

Add new has gift wrapping handler trait


<?php

namespace Gaufrette\FileStream;

use Gaufrette\FileStream;
use Gaufrette\StreamMode;

/**
 * Local stream
 *
 * @author Antoine Hérault <antoine.herault@gmail.com>
 */
class Local implements FileStream
{
    private $path;
    private $fileHandle;

    /**
     * Constructor
     *
     * @param  string $path
     */
    public function __construct($path)
    {
        $this->path = $path;
    }

    /**
     * {@inheritDoc}
     */
    public function open(StreamMode $mode)
    {
        $fileHandle = fopen($this->path, $mode->getMode());

        if (false === $fileHandle) {
            return false;
        }

        $this->mode = $mode;
        $this->fileHandle = $fileHandle;

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function read($count)
    {
        return fread($this->fileHandle, $count);
    }

    /**
     * {@inheritDoc}
     */
    public function write($data)
    {
        return fwrite($this->fileHandle, $data);
    }

    /**
     * {@inheritDoc}
     */
    public function close()
    {
        $closed = fclose($this->fileHandle);

        if ($closed) {
            $this->mode = null;
            $this->fileHandle = null;
        }

        return $closed;
    }

    /**
     * {@inheritDoc}
     */
    public function flush()
    {
        return fflush($this->fileHandle);
    }

    /**
     * {@inheritDoc}
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        return fseek($this->fileHandle, $offset, $whence);
    }

    /**
     * {@inheritDoc}
     */
    public function tell()
    {
        return ftell($this->fileHandle);
    }

    /**
     * {@inheritDoc}
     */
    public function eof()
    {
        return feof($this->fileHandle);
    }
}

Add local file stream class

Add local file stream class


<?php

namespace Backend\Modules\Blog\Tests\Action;

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

class IndexTest 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/index');

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

Test that you need to be logged in to see the tags index action


<?php

namespace FD\PrivateMessageBundle\Tests\EventSubscriber;

use Doctrine\ORM\EntityManager;
use FD\PrivateMessageBundle\Entity\Conversation;
use FD\PrivateMessageBundle\Event\ConversationEvent;
use FD\PrivateMessageBundle\EventSubscriber\LeaveConversationSubscriber;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Class LeaveConversationSubscriberTest.
 */
class LeaveConversationSubscriberTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test onConversationLeft with a conversation having no more recipients.
     */
    public function testOnConversationLeftRemove()
    {
        /** @var Request $request */
        $request = $this->getMock(Request::class);
        /** @var UserInterface $user */
        $user    = $this->getMock(UserInterface::class);
        $em = $this->getMockBuilder(EntityManager::class)
            ->disableOriginalConstructor()
            ->getMock();

        $em->expects($this->once())->method('remove');
        $em->expects($this->once())->method('flush');

        $service      = new LeaveConversationSubscriber($em);
        $conversation = new Conversation();
        $event        = new ConversationEvent($conversation, $request, $user);

        $service->onConversationLeft($event);
    }

    /**
     * Test onConversationLeft with a conversation still having recipients.
     */
    public function testOnConversationLeft()
    {
        /** @var Request $request */
        $request = $this->getMock(Request::class);
        /** @var UserInterface $user */
        $user    = $this->getMock(UserInterface::class);
        $em = $this->getMockBuilder(EntityManager::class)
            ->disableOriginalConstructor()
            ->getMock();

        $em->expects($this->never())->method('remove');
        $em->expects($this->never())->method('flush');

        $conversation = new Conversation();
        $conversation->addRecipient($user);

        $service      = new LeaveConversationSubscriber($em);
        $event        = new ConversationEvent($conversation, $request, $user);

        $service->onConversationLeft($event);
    }
}

Add unit test for LeaveConversationSubscriber