<?php

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

namespace Symfony\Component\HttpKernel;

/**
 * Client simulates a browser and makes requests to an HttpKernel instance.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @method Request  getRequest()  A Request instance
 * @method Response getResponse() A Response instance
 */
class HttpKernelBrowser extends Client
{
}

<?php

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

namespace Symfony\Component\HttpKernel;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Client simulates a browser and makes requests to an HttpKernel instance.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @method Request  getRequest()  A Request instance
 * @method Response getResponse() A Response instance
 */
class HttpKernelBrowser extends Client
{
}

[HttpKernel] Fix missing use for request and response classes


<?php

class Relax_Openssl_PrivateKeyTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->privateKey = tmpfile();
        $this->passPhrase = 'llamas love long passphrases';

        $this->pkey = openssl_pkey_new();
        openssl_pkey_export($this->pkey, $pkey, $this->passPhrase);
        fwrite($this->privateKey, $pkey);
        fflush($this->privateKey);
        $pkey_metadata = stream_get_meta_data($this->privateKey);
        $this->privateKeyPath = $pkey_metadata['uri'];
    }

    public function testValidPassphrase()
    {
        $pkey = new Relax_Openssl_PrivateKey(
            $this->privateKeyPath, false,
            $this->passPhrase
        );

        $this->assertTrue($pkey->isValid());
    }

    public function testInvaludPassphrase()
    {
        $pkey = new Relax_Openssl_PrivateKey(
            $this->privateKeyPath, false,
            'llamas hate invalid passphrases'
        );

        $this->assertFalse($pkey->isValid());
    }
}

Test passphrases are correctly checked

Test passphrases are correctly checked


<?php
//----------------------------------------------------------------------
// Copyright (c) 2012 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// 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 Work.
//
// THE WORK 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 WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

/**
 * Functions to help with file handling.
 */

/**
 * Write $data to a temp file and return the filename.  An optional
 * file prefix can be specified.
 *
 * NOTE: The caller is responsible for deleting ("unlink") the file
 * when it is no longer needed.
 *
 *     $fname = writeDataToTempFile($mydata, "foo-");
 *     doSomething($fname);
 *     unlink($fname);
 */
function writeDataToTempFile($data, $prefix = "geni-")
{
  $tmpfile = tempnam(sys_get_temp_dir(), $prefix);
  file_put_contents($tmpfile, $data);
  return $tmpfile;
}

?>

Add a file utilities library.

Add a file utilities library.

Add function writeDataToTempFile to capture a common pattern of
creating a temp file and writing a blob of data to
it. writeDataToTempFile returns the temp file name so it can be
deleted after use.


<?php

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

class m150804_080424_create_adjacency_list_comment_table extends Migration
{
    public function up()
    {
        $this->createTable('{{%comment_al}}', [
            'id' => Schema::TYPE_PK,

            'post_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'author_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'parent_id' => Schema::TYPE_INTEGER . ' NULL',

            'text' => Schema::TYPE_TEXT . ' NOT NULL',

            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
            'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ]);

        $this->createIndex('comment_al__post_id', '{{%comment_al}}', 'post_id');
        $this->addForeignKey('comment_al__post_id', '{{%comment_al}}', 'post_id', '{{%post}}', 'id', 'CASCADE', 'RESTRICT');

        $this->createIndex('comment_al__author_id', '{{%comment_al}}', 'author_id');
        $this->addForeignKey('comment_al__author_id', '{{%comment_al}}', 'author_id', '{{%user}}', 'id', 'CASCADE', 'RESTRICT');

        $this->createIndex('comment_al__parent_id', '{{%comment_al}}', 'parent_id');
        $this->addForeignKey('comment_al__parent_id', '{{%comment_al}}', 'parent_id', '{{%user}}', 'id', 'CASCADE', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('comment_al__post_id', '{{%comment_al}}');
        $this->dropIndex('comment_al__post_id', '{{%comment_al}}');

        $this->dropForeignKey('comment_al__author_id', '{{%comment_al}}');
        $this->dropIndex('comment_al__author_id', '{{%comment_al}}');

        $this->dropForeignKey('comment_al__parent_id', '{{%comment_al}}');
        $this->dropIndex('comment_al__parent_id', '{{%comment_al}}');

        $this->dropTable('{{%comment_al}}');
    }
}

Add adjacency list comment table.

Add adjacency list comment table.


<?php

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

class UsersTableRenameGroupColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table) {
            $table->renameColumn('group', 'group_id');
        });
    }

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

Add database migration for renaming group column to group_id within the users table.


<?php

namespace Backend\Modules\Pages\Domain\Page\Form;

use Backend\Modules\Pages\Domain\Page\PageDataTransferObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class PageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {

    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'data_class' => PageDataTransferObject::class,
            ]
        );
    }
}

Create base form for a page

Create base form for a page


<?php

namespace Aedart\Laravel\Helpers\Contracts\Cookie;

use Illuminate\Contracts\Cookie\QueueingFactory;

/**
 * Queueing Cookie Aware
 *
 * @see \Illuminate\Contracts\Cookie\QueueingFactory
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Laravel\Helpers\Contracts\Cookie
 */
interface QueueingCookieAware
{
    /**
     * Set queueing cookie
     *
     * @param QueueingFactory|null $factory Queueing Cookie Factory instance
     *
     * @return self
     */
    public function setQueueingCookie(?QueueingFactory $factory);

    /**
     * Get queueing cookie
     *
     * If no queueing cookie has been set, this method will
     * set and return a default queueing cookie, if any such
     * value is available
     *
     * @see getDefaultQueueingCookie()
     *
     * @return QueueingFactory|null queueing cookie or null if none queueing cookie has been set
     */
    public function getQueueingCookie(): ?QueueingFactory;

    /**
     * Check if queueing cookie has been set
     *
     * @return bool True if queueing cookie has been set, false if not
     */
    public function hasQueueingCookie(): bool;

    /**
     * Get a default queueing cookie value, if any is available
     *
     * @return QueueingFactory|null A default queueing cookie value or Null if no default value is available
     */
    public function getDefaultQueueingCookie(): ?QueueingFactory;
}

Add queueing cookie aware component

Add queueing cookie aware component


<?php
//----------------------------------------------------------------------
// Copyright (c) 2012 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// 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 Work.
//
// THE WORK 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 WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

//--------------------------------------------------
// Utilities for the slice authority
//--------------------------------------------------

require_once("sa_settings.php");

/**
 * Create a slice certificate and return it.
 *
 * The result is a string containing the PEM encoded certificate.
 */
function create_slice_certificate($slice_name, $slice_email, $slice_uuid,
                                  $cert_life_days, $auth_cert_file,
                                  $auth_key_file)
{
  global $sa_mkslicecert_prog;
  global $sa_gcf_include_path;

  // Run slicecred.py and return it as the content.
  $cmd_array = array($sa_mkslicecert_prog,
                     '--gcfpath',
                     $sa_gcf_include_path,
                     $auth_cert_file,
                     $auth_key_file,
                     $slice_name,
                     $cert_life_days,
                     $slice_email,
                     $slice_uuid);
  $command = implode(" ", $cmd_array);
  $result = exec($command, $output, $status);

  /* The slice certificate is printed to stdout, which is captured in
     $output as an array of lines. Crunch them all together in a
     single string, separated by newlines.
  */
  $slice_cert = implode("\n", $output);
  return $slice_cert;
}

?>

Add SA slice cert interface.

Add SA slice cert interface.

SA create_slice_certificate invokes mkslicecert with appropriate
arguments to generate a long-lived slice certificate.


<?php

/*
 * This file is part of the HWIOAuthBundle package.
 *
 * (c) Hardware.Info <opensource@hardware.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace HWI\Bundle\OAuthBundle\Tests\OAuth\ResourceOwner;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\OdnoklassnikiResourceOwner;
use Symfony\Component\HttpFoundation\Request;

class OdniklassnikiResourceOwnerTest extends GenericOAuth2ResourceOwnerTest
{
    protected $userResponse = <<<json
{
    "id": "1",
    "username": "bar"
}
json;

    protected $paths = array(
        'identifier' => 'id',
        'nickname'   => 'username',
        'realname'   => 'name',
    );

    protected function setUpResourceOwner($name, $httpUtils, array $options)
    {
        $options = array_merge(
            array(
                'authorization_url'         => 'http://www.odnoklassniki.ru/oauth/authorize',
                'access_token_url'          => 'http://api.odnoklassniki.ru/oauth/token.do',
                'infos_url'                 => 'http://api.odnoklassniki.ru/fb.do?method=users.getCurrentUser',

                'odnoklassniki_app_key'     => '123456',
            ),
            $options
        );

        return new OdnoklassnikiResourceOwner($this->buzzClient, $httpUtils, $options, $name);
    }
}

Add odnoklassniki resource owner test

Add odnoklassniki resource owner test


<?php

namespace Tests\AppBundle\API\Listing;

use AppBundle\API\Webservice;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

class ProjectsTest extends WebTestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';

    public function testExecute()
    {
        $container = static::createClient()->getContainer();
        $default_db = $container->getParameter('default_db');
        $service = $container->get('app.api.webservice')->factory('listing', 'projects');
        $session = new MockArraySessionStorage();

        //Test for error returned by user is not logged in
        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db)),
            $session
        );
        $expected = array("error" => Webservice::ERROR_NOT_LOGGED_IN, "data" => array());

        $this->assertEquals($expected, $results);

        //Test of correct project if the user has only one project
        $session->set('user', array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        ));
        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db)),
            $session
        );
        $expected = array("data" => array(
                array(
                    "id" => "table_1",
                    "import_date" => "2016-05-17 10:00:52.627236+00",
                    "rows" => 10,
                    "columns" => 5,
                    "import_filename" => "listingProjectsTestFile.biom"
                )
            )
        );
        $this->assertArraySubset($expected, $results);
    }
}

Add test for listing projects webservice


<?php
/*
 * This file is part of the prooph/common.
 * (c) 2014-2015 prooph software GmbH <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 22.08.15 - 15:00
 */
namespace ProophTest\Common\Messaging;

use PHPUnit_Framework_TestCase as TestCase;
use Prooph\Common\Messaging\DomainMessage;
use Prooph\Common\Messaging\Message;
use Prooph\Common\Messaging\NoOpMessageConverter;

/**
 * Class NoOpMessageConverterTest
 *
 * @package ProophTest\Common\Messaging
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class NoOpMessageConverterTest extends TestCase
{
    /**
     * @test
     */
    public function it_converts_to_array()
    {
        $messageMock = $this->getMockForAbstractClass(DomainMessage::class, [], '', true, true, true, ['toArray']);
        $messageMock->expects($this->once())->method('toArray');

        $converter = new NoOpMessageConverter();
        $converter->convertToArray($messageMock);
    }

    /**
     * @test
     * @expectedException Assert\InvalidArgumentException
     * @expectedExceptionMessage was expected to be instanceof of "Prooph\Common\Messaging\DomainMessage" but is not.
     */
    public function it_throws_exception_when_message_is_not_a_domain_message()
    {
        $messageMock = $this->getMockForAbstractClass(Message::class);

        $converter = new NoOpMessageConverter();
        $converter->convertToArray($messageMock);
    }
}

Add no op message converter test

Add no op message converter test


<?php
class PDOIterator implements Iterator {
    private $position = 0;
    private $pdo;
    private $fetchMode;
    private $nextResult;

    public function __construct(PDOStatement $pdo, $fetchMode = PDO::FETCH_ASSOC) {
        $this->position = 0;
        $this->pdo = $pdo;
        $this->fetchMode = $fetchMode;
    }

    function rewind() {
        $this->position = 0;
        $this->pdo->execute();
    }

    function current() {
        return $this->nextResult;
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
        $this->nextResult = $this->pdo->fetch($this->fetchMode, PDO::FETCH_ORI_NEXT);
    }

    function valid() {
        $invalid = $this->nextResult === false;
        if ($invalid) {
            $this->pdo->closeCursor();
        }
        return !$invalid;
    }
}

Add a PDO iterator object.

Add a PDO iterator object.


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Test\Package\Loader;

use Composer\Package\Loader\RootPackageLoader;
use Composer\Test\Mock\ProcessExecutorMock;

class RootPackageLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testDetachedHeadBecomesDevHash()
    {
        if (!function_exists('proc_open')) {
            $this->markTestSkipped('proc_open() is not available');
        }

        $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';

        $manager = $this->getMockBuilder('\\Composer\\Repository\\RepositoryManager')
            ->disableOriginalConstructor()
            ->getMock();

        $self = $this;

        /* Can do away with this mock object when https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81 is fixed */
        $processExecutor = new ProcessExecutorMock(function($command, &$output = null, $cwd = null) use ($self, $commitHash) {
            $self->assertStringStartsWith('git branch', $command);

            $output = "* (no branch) $commitHash Commit message\n";

            return 0;
        });

        $loader = new RootPackageLoader($manager, null, $processExecutor);
        $package = $loader->load(array());

        $this->assertEquals("dev-$commitHash", $package->getVersion());
    }
}

Test for detached heads yielding an invalid version


<?php

namespace Tests\PDO\PDO;

use Stratedge\Wye\Wye;
use Tests\TestCase;

class LastInsertIdTest extends TestCase
{
    public function testReturnsGivenValueAsString()
    {
        $pdo = Wye::makePDO();

        $result = Wye::makeResult();
        $result->lastInsertId(5);
        $result->attach();

        $statement = $pdo->prepare('INSERT INTO apparatus');
        $statement->execute();

        $this->assertSame('5', $pdo->lastInsertId());
    }

    public function testReturnsNullByDefault()
    {
        $pdo = Wye::makePDO();

        $result = Wye::makeResult()->attach();

        $statement = $pdo->prepare('INSERT INTO apparatus');
        $statement->execute();

        $this->assertNull($pdo->lastInsertId());
    }
}

Add very basic unit tests for PDO::lastInsertId()


2017 Registration<a href="<?php echo base_url('admin/audit_started_2017/excel_phase2_1') ?>"><button class="exportBtn">Export to Excel</button>

            S.No
            Sch.Id
	    Udise
            School Name
            pincode
            City
            State
            District
            Co-ord. Name
            Co-ord. Email
            Co-ord. Mobile
            Progress

            Action

        <?php //echo '
'; print_r($record); ?>

          <?php $i=1; foreach($record as $r){ ?>
            <tr role="row" class="<?php echo ($i%2==0) ? "even" : "odd"; ?>">
                <?php echo $i; ?>
                <?php echo $r->id; ?>
		<?php echo $r->udise; ?>
                <?php echo $r->name; ?>
                <?php echo $r->pincode; ?>
                <?php echo $r->city; ?>
                <?php echo $r->state_name; ?>
                <?php echo $r->district_name; ?>
                <?php echo $r->coname; ?>
                <?php echo $r->coemail; ?>
                <?php echo $r->comobile; ?>
                <?php echo $r->progress; ?>
                <a target="_blank" href="<?php echo base_url('admin/audit_started_2017/response/').$r->id; ?>" title="View Responses"><img src="<?php echo base_url() ?>assets/front/images/1446146277_view6.png">

          <?php $i++; } ?>

Add New File Reperest Phase 2 New Registration

Add New File Reperest Phase 2 New Registration


<?php

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

class UpdateDevelopersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if(Schema::hasTable('developers')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->renameColumn('name_jp', 'original');
                $table->renameColumn('name_en', 'romaji');
                $table->string('furi')->nullable()->comment('Hiragana/katakana depending on the original name between native Japanese or foreign name. Null value is aceptable mainly for original name that is already in hiragana/katakana.');
            });
        }
        if(Schema::hasTable('developers')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->string('original')->nullable(false)->default(false)->change();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if(Schema::hasTable('developers')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->string('original')->nullable()->default('')->change();
            });
        }
        if(Schema::hasTable('developers')) {
            Schema::table('developers', function(Blueprint $table) {
                $table->dropColumn(['furi']);
                $table->renameColumn('romaji', 'name_en');
                $table->renameColumn('original', 'name_jp');
            });
        }
    }
}

Set migration to update developers table

- Rename name_jp to original
- Rename name_en to romaji
- Add furi column


<?php

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

class AddJidToJidFromIndexesToMessages extends Migration
{
    public function up()
    {
        $this->schema->table('messages', function(Blueprint $table) {
            $table->index(['user_id', 'jidfrom', 'jidto', 'id'])->nullable();
        });
    }

    public function down()
    {
        $this->schema->table('messages', function(Blueprint $table) {
            $table->dropIndex('messages_user_id_jidfrom_jidto_id_index');
        });

    }
}

Add indexes to Messages table

Add indexes to Messages table


<?php

use Movim\Migration;
use App\Info;

class ClearBuggyPubsubNodesInInfosTable extends Migration
{
    public function up()
    {
        Info::where('node', '0')->delete();
    }

    public function down()
    {

    }
}

Migrate the Info table to clear the bad cache


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

/**
 * @author Mark Unwin <marku@opmantek.com>
 *
 * @version   1.14.4

 *
 * @copyright Copyright (c) 2014, Opmantek
 * @license http://www.gnu.org/licenses/agpl-3.0.html aGPL v3
 */

include('v_devices_collection.php');

Add a template that simply calls v_devices_collection for output.


<?php

namespace React\Tests\ChildProcess;

use React\EventLoop\ExtEventLoop;

class ExtEventLoopProcessTest extends AbstractProcessTest
{
    public function createLoop()
    {
        if (!extension_loaded('event')) {
            $this->markTestSkipped('ext-event is not installed.');
        }
        if (!class_exists('React\EventLoop\ExtEventLoop')) {
            $this->markTestSkipped('ext-event not supported by this legacy react/event-loop version');
        }

        return new ExtEventLoop();
    }
}

Test against ext-event if available

Test against ext-event if available


<?php
/**
 * @project RestServer
 * @author Jens Kohl <jens.kohl@milchundzucker.de>
 * @since 2014-07-31 13:17
 */

namespace JK\RestServer;

/**
 * Class Language
 * Should represent the parsed Accept-Language
 *
 * Probably will change in the future
 *
 * @package JK\RestServer
 */
class Language extends \SplEnum {
    const __default = self::EN;

    const DE = "de";
    const DE_DE = "de_DE";
    const EN = "en";
}

Add class to represent a requested language


<?php
function cdash_testsuite_unlink($filename)
{
  $try_count = 1;
  echo "unlink '".$filename."'\n";
  $success = unlink($filename);

  while(file_exists($filename) && $try_count < 300)
  {
    usleep(1000000); // == 1000 ms, == 1.0 seconds

    $try_count++;
    echo "attempt $try_count to unlink '".$filename."'\n";
    $success = unlink($filename);
  }

  if ($try_count > 3)
  {
    echo "excessive try_count=$try_count unlinking '".$filename."'\n";
  }

  if (file_exists($filename))
  {
    throw new Exception("file still exists after unlink: $filename");
  }

  return $success;
}
?>

ENH: Add cdash_unlink and cdash_testsuite_unlink: debug/fix unlink problems

git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@3443 91079597-3006-4846-9bd3-4f3fb3d139a7


<?php

return [
    // string, required, root directory of all source files
    'sourcePath' => __DIR__ . DIRECTORY_SEPARATOR . '..',
    // array, required, list of language codes that the extracted messages
    // should be translated to. For example, ['zh-CN', 'de'].
    'languages' => ['ro_MD'],
    // string, the name of the function for translating messages.
    // Defaults to 'Yii::t'. This is used as a mark to find the messages to be
    // translated. You may use a string for single function name or an array for
    // multiple function names.
    'translator' => 'Yii::t',
    // boolean, whether to sort messages by keys when merging new messages
    // with the existing ones. Defaults to false, which means the new (untranslated)
    // messages will be separated from the old (translated) ones.
    'sort' => false,
    // boolean, whether to remove messages that no longer appear in the source code.
    // Defaults to false, which means each of these messages will be enclosed with a pair of '@@' marks.
    'removeUnused' => false,
    // array, list of patterns that specify which files/directories should NOT be processed.
    // If empty or not set, all files/directories will be processed.
    // A path matches a pattern if it contains the pattern string at its end. For example,
    // '/a/b' will match all files and directories ending with '/a/b';
    // the '*.svn' will match all files and directories whose name ends with '.svn'.
    // and the '.svn' will match all files and directories named exactly '.svn'.
    // Note, the '/' characters in a pattern matches both '/' and '\'.
    // See helpers/FileHelper::findFiles() description for more details on pattern matching rules.
    'only' => ['*.php'],
    // array, list of patterns that specify which files (not directories) should be processed.
    // If empty or not set, all files will be processed.
    // Please refer to "except" for details about the patterns.
    // If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
    'except' => [
        '.svn',
        '.git',
        '.gitignore',
        '.gitkeep',
        '.hgignore',
        '.hgkeep',
        '/messages',
    ],

    // 'php' output format is for saving messages to php files.
    'format' => 'php',
    // Root directory containing message translations.
    'messagePath' => __DIR__,
    // boolean, whether the message file should be overwritten with the merged messages
    'overwrite' => false,

    /*
    // 'db' output format is for saving messages to database.
    'format' => 'db',
    // Connection component to use. Optional.
    'db' => 'db',
    // Custom source message table. Optional.
    // 'sourceMessageTable' => '{{%source_message}}',
    // Custom name for translation message table. Optional.
    // 'messageTable' => '{{%message}}',
    */

    /*
    // 'po' output format is for saving messages to gettext po files.
    'format' => 'po',
    // Root directory containing message translations.
    'messagePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
    // Name of the file that will be used for translations.
    'catalog' => 'messages',
    // boolean, whether the message file should be overwritten with the merged messages
    'overwrite' => true,
    */
];

Prepare for source message translations

Prepare for source message translations


<?php
/**
 * Copyright 2017 The WildPHP Team
 *
 * You should have received a copy of the MIT license with the project.
 * See the LICENSE file for more information.
 */

use PHPUnit\Framework\TestCase;
use WildPHP\Modules\LinkSniffer\Backends\LinkTitle;

class LinkTitleBackendTest extends TestCase
{
	public function initializeLinkTitleBackend()
	{
		$loop = \React\EventLoop\Factory::create();
		return new LinkTitle($loop);
	}

	public function testLinkTitle()
	{
		$expected = new \WildPHP\Modules\LinkSniffer\BackendResult('https://www.google.nl/', 'Google');

		$linkTitleBackend = $this->initializeLinkTitleBackend();
		$promise = $linkTitleBackend->request('https://www.google.nl/');

		$promise->then(function (\WildPHP\Modules\LinkSniffer\BackendResult $result) use ($expected)
		{
			self::assertEquals($expected, $result);
		});
	}
}

Add a simple LinkTitle test

Add a simple LinkTitle test

Signed-off-by: Yoshi2889 <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com>


<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\RequestSpec;

class DefaultLocationTypeProvider implements Generic\SpecProviderInterface {

  /**
   * @inheritDoc
   */
  public function modifySpec(RequestSpec $spec) {
    $locationField = $spec->getFieldByName('location_type_id')->setRequired(TRUE);
    $defaultType = \CRM_Core_BAO_LocationType::getDefault();
    if ($defaultType) {
      $locationField->setDefaultValue($defaultType->id);
    }
  }

  /**
   * @inheritDoc
   */
  public function applies($entity, $action) {
    return $action === 'create' && in_array($entity, ['Address', 'Email', 'IM', 'OpenID', 'Phone']);
  }

}

Set default location type for Address, Email, IM, OpenID, Phone


<?php
/**
 * Lithium: the most rad php framework
 *
 * @copyright     Copyright 2011, Union of RAD (http://union-of-rad.org)
 * @license       http://opensource.org/licenses/bsd-license.php The BSD License
 */

namespace lithium\data\source\database\adapter\my_sql;

use lithium\data\source\database;

class Result extends \lithium\data\source\database\Result {

	public function prev() {
		if ($this->_current = $this->_prev()) {
			$this->_iterator--;
			return $this->_current;
		}
	}

	protected function _prev() {
		if ($this->_resource && $this->_iterator) {
			if(mysql_data_seek($this->_resource, $this->_iterator -1)) {
				return mysql_fetch_row($this->_resource);
			}
		}
	}

	protected function _next() {
		if ($this->_resource) {
			$inRange = $this->_iterator < mysql_num_rows($this->_resource);
			if($inRange && mysql_data_seek($this->_resource, $this->_iterator)) {
				return mysql_fetch_row($this->_resource);
			}
		}
	}

	protected function _close() {
		if ($this->_resource) {
			mysql_free_result($this->_resource);
		}
	}
}

?>

<?php
/**
 * Lithium: the most rad php framework
 *
 * @copyright     Copyright 2011, Union of RAD (http://union-of-rad.org)
 * @license       http://opensource.org/licenses/bsd-license.php The BSD License
 */

namespace lithium\data\source\database\adapter\my_sql;

class Result extends \lithium\data\source\database\Result {

	public function prev() {
		if ($this->_current = $this->_prev()) {
			$this->_iterator--;
			return $this->_current;
		}
	}

	protected function _prev() {
		if ($this->_resource && $this->_iterator) {
			if(mysql_data_seek($this->_resource, $this->_iterator -1)) {
				return mysql_fetch_row($this->_resource);
			}
		}
	}

	protected function _next() {
		if ($this->_resource) {
			$inRange = $this->_iterator < mysql_num_rows($this->_resource);
			if($inRange && mysql_data_seek($this->_resource, $this->_iterator)) {
				return mysql_fetch_row($this->_resource);
			}
		}
	}

	protected function _close() {
		if ($this->_resource) {
			mysql_free_result($this->_resource);
		}
	}
}

?>

Remove superfluous use statement (thanks eclipse!!)


<?php namespace ThibaudDauce\EloquentVariableModelConstructor;

trait VariableModelConstructorTrait {

  /**
   * Database field indicated class name.
   *
   * @var string
   */
  protected $class_name_field = 'class_name';

  /**
   * Create a new model instance that is existing.
   *
   * @override Illuminate\Database\Eloquent\Model
   * @param  array  $attributes
   * @return \Illuminate\Database\Eloquent\Model|static
   */
  public function newFromBuilder($attributes = array())
  {
    if (!isset($attributes->$class_name_field))
      return parent::newFromBuilder($attributes);

    $class = $attributes->$class_name_field;
    $instance = new $class;

    $instance->setRawAttributes((array) $attributes, true);

    return $instance;
  }

}

Add variable model constructor trait

Add variable model constructor trait


<?php
/**
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Authentication\Tests;

use Joomla\Authentication\AbstractUsernamePasswordAuthenticationStrategy;
use Joomla\Authentication\Authentication;
use Joomla\Authentication\Password\HandlerInterface;
use PHPUnit\Framework\TestCase;

/**
 * Test class for \Joomla\Authentication\AbstractUsernamePasswordAuthenticationStrategy
 */
class AbstractUsernamePasswordAuthenticationStrategyTest extends TestCase
{
	/**
	 * @testdox  A user can be successfully authenticated
	 *
	 * @covers   Joomla\Authentication\AbstractUsernamePasswordAuthenticationStrategy
	 */
	public function testAuthenticateSuccess()
	{
		$handler = $this->createMock(HandlerInterface::class);
		$handler->expects($this->once())
			->method('validatePassword')
			->willReturn(true);

		$strategy = new class($handler) extends AbstractUsernamePasswordAuthenticationStrategy
		{
			public function authenticate()
			{
				return $this->doAuthenticate('username', 'password');
			}

			protected function getHashedPassword($username)
			{
				return 'password';
			}
		};

		$this->assertSame('username', $strategy->authenticate());
		$this->assertSame(Authentication::SUCCESS, $strategy->getResult(), 'The correct result status is set');
	}

	/**
	 * @testdox  A user cannot be authenticated when a password cannot be found for the username
	 *
	 * @covers   Joomla\Authentication\AbstractUsernamePasswordAuthenticationStrategy
	 */
	public function testAuthenticateNoUser()
	{
		$handler = $this->createMock(HandlerInterface::class);
		$handler->expects($this->never())
			->method('validatePassword');

		$strategy = new class($handler) extends AbstractUsernamePasswordAuthenticationStrategy
		{
			public function authenticate()
			{
				return $this->doAuthenticate('username', 'password');
			}

			protected function getHashedPassword($username)
			{
				return false;
			}
		};

		$this->assertFalse($strategy->authenticate());
		$this->assertSame(Authentication::NO_SUCH_USER, $strategy->getResult(), 'The correct result status is set');
	}

	/**
	 * @testdox  A user cannot be authenticated when the password cannot be validated
	 *
	 * @covers   Joomla\Authentication\AbstractUsernamePasswordAuthenticationStrategy
	 */
	public function testAuthenticateInvalidPassword()
	{
		$handler = $this->createMock(HandlerInterface::class);
		$handler->expects($this->once())
			->method('validatePassword')
			->willReturn(false);

		$strategy = new class($handler) extends AbstractUsernamePasswordAuthenticationStrategy
		{
			public function authenticate()
			{
				return $this->doAuthenticate('username', 'password');
			}

			protected function getHashedPassword($username)
			{
				return 'password';
			}
		};

		$this->assertFalse($strategy->authenticate());
		$this->assertSame(Authentication::INVALID_CREDENTIALS, $strategy->getResult(), 'The correct result status is set');
	}
}

Add explicit tests covering the abstract username/password strategy


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

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

class CreateOsuDifficultyAttribs extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('osu_difficulty_attribs', function (Blueprint $table) {
            $table->unsignedSmallInteger('attrib_id');
            $table->string('name', 256)->default('');
            $table->boolean('visible')->default(0);
            $table->primary('attrib_id');
        });

        DB::table('osu_difficulty_attribs')->insert([
            ['attrib_id' => 1, 'name' => 'Aim', 'visible' => 1],
            ['attrib_id' => 3, 'name' => 'Speed', 'visible' => 1],
            ['attrib_id' => 5, 'name' => 'OD', 'visible' => 0],
            ['attrib_id' => 7, 'name' => 'AR', 'visible' => 0],
            ['attrib_id' => 9, 'name' => 'Max combo', 'visible' => 0],
            ['attrib_id' => 11, 'name' => 'Strain', 'visible' => 1],
            ['attrib_id' => 13, 'name' => 'Hit window 300', 'visible' => 0],
            ['attrib_id' => 15, 'name' => 'Score multiplier', 'visible' => 0],
            ['attrib_id' => 17, 'name' => 'Flashlight', 'visible' => 0],
            ['attrib_id' => 19, 'name' => 'Slider factor', 'visible' => 0],
            ['attrib_id' => 21, 'name' => 'Speed note count', 'visible' => 0],
        ]);
    }

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

Add migration for osu_difficulty_attribs table


<?php

namespace Systemblast\Engine\Foundation;

class Application
{
    private static $instance = null;

    private function __construct()
    {
        $dependencies = require_once root_path('config/dependency.php');
        $container    = new \League\Container\Container;
        foreach ($dependencies['singleton'] as $interface => $implementation) {
            $container->share($interface, $implementation);
        }

        foreach ($dependencies['binding'] as $interface => $implementation) {
            $container->add($interface, $implementation);
        }
        $this->container = $container;
    }

    public static function make()
    {
        // Check if instance is already exists
        if (self::$instance == null) {
            self::$instance = new Application();
        }
        return self::$instance;
    }

    private function __clone()
    {
        // Stopping Clonning of Object
    }

    private function __wakeup()
    {
        // Stopping unserialize of object
    }
}

Add Systemblast\Engine\Foundation to prevent from creating same instance multiple times


<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\ORM\Tools\ToolsException;

class MergeSharedEntitiesTest extends \Doctrine\Tests\OrmFunctionalTestCase
{

    protected function setUp()
    {
        parent::setUp();

        try {
            $this->_schemaTool->createSchema(
                array(
                    $this->_em->getClassMetadata(__NAMESPACE__ . '\MSEFile'),
                    $this->_em->getClassMetadata(__NAMESPACE__ . '\MSEPicture'),
                )
            );
        } catch (ToolsException $ignored) {
        }
    }

    public function testMergeSharedNewEntities()
    {

        /** @var MSEPicture $picture */
        $file = new MSEFile;

        $picture = new MSEPicture;
        $picture->file = $file;
        $picture->otherFile = $file;

        $em = $this->_em;

        $picture = $em->merge($picture);

        $this->assertEquals($picture->file, $picture->otherFile, "Identical entities must remain identical");
    }

    public function testMergeSharedManagedEntities()
    {

        /** @var MSEPicture $picture */
        $file = new MSEFile;

        $picture = new MSEPicture;
        $picture->file = $file;
        $picture->otherFile = $file;

        $em = $this->_em;
        $em->persist($file);
        $em->flush();
        $em->clear();

        $picture = $em->merge($picture);

        $this->assertEquals($picture->file, $picture->otherFile, "Identical entities must remain identical");
    }

    public function testMergeSharedManagedEntitiesSerialize()
    {

        /** @var MSEPicture $picture */
        $file = new MSEFile;

        $picture = new MSEPicture;
        $picture->file = $file;
        $picture->otherFile = $file;

        $serializedPicture = serialize($picture);

        $em = $this->_em;
        $em->persist($file);
        $em->flush();
        $em->clear();

        $picture = unserialize($serializedPicture);
        $picture = $em->merge($picture);

        $this->assertEquals($picture->file, $picture->otherFile, "Identical entities must remain identical");
    }

}

/**
 * @Entity
 */
class MSEPicture
{
    /**
     * @Column(name="picture_id", type="integer")
     * @Id @GeneratedValue
     */
    public $pictureId;

    /**
     * @ManyToOne(targetEntity="MSEFile", cascade={"persist", "merge"})
     * @JoinColumn(name="file_id", referencedColumnName="file_id")
     */
    public $file;

    /**
     * @ManyToOne(targetEntity="MSEFile", cascade={"persist", "merge"})
     * @JoinColumn(name="other_file_id", referencedColumnName="file_id")
     */
    public $otherFile;
}

/**
 * @Entity
 */
class MSEFile
{
    /**
     * @Column(name="file_id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    public $fileId;

}

Test case for merging entities with associations to identical entities.


<?php

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

class CreateJobsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('jobs', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('graphic');
			$table->integer('project_id');
			$table->integer('user_id');
			$table->integer('duration');
			$table->timestamp('job_start');
			$table->timestamp('job_end');
			$table->timestamps();
		});
	}

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

}

Create migration for Jobs table

Create migration for Jobs table


<?php

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

class RemovePhotosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::drop('photos');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_url')->comment('The url of the file on s3.');
            $table->string('edited_file_url')->nullable()->comment('The url of the edited file on s3.');
            $table->string('caption')->nullable();
            $table->timestamps();
        });
    }
}

Add migration to drop the photos table

Add migration to drop the photos table


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\EventHandling;

use Broadway\Domain\DomainMessageInterface;
use Broadway\EventHandling\EventListenerInterface;

trait DelegateEventHandlingToSpecificMethodTrait
{
    /**
     * {@inheritDoc}
     */
    public function handle(DomainMessageInterface $domainMessage)
    {
        $event  = $domainMessage->getPayload();
        $method = $this->getHandleMethod($event);

        if (!method_exists($this, $method)) {
            return;
        }

        $parameter = new \ReflectionParameter(array($this, $method), 0);
        $expectedClass = $parameter->getClass();

        if ($expectedClass->getName() == get_class($event)) {
            $this->$method($event, $domainMessage);
        }
    }

    private function getHandleMethod($event)
    {
        $classParts = explode('\\', get_class($event));

        return 'apply' . end($classParts);
    }
}

III-196: Introduce a trait for event handling delegation to a specific method, for implementing EventListenerInterface of Broadway library


<?php

declare(strict_types=1);

namespace Tests;

use Illuminate\Support\Facades\Artisan;
use LaravelZero\Framework\Contracts\Providers\ComposerContract;

final class MenuComponentTest extends TestCase
{
    /** @test */
    public function it_installs_the_required_packages(): void
    {
        $composerMock = $this->createMock(ComposerContract::class);

        $composerMock->expects($this->once())
            ->method('require')
            ->with('nunomaduro/laravel-console-menu "^3.0"');

        $this->app->instance(ComposerContract::class, $composerMock);

        Artisan::call('app:install', ['component' => 'menu']);
    }
}

Add unit test class for the Menu component


<?php

namespace PHPMD\Writer;

use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \PHPMD\Writer\StreamWriter
 * @covers ::__construct
 */
class StreamWriterTest extends TestCase
{
    /**
     * @covers ::getStream
     */
    public function testGetStream()
    {
        $writer = new StreamWriter(STDOUT);
        static::assertSame(STDOUT, $writer->getStream());
    }
}

Add coverage for StreamWriter getStream

Add coverage for StreamWriter getStream


<?php

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

namespace Symfony\Component\Mailer\Bridge\Amazon\Transport;

use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * @author Kevin Verschaeve
 */
class SesSmtpTransport extends EsmtpTransport
{
    /**
     * @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
     */
    public function __construct(string $username, string $password, string $region = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
    {
        parent::__construct(sprintf('email-smtp.%s.amazonaws.com', $region ?: 'eu-west-1'), 587, true, $dispatcher, $logger);

        $this->setUsername($username);
        $this->setPassword($password);
    }
}

<?php

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

namespace Symfony\Component\Mailer\Bridge\Amazon\Transport;

use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * @author Kevin Verschaeve
 */
class SesSmtpTransport extends EsmtpTransport
{
    /**
     * @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
     */
    public function __construct(string $username, string $password, string $region = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
    {
        parent::__construct(sprintf('email-smtp.%s.amazonaws.com', $region ?: 'eu-west-1'), 465, true, $dispatcher, $logger);

        $this->setUsername($username);
        $this->setPassword($password);
    }
}

Use port 465 for SES SMTP transport

Use port 465 for SES SMTP transport

Fixes #34064


<?php

namespace Bundle\MenuBundle\Tests;
use Bundle\MenuBundle\MenuItem;

class MenuItemTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateMenuItemWithEmptyParameter()
    {
        $menu = $this->createMenu();
        $this->assertTrue($menu instanceof MenuItem);
    }

    public function testCreateMenuWithNameAndRoute()
    {
        $menu = $this->createMenu('test1', 'other_route');
        $this->assertEquals('test1', $menu->getName());
        $this->assertEquals('other_route', $menu->getRoute());
    }

    public function testCreateMenuWithTitle()
    {
        $title = 'This is a test item title';
        $menu = $this->createMenu(null, null, array('title' => $title));
        $this->assertEquals($title, $menu->getAttribute('title'));
    }

    public function testName()
    {
        $menu = $this->createMenu();
        $menu->setName('menu name');
        $this->assertEquals('menu name', $menu->getName());
    }

    public function testLabel()
    {
        $menu = $this->createMenu();
        $menu->setLabel('menu label');
        $this->assertEquals('menu label', $menu->getLabel());
    }

    public function testRoute()
    {
        $menu = $this->createMenu();
        $menu->setRoute('menu_route');
        $this->assertEquals('menu_route', $menu->getRoute());
    }

    public function testAttributes()
    {
        $attributes = array('class' => 'test_class', 'title' => 'Test title');
        $menu = $this->createMenu();
        $menu->setAttributes($attributes);
        $this->assertEquals($attributes, $menu->getAttributes());
    }

    public function testDefaultAttribute()
    {
        $menu = $this->createMenu(null, null, array('id' => 'test_id'));
        $this->assertEquals('test_id', $menu->getAttribute('id'));
        $this->assertEquals('default_value', $menu->getAttribute('unknown_attribute', 'default_value'));
    }

    /**
     * Create a new MenuItem
     *
     * @param string $name
     * @param string $route
     * @param array $attributes
     * @return MenuItem
     */
    protected function createMenu($name = 'test_menu', $route = 'homepage', array $attributes = array())
    {
        return new MenuItem($name, $route, $attributes);
    }
}

Add a couple of unit tests for MenuItem

Add a couple of unit tests for MenuItem


<?php

namespace Greenelf\Panel;

use Illuminate\Database\Eloquent\Model;

class RolePermission extends Model
{
    /**
     * A role may be given various permissions.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function permissions()
    {
     //   return $this->belongsToMany(Permission::class);
    }

    /**
     * Grant the given permission to a role.
     *
     * @param  Permission $permission
     * @return mixed
     */
    public function givePermissionTo(RolePermission $permission)
    {
       // return $this->permissions()->save($permission);
    }
}

Add role permission table and model

Add role permission table and model


<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );

echo userHTML( );

$user = $_SESSION[ 'user' ];

if( $_POST )
{
    $data = array( 'speaker' => $user );
    $data = array_merge( $_POST, $data );
    echo( "Sending your acknowledgment to database " );
    $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
    if( $res )
    {
        echo printInfo(
            "You have successfully acknowledged your AWS schedule.
            Please mark your calendar as well."
        );

        $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>";
        $email .= "<p>" . humanReadableDate( 'now' ) . "</p>";
        $subject = "$user has acknowledged his/her AWS date";

        $to = 'acadoffice@ncbs.res.in';
        $cc = 'hippo@lists.ncbs.res.in';
        sendPlainTextEmail( $email, $subject, $to, $cc );

        goToPage( "user_aws.php", 1 );
        exit;
    }
    else
    {
        echo printWarning( "Failed to update database ..." );
    }
}

echo goBackToPageLink( "user_aws.php", "Go back" );

?>

<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );

echo userHTML( );

$user = $_SESSION[ 'user' ];

if( $_POST )
{
    $data = array( 'speaker' => $user );
    $data = array_merge( $_POST, $data );
    echo( "Sending your acknowledgment to database " );
    $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
    if( $res )
    {
        echo printInfo(
            "You have successfully acknowledged your AWS schedule.
            Please mark your calendar as well."
        );

        $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>";
        $email .= "<p>" . humanReadableDate( 'now' ) . "</p>";
        $subject = loginToText( $user ) . " has acknowledged his/her AWS date";

        $to = 'acadoffice@ncbs.res.in';
        $cc = 'hippo@lists.ncbs.res.in';
        sendPlainTextEmail( $email, $subject, $to, $cc );

        goToPage( "user_aws.php", 1 );
        exit;
    }
    else
    {
        echo printWarning( "Failed to update database ..." );
    }
}

echo goBackToPageLink( "user_aws.php", "Go back" );

?>

Send email to acadoffice when user acknowledge his AWS.

Former-commit-id: 3285ac8554522192665d8a9d65ffd3d25240fd35
Former-commit-id: c262a061a641e53d217875a578a08ca0584cfc74


<?php

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

class CreateFeedbackTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('feedback', function(Blueprint $table)
    {
      $table->increments('id');
      $table->integer('user')->unsigned();
      $table->string('code');
      $table->text('feedback');
      $table->tinyInteger('status')->default(0);
      $table->timestamps();
    });
  }

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

}

Create feedback migration ( @doomsayer2 run `php artisan migrate` )


<?php
use Migrations\AbstractMigration;

class AddDefaultValueForLocked extends AbstractMigration
{

    public function change()
    {
        $table = $this->table('jobs');
        $table->changeColumn('locked', 'integer', [
            'default' => 0
        ]);
        $table->update();
    }
}

Add migration to fix no default value errors on the locked column


<?php
use Afrihost\SwarmProcess\SwarmProcess;
use Psr\Log\NullLogger;

/**
 * User: sarel
 * Date: 2016/01/18
 * Time: 07:56
 */
class SwarmProcessTestNoSetup extends PHPUnit_Framework_TestCase
{
    /**
     * Tests whether if we give it a logger, we get return the same logger if we check which one it has internally
     */
    public function testLoggerGiven()
    {
        $given = new NullLogger();

        $swarm = new SwarmProcess($given);

        $this->assertTrue($given === $swarm->getLogger(), 'Logger given at construction not the same as class has internally');
    }

    public function testLoggerNotGiven()
    {
        $swarm = new SwarmProcess();

        $this->assertInstanceOf('Psr\Log\NullLogger', $swarm->getLogger(), 'Logger expected when none is given, should be the NullLogger');
    }
}

Test giving and not-giving logger (should get NullLogger if none is given)


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that the 404 page works');
$I->haveEnabledFilters();
$I->amOnPage('/some/bad/url/that/will/never/exist');
$I->seePageNotFound();
$I->dontSee('whoops');

Add acceptance test to check 404 page

Add acceptance test to check 404 page


<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\RequestSpec;

class RelationshipTypeCreationSpecProvider implements Generic\SpecProviderInterface {

  /**
   * @inheritDoc
   */
  public function modifySpec(RequestSpec $spec) {
    $spec->getFieldByName('name_a_b')->setRequired(TRUE);
    $spec->getFieldByName('name_b_a')->setRequired(TRUE);
  }

  /**
   * @inheritDoc
   */
  public function applies($entity, $action) {
    return $entity === 'RelationshipType' && $action === 'create';
  }

}

Add relationshipType spec for required fields


<?php

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

class AddUploadsTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
    public function up()
    {
        Schema::create('uploads', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('application_id');
            $table->string('url');
            $table->string('src_name');
            $table->string('content_type');
            $table->string('size');
            $table->timestamps();
        });
    }

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

Create uploads table in database.

Create uploads table in database.


<?php

namespace Risan\OAuth1\Signature;

interface SignerInterface
{
    /**
     * Get signer method name.
     *
     * @return string
     */
    public function method();

    /**
     * Create a signature for given request parameters.
     *
     * @param  string $uri
     * @param  array  $parameters
     * @param  string $httpMethod
     * @return string
     */
    public function sign($uri, array $parameters = [], $httpMethod = 'POST');
}

Add new interface for signer.

:sparkles: Add new interface for signer.


<?php

namespace Oro\Bundle\AddressBundle\Tests\Functional\DataFixtures;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\AddressBundle\Entity\Region;

class LoadRegionData extends AbstractFixture
{
    const REGION_AD_07 = 'region.ad07';
    const REGION_DK_85 = 'region.dk85';

    /** @var array */
    protected $regions = [
        self::REGION_AD_07 => [
            'combinedCode' => 'AD-07',
            'code' => '07',
            'name' => 'Andorra la Vella',
        ],
        self::REGION_DK_85 => [
            'combinedCode' => 'DK-85',
            'code' => '85',
            'name' => 'Sjælland',
        ],
    ];

    /**
     * Load address types
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $repository = $manager->getRepository(Region::class);

        foreach ($this->regions as $reference => $data) {
            /** @var $region Region */
            $region = $repository->find($data['combinedCode']);
            if (!$region) {
                $region = new Region($data['combinedCode']);
                $region->setCode($data['code']);
                $region->setName($data['name']);

            }

            $this->setReference($reference, $region);

            $manager->persist($region);
        }

        $manager->flush();
    }
}

BB-8457: Create functional tests for OrderAddress entity API


<?php
function remove_recent_comment_style() {
	global $wp_widget_factory;
	remove_action(
            'wp_head',
            array( $wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style' )
        );
}
add_action( 'widgets_init', 'remove_recent_comment_style' );
?>

Remove a classe .recentcomment do head

Remove a classe .recentcomment do head


<?php

namespace Clastic\TaxonomyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ClasticTaxonomyExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}

<?php

namespace Clastic\TaxonomyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ClasticTaxonomyExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (true === isset($bundles['StofDoctrineExtensionsBundle'])) {
            $this->configureStofDoctrineExtensionsBundle($container);
        }
    }

    /**
     * @param ContainerBuilder $container The service container
     *
     * @return void
     */
    protected function configureStofDoctrineExtensionsBundle(ContainerBuilder $container)
    {
        foreach (array_keys($container->getExtensions()) as $name) {
            switch ($name) {
                case 'stof_doctrine_extensions':
                    $container->prependExtensionConfig(
                        $name,
                        array('orm' => array('default' => array('tree' => true)))
                    );
                    break;
            }
        }
    }
}

Move configuration to Bundle Extension.

[Taxonomy] Move configuration to Bundle Extension.


<?php
/**
 * Refresh project token
 *
 * @author Timo Tijhof, 2012-2013
 * @since 1.0.0
 * @package TestSwarm
 */
define( 'SWARM_ENTRY', 'SCRIPT' );
require_once __DIR__ . '/../inc/init.php';

class RefreshProjectTokenScript extends MaintenanceScript {

	protected function init() {
		$this->setDescription(
			'Refresh the authentication token of a project. Invalides the current token and returns an newly generated one.'
		);
		$this->registerOption( 'id', 'value', 'ID of project.' );
		$this->registerOption( 'quick', 'boolean', 'Skip confirmation.' );
	}

	protected function execute() {
		$db = $this->getContext()->getDB();

		$id = $this->getOption( 'id' );

		// Verify parameters
		if ( !$id ) {
			$this->error( '--id is required.' );
		}

		$checkId = $db->getOne(str_queryf(
			'SELECT
				id
			FROM projects
			WHERE id = %s;',
			$id
		));

		if ( !$checkId || $checkId !== $id ) {
			$this->error( 'Project "' . $id . '" does not exist.' );
		}

		if ( !$this->getOption( 'quick' ) ) {
			$this->timeWarningForScriptWill( 'invalidate the existing token' );
		}

		// New token
		$authToken = LoginAction::generateRandomHash( 40 );
		$authTokenHash = sha1( $authToken );

		$isUpdated = $db->query(str_queryf(
			'UPDATE projects
			SET
				auth_token = %s
			WHERE id = %s
			LIMIT 1;',
			$authTokenHash,
			$id
		));
		if ( !$isUpdated ) {
			$this->error( 'Updating of row into database failed.' );
		}

		$this->out(
			'Authentication token of project "' . $id . '" has been succesfully refreshed!' . PHP_EOL
			. 'The following auth token has been generated for this project:' . PHP_EOL
			. $authToken . PHP_EOL . PHP_EOL
		);
	}
}

$script = RefreshProjectTokenScript::newFromContext( $swarmContext );
$script->run();

Implement refresh project token script

scripts: Implement refresh project token script

Fixes #281.


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

use app\components\db\Migration;

class m190719_123951_fix_mystery_battles extends Migration
{
    public function safeUp()
    {
        $startPeriod = (int)floor(strtotime('2019-07-18T21:00:00+09:00') / 7200) - 1;

        // あらかじめ WHERE で絞り込んだ INDEX を作って
        // この INDEX を優先してもらうことで高速化を図る
        // これを作成しないと、シーケンシャルスキャンでとんでもないことになった…
        $index = 'tmp_battle2_' . hash('crc32b', __METHOD__);
        $this->execute(
            "CREATE UNIQUE INDEX {$index} ON {{battle2}}([[id]]) " .
            'WHERE ([[map_id]] IS NULL) ' .
            "AND ([[period]] >= {$startPeriod})"
        );

        // 現在、battle2_splatnet テーブルの中身が、テキストになっているので、
        // テキストを一度 JSONB として解釈してもらってさらにクエリを投げる。
        // 死ぬほど遅い。
        $db = Yii::$app->db;
        $this->execute(
            'UPDATE {{battle2}} ' .
            'SET [[map_id]] = {{map2}}.[[id]] ' .
            'FROM {{battle2_splatnet}} {{j}}, {{map2}} '.
            'WHERE ((' . implode(') AND (', [
                '{{battle2}}.[[id]] = {{j}}.[[id]]',
                "((({{j}}.[[json]]->>0)::JSONB)->'stage'->>'id')::INTEGER = {{map2}}.[[splatnet]]",
                'JSONB_TYPEOF({{j}}.[[json]]) = ' . $db->quoteValue('string'),
                '{{battle2}}.[[map_id]] IS NULL',
                '{{battle2}}.[[period]] >= ' . $db->quoteValue($startPeriod),
            ]) . '))'
        );

        $this->execute("DROP INDEX {$index}");
    }

    public function safeDown()
    {
    }
}

Fix the data of Shifty Station registered early


<?php
function exchange($coin) {
  return [
    floor($coin/2),
    floor($coin/3),
    floor($coin/4)
  ];
};

function sellCoins($coins) {
  $value = 0;
  foreach ($coins as $coin) {
    $value += sell(intval($coin));
  }
  return $value;
}

function sell($coin) {
  static $sellCache = [
    1 => 1,
    0 => 0
  ];

  if (array_key_exists($coin, $sellCache)) {
    return $sellCache[$coin];
  }
  return $sellCache[$coin] = max($coin, sellCoins(exchange($coin)));
};

while (false !== ($line = fgets(STDIN))) {
  echo sell(+$line) . "\n";
}
?>

Add another PHP solution for COINS

Add another PHP solution for COINS


<?php

declare(strict_types=1);

namespace Scheb\Tombstone\Tests;

class ComposerJsonTest extends TestCase
{
    private const SRC_DIR = __DIR__.'/../src';

    /**
     * @test
     */
    public function packageDependenciesEqualRootDependencies(): void
    {
        $usedDependencies = [];
        $rootDependencies = $this->getComposerDependencies(__DIR__.'/../composer.json');

        foreach ($this->listSubPackages() as $package) {
            $packageDependencies = $this->getComposerDependencies(self::SRC_DIR.'/'.$package.'/composer.json');
            foreach ($packageDependencies as $dependency => $version) {
                // Skip scheb/tombstone-* dependencies
                if (0 === strpos($dependency, 'scheb/tombstone-')) {
                    continue;
                }

                $message = sprintf('Dependency "%s" from package "%s" is not defined in root composer.json', $dependency, $package);
                $this->assertArrayHasKey($dependency, $rootDependencies, $message);

                $message = sprintf('Dependency "%s:%s" from package "%s" requires a different version in the root composer.json', $dependency, $version, $package);
                $this->assertEquals($version, $rootDependencies[$dependency], $message);

                $usedDependencies[] = $dependency;
            }
        }

        $unusedDependencies = array_diff(array_keys($rootDependencies), array_unique($usedDependencies));
        $message = sprintf('Dependencies declared in root composer.json, which are not declared in any sub-package: %s', implode($unusedDependencies));
        $this->assertCount(0, $unusedDependencies, $message);
    }

    /**
     * @test
     */
    public function rootReplacesSubPackages(): void
    {
        $rootReplaces = $this->getComposerReplaces(__DIR__.'/../composer.json');
        foreach ($this->listSubPackages() as $package) {
            $packageName = $this->getComposerPackageName(self::SRC_DIR.'/'.$package.'/composer.json');
            $message = sprintf('Root composer.json must replace the sub-packages "%s"', $packageName);
            $this->assertArrayHasKey($packageName, $rootReplaces, $message);
        }
    }

    private function listSubPackages(): \Traversable
    {
        foreach (new \DirectoryIterator(self::SRC_DIR) as $dirInfo) {
            if ($dirInfo->isDir() && !$dirInfo->isDot()) {
                yield $dirInfo->getFilename();
            }
        }
    }

    private function getComposerDependencies(string $composerFilePath): array
    {
        return $this->parseComposerFile($composerFilePath)['require'];
    }

    private function getComposerPackageName(string $composerFilePath): string
    {
        return $this->parseComposerFile($composerFilePath)['name'];
    }

    private function getComposerReplaces(string $composerFilePath): array
    {
        return $this->parseComposerFile($composerFilePath)['replace'];
    }

    private function parseComposerFile(string $composerFilePath): array
    {
        return json_decode(file_get_contents($composerFilePath), true);
    }
}

Add test to ensure composer.json configurations are in sync


<?php

namespace FontLib\Tests;

use FontLib\Font;

class FontTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Fontlib\Exception\FontNotFoundException
     */
    public function testLoadFileNotFound()
    {
        Font::load('non-existing/font.ttf');
    }

    public function testLoadTTFFontSuccessfully()
    {
        $trueTypeFont = Font::load('sample-fonts/IntelClear-Light.ttf');

        $this->assertInstanceOf('FontLib\TrueType\File', $trueTypeFont);
    }
}

Add test to ensure factory is build TrueType File.


<?php

use App\Permission;
use App\Role;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentRecordManagePermission extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $permission = Permission::create([
            'name'         => 'payment-record.manage',
            'display_name' => '繳費紀錄管理',
            'description'  => '檢視、管理各社團繳費紀錄',
        ]);

        /* @var Role $admin */
        $admin = Role::where('name', 'Admin')->first();
        $admin->attachPermission($permission);
        /* @var Role $eas */
        $eas = Role::where('name', 'EAS')->first();
        $eas->attachPermission($permission);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Permission::where('name', 'payment-record.manage')->delete();
    }
}

Create payment record manage permission

Create payment record manage permission


<?php

class LoadashPhp
{
    public function LoadashPhp() {
        ini_set('display_errors', '1');
        ini_set('display_startup_errors', '1');
    }

    /**
     * Creates an array of elements split into groups the length of size.
     * If array can’t be split evenly, the final chunk will be the remaining elements.
     * @param $array
     * @param $number
     * @throws Exception
     * @return array
     */
    public function chunk($array, $number) {
        if(!is_array($array) || !is_int($number)) {
            $this->throw_exception("Invalid param type");
        }
        if(count($array) < $number) {
            $this->throw_exception("Array size is smaller than number");
        }
        $index = 0;
        $array_index = 0;
        $chunk_array = array();
        foreach($array as $value) {
            if($index == $number) {
                $index = 0;
                $array_index++;
            }
            $chunk_array[$array_index][] = $value;
            $index++;
        }
        return $chunk_array;
    }

    /**
     * Creates an array with all falsey values removed.
     * The values false, null, 0, and "" are falsey.
     * @param $array
     * @throws Exception
     * @return array
     */
    public function compact($array) {
        if(!is_array($array)) {
            $this->throw_exception("Invalid param type");
        }
        if(empty($array)) {
            $this->throw_exception("Array is empty");
        }
        $chunk_array = array();
        foreach($array as $value) {
            if($value !== false && $value != null && !empty($value))
                $chunk_array[] = $value;
        }
        return $chunk_array;
    }

    /**
     * Throws an exception with provided message.
     * @param $msg
     * @throws Exception
     */
    private function throw_exception($msg) {
        throw new Exception($msg);
    }
}

Add Loadash 'chunk' and 'compact' functionality


<?php
namespace nochso\Omni\Test;

use nochso\Omni\DurationFormat;

class DurationFormatTest extends \PHPUnit_Framework_TestCase
{
    public function formatProvider()
    {
        return [
            [DurationFormat::FORMAT_SHORT, '0s', 0],
            [DurationFormat::FORMAT_SHORT, '1s', 1],
            [DurationFormat::FORMAT_SHORT, '1m', 60],
            [DurationFormat::FORMAT_SHORT, '1m 59s', 119],
            [DurationFormat::FORMAT_SHORT, '1y 5d', new \DateInterval('P1Y5D')],
            [DurationFormat::FORMAT_SHORT, '1mo', new \DateInterval('P30D')],
            [DurationFormat::FORMAT_LONG, '0 seconds', 0],
            [DurationFormat::FORMAT_LONG, '1 second', 1],
            [DurationFormat::FORMAT_LONG, '1 minute', 60],
            [DurationFormat::FORMAT_LONG, '1 minute 59 seconds', 119],
            [DurationFormat::FORMAT_LONG, '1 year 5 days', new \DateInterval('P1Y5D')],
            [DurationFormat::FORMAT_LONG, '1 month', new \DateInterval('P30D')],
        ];
    }

    /**
     * @dataProvider formatProvider
     *
     * @param string|int        $formatName
     * @param string            $expected
     * @param int|\DateInterval $duration
     */
    public function testFormat($formatName, $expected, $duration)
    {
        $df = DurationFormat::create($formatName);
        $this->assertSame($expected, $df->format($duration));
    }

    public function testAddFormat()
    {
        $df = DurationFormat::create();
        $format = [
            DurationFormat::YEAR => ' Jahr(e)',
            DurationFormat::MONTH => ' Monat(e)',
            DurationFormat::WEEK => ' Woche(n)',
            DurationFormat::DAY => ' Tag(e)',
            DurationFormat::HOUR => ' Stunde(n)',
            DurationFormat::MINUTE => ' Minute(n)',
            DurationFormat::SECOND => ' Sekunde(n)',
        ];
        $df->addFormat('german', $format);
        $this->assertSame('0 Sekunden', $df->format(0));
        $this->assertSame('1 Jahr 3 Stunden', $df->format(new \DateInterval('P1YT3H')));
    }

    public function testSetFormat()
    {
        $df = DurationFormat::create();
        $this->expectException('InvalidArgumentException');
        $df->setFormat('does not exist');
    }

    public function testLimitPeriods()
    {
        $df = DurationFormat::create()->limitPeriods(2);
        $this->assertSame('1y 3h', $df->format(new \DateInterval('P1YT3H5M3S')));
    }
}

Add tests for new class DurationFormat

test: Add tests for new class DurationFormat


<?php

use Phinx\Migration\AbstractMigration;

class AllowNullOnDocsUpdatedAtCols extends AbstractMigration {
    public function change() {
        $this->table('documents')
            ->changeColumn('updated_at', 'datetime', ['null' => true])
            ->changeColumn('updated_by', 'string', ['null' => true])
            ->update();
        $this->table('folders')
            ->changeColumn('updated_at', 'datetime', ['null' => true])
            ->changeColumn('updated_by', 'string', ['null' => true])
            ->update();
    }
}

Fix docs & folders : allow updated_at and updated_by to be null


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\KeyDataBuilders;

use hollodotme\Readis\Application\Interfaces\ProvidesKeyInfo;
use hollodotme\Readis\Application\ReadModel\Constants\KeyType;
use hollodotme\Readis\Application\ReadModel\DTO\KeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\BuildsKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\PrettifiesString;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyName;
use hollodotme\Readis\Infrastructure\Redis\ServerManager;

final class SetKeyDataBuilder implements BuildsKeyData
{
	private const MEMBER_SEPARATOR = "\n\n---\n\n";

	/** @var ServerManager */
	private $manager;

	/** @var PrettifiesString */
	private $prettifier;

	public function __construct( ServerManager $manager, PrettifiesString $prettifier )
	{
		$this->manager    = $manager;
		$this->prettifier = $prettifier;
	}

	public function canBuildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : bool
	{
		return !$keyName->hasSubKey() && (KeyType::SET === $keyInfo->getType());
	}

	public function buildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : ProvidesKeyData
	{
		$rawMembers = [];
		foreach ( $keyInfo->getSubItems() as $index => $member )
		{
			$rawMembers[] = $this->getMemberOutput( $index, $member );
		}

		$prettyMembers = [];
		foreach ( $keyInfo->getSubItems() as $index => $member )
		{
			$prettyMember    = $this->prettifier->prettify( $member );
			$prettyMembers[] = $this->getMemberOutput( $index, $prettyMember );
		}

		$rawKeyData = implode( self::MEMBER_SEPARATOR, $rawMembers );
		$keyData    = implode( self::MEMBER_SEPARATOR, $prettyMembers );

		return new KeyData( $keyData, $rawKeyData );
	}

	private function getMemberOutput( int $index, string $member ) : string
	{
		return sprintf(
			"Member %d:\n%s\n%s",
			$index,
			str_repeat( '=', 8 + strlen( (string)$index ) ),
			$member
		);
	}
}

Add set key data builder

Add set key data builder


<?php namespace App\Providers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Dropbox\DropboxAdapter;
use League\Flysystem\Filesystem;
use Dropbox\Client;

class DropboxFilesystemServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap the application services.
	 *
	 * @return void
	 */
	public function boot()
	{
        Storage::extend('dropbox', function()
        {
            $client = new Client($config["accessToken"], config["ClientIdentifier"]);
            $adapter = new DropboxAdapter($client);
            $filesystem = new Filesystem($adapter);
            return $filesystem;
        });
	}

}

Add the dropbox adapter to extend the choice to use dropbox for backing up.


<?php

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

namespace Surfnet\StepupSelfService\SelfServiceBundle\Exception;

class UnexpectedIssuerException extends RuntimeException
{
}

Introduce exception for encountering unexpected issuer


<?php

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

class IncreaseTokenFieldLength extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('access_token', 2048)->change();
            $table->string('refresh_token', 2048)->change();
        });

        Schema::table('clients', function (Blueprint $table) {
            $table->string('access_token', 2048)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('access_token', 1024)->change();
            $table->string('refresh_token', 1024)->change();
        });

        Schema::table('clients', function (Blueprint $table) {
            $table->string('access_token', 1024)->change();
        });
    }
}

Increase default token field lengths.

Increase default token field lengths.


<?php

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

class CreatePasswordChange extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create('account_email_changes', function(Blueprint $table) {
            $table->increments('account_email_change_id');
            $table->integer('account_id');
            $table->string('token');
            $table->string('email_previous');
            $table->string('email_new');
            $table->boolean('is_previous_confirmed');
            $table->boolean('is_new_confirmed');
            $table->boolean('is_complete');
            $table->timestamps();

            $table->foreign('account_id')->references('account_id')->on('accounts');
        });
    }

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

Create account email change migration

Create account email change migration


<?php

use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FixRsvpPermissionNaming extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        $create_rsvp = Permission::findByName('create-rsvp');
        $create_rsvp->name = "create-rsvps";
        $create_rsvp->save();

        $create_rsvp_own = Permission::findByName('create-rsvp-own');
        $create_rsvp_own->name = "create-rsvps-own";
        $create_rsvp_own->save();

        $delete_rsvp_own = Permission::findByName('delete-rsvp-own');
        $delete_rsvp_own->name = "delete-rsvps-own";
        $delete_rsvp_own->save();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        $create_rsvps = Permission::findByName('create-rsvps');
        $create_rsvps->name = "create-rsvp";
        $create_rsvps->save();

        $create_rsvps_own = Permission::findByName('create-rsvps-own');
        $create_rsvps_own->name = "create-rsvp-own";
        $create_rsvps_own->save();

        $delete_rsvps_own = Permission::findByName('delete-rsvps-own');
        $delete_rsvps_own->name = "delete-rsvp-own";
        $delete_rsvps_own->save();
    }
}

Fix inconsistent RSVP permission naming

Fix inconsistent RSVP permission naming


<?php

namespace Enqueue\AmqpExt;

use Interop\Queue\PsrConsumer;
use Interop\Queue\PsrSubscriptionConsumer;

class AmqpSubscriptionConsumer implements PsrSubscriptionConsumer
{
    /**
     * {@inheritdoc}
     */
    public function consume($timeout = 0)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function subscribe(PsrConsumer $consumer, callable $callback)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function unsubscribe(PsrConsumer $consumer)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function unsubscribeAll()
    {
    }
}

Move subscription related logic to SubscriptionConsumer class.


<?php
//Contrary to JavaScript, variables are in local scope by default, meaning that
//variables declared outside function are not available to functions unless they are passed in
//as parameters
//use of the global keyword makes variables work similar to JavaScript

$test = true;

function test(){
	//$test is not accessible here, unlike JavaScript
	global $test; //now $test can be accessed here
	$GLOBALS['test']; //will also return value of $test global variable
}

Add note about php variable scope

Add note about php variable scope


<?php
/**
 * Script to set a placeholder email for users with blank mail field.
 *
 * to run:
 * drush --script-path=../scripts/ php-script fix-empty-mail.php
 */

$troublemakers = db_query('SELECT uid FROM users LEFT JOIN field_data_field_mobile ON uid = entity_id WHERE mail = \'\' AND uid != 0');
$fixed = 0;

foreach ($troublemakers as $user) {
  $user = user_load($user->uid);

  // Set the new email for the deactivated user.
  $mobile = dosomething_user_get_field('field_mobile', $user);
  $fresh_and_clean_digits = dosomething_user_clean_mobile_number(preg_replace('[^0-9]', '', $mobile));
  if (! $fresh_and_clean_digits) {
    print 'Could not fix ' . $user->uid . ' (' . $mobile . ', ' . $user->mail . ')' . PHP_EOL;
    continue;
  }

  $new_email = $fresh_and_clean_digits . '@mobile.import';
  print 'Updated user ' . $user->uid . '(' . $user->mail . ' --> ' . $new_email . ')' . PHP_EOL;
  $user = user_save($user, ['mail' => $new_email]);

  $fixed++;
}

print '[✔] Fixed mobile placeholder email for ' . $fixed . ' users.' . PHP_EOL;

Add a script to fix users with empty email.


<?php

namespace RCatlin\Blog\Test\Unit\Serializer;

use League\Container\Container;
use League\Fractal\TransformerAbstract;
use RCatlin\Blog\Test\Unit\BuildsMocks;
use RCatlin\Blog\Serializer;
use RCatlin\Blog\Test\Unit\HasFaker;

class TransformerContainerTest extends \PHPUnit_Framework_TestCase
{
    use BuildsMocks;
    use HasFaker;

    public function testGetTransformer()
    {
        $alias = $this->getFaker()->word;
        $transformer = $this->getMockTransformer();

        $container = $this->getMockContainer();
        $container->expects($this->once())
            ->method('get')
            ->with($alias)
            ->willreturn($transformer)
        ;

        $transformerContainer = new Serializer\TransformerContainer($container);

        $this->assertSame($transformer, $transformerContainer->getTransformer($alias));
    }

    public function testHasTransformer()
    {
        $faker = $this->getFaker();

        $alias = $faker->word;
        $hasTransformer = $faker->boolean();

        $container = $this->getMockContainer();
        $container->expects($this->once())
            ->method('has')
            ->with($alias)
            ->willreturn($hasTransformer)
        ;

        $transformerContainer = new Serializer\TransformerContainer($container);

        $this->assertSame($hasTransformer, $transformerContainer->hasTransformer($alias));
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|Container
     */
    private function getMockContainer()
    {
        return $this->buildMock(Container::class);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|TransformerAbstract
     */
    private function getMockTransformer()
    {
        return $this->buildMock(TransformerAbstract::class);
    }
}

Add Unit Test for TransformerContainer

Add Unit Test for TransformerContainer


<?php

require_once dirname(__FILE__) . '/../dbstewardUnitTestBase.php';

class ColumnDefaultIsFunctionTest extends dbstewardUnitTestBase
{

  /**
   * Tests that functions referenced as default values for columns
   * 1) do not result in build failures
   * 2) generate sane SQL on build
   */
  public function testBuildColumnSQL() {
    $xml = <<<XML
<dbsteward>
  <database>
    <role>
      <application>dbsteward_phpunit_app</application>
      <owner>deployment</owner>
      <replication/>
      <readonly/>
    </role>
  </database>

  <schema name="dbsteward" owner="ROLE_OWNER">
    <function name="test" returns="integer" owner="ROLE_OWNER" cachePolicy="VOLATILE" description="always returns 5, is a test function">
      <functionDefinition language="plpgsql" sqlFormat="pgsql8">
        BEGIN
          RETURN 5;
        END
      </functionDefinition>
    </function>
  </schema>
  <schema name="hotel" owner="ROLE_OWNER">

      <tableOption sqlFormat="pgsql8" name="with" value="(oids=false)"/>
      <column name="rate_id" type="integer" null="false"/>
      <column name="rate_group_id" null="false" foreignSchema="hotel" foreignTable="rate_group" foreignColumn="rate_group_id" foreignKeyName="rate_rate_group_id_fkey" foreignOnUpdate="NO_ACTION" foreignOnDelete="NO_ACTION"/>
      <column name="rate_name" type="character varying(120)"/>
      <column name="rate_value" type="numeric"/>

      <tableOption sqlFormat="pgsql8" name="with" value="(oids=false)"/>
      <column name="rate_group_id" type="integer" null="false" default="dbsteward.test()"/>
      <column name="rate_group_name" type="character varying(100)"/>
      <column name="rate_group_enabled" type="boolean" null="false" default="true"/>

  </schema>
</dbsteward>
XML;

    $expected = <<<EXP
ALTER TABLE hotel.rate ALTER COLUMN rate_id SET NOT NULL;
ALTER TABLE hotel.rate ALTER COLUMN rate_group_id SET NOT NULL;
ALTER TABLE hotel.rate_group ALTER COLUMN rate_group_id SET DEFAULT dbsteward.test();
ALTER TABLE hotel.rate_group ALTER COLUMN rate_group_id SET NOT NULL;
ALTER TABLE hotel.rate_group ALTER COLUMN rate_group_enabled SET DEFAULT true;
ALTER TABLE hotel.rate_group ALTER COLUMN rate_group_enabled SET NOT NULL;
EXP;

    $this->set_xml_content_a($xml);
    $this->build_db('pgsql8');
    $actual = file_get_contents(dirname(__FILE__) . '/../testdata/unit_test_xml_a_build.sql');
    $this->assertTrue(stripos($actual, $expected) !== FALSE);
  }
}

Test for checking that function return values as default column values works and doesn't break builds


<?php

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

namespace Symfony\Bundle\SwiftmailerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

/**
 * Warmup the cache.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author Clément JOBEILI <clement.jobeili@gmail.com>
 */
class SendEmailCommand extends Command
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('swiftmailer:spool:send')
            ->setDescription('Send all emails from the spool')
            ->addOption('message-limit', 0, InputOption::VALUE_OPTIONAL, 'The maximum number of messages to send.')
            ->addOption('time-limit', 0, InputOption::VALUE_OPTIONAL, 'The time limit for sending messages (in seconds).')
            ->setHelp(<<<EOF
The <info>swiftmailer:spool:send</info> command send all emails from the spool.

EOF
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $mailer     = $this->container->get('mailer');
        $transport  = $mailer->getTransport();

        if ("Swift_Transport_SpoolTransport" === get_class($transport)) {
            $spool = $transport->getSpool();
            $spool->setMessageLimit($input->getOption('message-limit'));
            $spool->setTimeLimit($input->getOption('time-limit'));
            $sent = $spool->flushQueue($this->container->get('swiftmailer.transport.real'));

            $output->writeln(sprintf('sent %s emails', $sent));
        }
    }
}

[SwiftMailer] Add the SendEmail Command (for the spool)


<?php
    namespace Library;

    /**
     * For storing messages to displaying to the user later. Use \Library\Session
     * for storing the message.
     *
     * @package Library
     *
     * @see \Library\Session
     */
    class Message
    {
        private $msg = array();

        private $flashCount = array();

        /**
         * Cache session instance
         *
         * @var object
         */
        private $session = null;

        public function __construct()
        {
            $this->session = page()->load->library('Session');
            $flashes = $this->session->getAllFlash();

            foreach ($flashes as $key=>$msg)
            {
                $keys = explode('_', $key);
                if ($keys[0] === 'msg')
                {
                    $this->write($keys[1], $keys[2]);
                }
            }
        }

        /**
         * Store success message to display later.
         *
         * @param  string $msg     Message to write
         * @param  bool   $persist Set if message will persist until the next page or
         *                         only exists on the current page.
         */
        public function success($msg, $persist=false)
        {
            $this->write('success', $msg, $persist);
        }

        /**
         * Store warning message to display later.
         *
         * @param  string $msg     Message to write
         * @param  bool   $persist Set if message will persist until the next page or
         *                         only exists on the current page.
         */
        public function warning($msg, $persist=false)
        {
            $this->write('warning', $msg, $persist);
        }

        /**
         * Store error message to display later.
         *
         * @param  string $msg     Message to write
         * @param  bool   $persist Set if message will persist until the next page or
         *                         only exists on the current page.
         */
        public function error($msg, $persist=false)
        {
            $this->write('error', $msg, $persist);
        }

        /**
         * Store info message to display later.
         *
         * @param  string $msg     Message to write
         * @param  bool   $persist Set if message will persist until the next page or
         *                         only exists on the current page.
         */
        public function info($msg, $persist=false)
        {
            $this->write('info', $msg, $persist);
        }

        /**
         * Actual method to store the message regardless of the type.
         *
         * @param  string $type    Message type
         * @param  string $msg     Message to write
         * @param  bool   $persist Set if message will persist until the next page or
         *                         only exists on the current page.
         */
        private function write($type, $msg, $persist=false)
        {
            $this->msg[$type][] = $msg;

            if ($persist)
            {
                $this->session->setFlash('msg_'.$type.'_'.$this->count[$type], $msg);
                $this->flashCount[$type]++;
            }
        }

        /**
         * Get all message as an array.
         *
         * @return array Collection of the message
         */
        public function getAsArray()
        {
            return $this->msg;
        }
    }

?>

Add library to store/receive user message