<?php

require dirname(__DIR__) . '/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use React\EventLoop\Factory;
use WyriHaximus\React\GuzzlePsr7\HttpClientAdapter;

$loop = Factory::create();

(new Client([
    'handler' => HandlerStack::create(new HttpClientAdapter($loop)),
]))->getAsync('http://blog.wyrihaximus.net/', [
    'stream' => true,
])->then(function(Response $response) use ($loop) { // Success callback
    $body = $response->getBody();
    $tick = function () use ($body, $loop, &$tick) {
        do {
            $data = $body->read(1024);
            echo $data;
            echo PHP_EOL;
            echo '----------------------------------------';
            echo PHP_EOL;
            echo '|                Chunk                 |';
            echo PHP_EOL;
            echo '----------------------------------------';
            echo PHP_EOL;
        } while ($data !== '');

        if (!$body->eof()) {
            $loop->futureTick($tick);
        } else {
            echo PHP_EOL;
        }
    };
    $loop->futureTick($tick);
}, function(Exception $error) { // Error callback
    echo $error->getMessage(), PHP_EOL;
    var_export($error);
});

$loop->run();

Handle stream using ticks example

Handle stream using ticks example


<?php namespace Lio\ServiceProviders;

use Illuminate\Support\ServiceProvider;
use Lio\Content\ForeignLanguageSpamDetector;
use Lio\Content\PhoneNumberSpamDetector;
use Lio\Content\SpamFilter;

class ContentServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bindShared('Lio\Content\SpamDetector', function () {
            return new SpamFilter([
                new PhoneNumberSpamDetector,
                new ForeignLanguageSpamDetector,
            ]);
        });
    }

    public function provides()
    {
        return ['Lio\Content\SpamDetector'];
    }
}

<?php namespace Lio\ServiceProviders;

use Illuminate\Support\ServiceProvider;
use Lio\Content\SpamFilter;

class ContentServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bindShared('Lio\Content\SpamDetector', function () {
            return new SpamFilter([]);
        });
    }

    public function provides()
    {
        return ['Lio\Content\SpamDetector'];
    }
}

Disable spam filters for now

Disable spam filters for now


<?php

use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;

class AddBarcodeId extends AbstractMigration
{
    public function up()
    {
      $q= "ALTER TABLE barcode DROP PRIMARY KEY,
                               ADD COLUMN `id` INT(11) unsigned NOT NULL
                                   AUTO_INCREMENT PRIMARY KEY FIRST,
                               ADD UNIQUE `item` (item, code)";
      $this->execute($q);
    }

    public function down()
    {
      $q= "ALTER TABLE barcode DROP PRIMARY KEY, DROP COLUMN `id`,
                               DROP KEY `item`,
                               ADD PRIMARY KEY (item, code)";
    }
}

Add simple primary key for barcode (easier for ORM)


<?php

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

class AddUserSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_settings', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('key');
            $table->string('value');
        });
    }

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

Add database migration for user settings


<?php

namespace Iyzipay\Tests\Request;

use Iyzipay\Model\Locale;
use Iyzipay\Request\CreatePaymentPostAuthRequest;
use Iyzipay\Tests\TestCase;

class CreatePaymentPostAuthRequestTest extends TestCase
{
    public function test_should_get_json_object()
    {
        $request = new CreatePaymentPostAuthRequest();
        $request->setLocale(Locale::TR);
        $request->setConversationId("123456");
        $request->setPaymentId("1");
        $request->setPaidPrice("0.6");
        $request->setIp("85.34.78.112");

        $jsonObject = $request->getJsonObject();

        $this->assertEquals(Locale::TR, $jsonObject["locale"]);
        $this->assertEquals("123456", $jsonObject["conversationId"]);
        $this->assertEquals("1", $jsonObject["paymentId"]);
        $this->assertEquals("0.6", $jsonObject["paidPrice"]);
        $this->assertEquals("85.34.78.112", $jsonObject["ip"]);
    }

    public function test_should_convert_to_pki_request_string()
    {
        $request = new CreatePaymentPostAuthRequest();
        $request->setLocale(Locale::TR);
        $request->setConversationId("123456");
        $request->setPaymentId("1");
        $request->setPaidPrice("0.6");
        $request->setIp("85.34.78.112");

        $str = "[locale=tr," .
            "conversationId=123456," .
            "paymentId=1," .
            "paidPrice=0.6," .
            "ip=85.34.78.112]";

        $this->assertEquals($str, $request->toPKIRequestString());
    }

    public function test_should_get_json_string()
    {
        $request = new CreatePaymentPostAuthRequest();
        $request->setLocale(Locale::TR);
        $request->setConversationId("123456");
        $request->setPaymentId("1");
        $request->setPaidPrice("0.6");
        $request->setIp("85.34.78.112");

        $json = '
            {
                "locale":"tr",
                "conversationId":"123456",
                "paymentId":"1",
                "paidPrice":"0.6",
                "ip":"85.34.78.112"
            }';

        $this->assertJson($request->toJsonString());
        $this->assertJsonStringEqualsJsonString($json, $request->toJsonString());
    }
}

Create payment post auth request test added


<?php

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

class CreateDaythemesTable extends Migration {

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

			$table->integer('eventgroup_id')->unsigned();
            $table->foreign('eventgroup_id')->references('id')->on('eventgroups');
			$table->string('title');
			$table->integer('date')->unsigned(); // use unix timestamp
		});
	}

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

}

Add missing migration for daythemes

Add missing migration for daythemes


<?php
use \Memvents\Event;

class EventModelTest extends \Codeception\TestCase\Test
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    function testSavingEvent()
    {
        $event = new Event();

        $event->name = 'Meetup Name';
        $event->event_id = 'qmmzjkytjbpb';
        $event->time = '1435077000000';
        $event->status = 'upcoming';
        $event->event_url = 'http://www.meetup.com/memphis-technology-user-groups/events/222899465/';
        $event->created = '1422646230000';

        $this->assertTrue($event->save());

        $this->assertEquals('Meetup Name', $event->name);

        $this->tester->seeRecord('events', array(
            'name' => 'Meetup Name',
            'event_id' => 'qmmzjkytjbpb',
            'time' => '1435077000000',
            'status' => 'upcoming',
            'event_url' => 'http://www.meetup.com/memphis-technology-user-groups/events/222899465/',
            'created' => '1422646230000',
        ));
    }

}

Add unit test for event model

Add unit test for event model


<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$c = trim(fgets(STDIN));

echo "TOTAL = R$ " . number_format($b + ($c * 0.15) * 100 / 100, 2, '.', '') . "\n";
?>

Solve Salary with Bonus in php

Solve Salary with Bonus in php


<?php

namespace mcordingley\Regression\Tests\Algorithm\GradientDescent\Gradient;

use mcordingley\Regression\Algorithm\GradientDescent\Gradient\Linear;
use mcordingley\Regression\Algorithm\GradientDescent\Gradient\Regularized;
use PHPUnit_Framework_TestCase;

class RegularizedTest extends PHPUnit_Framework_TestCase
{
    public function testCost()
    {
        $gradient = $this->makeGradient();
        static::assertEquals(1.5, $gradient->cost([1.0, 1.0], [2.0, 2.0], 3.0));
    }

    /**
     * @return Regularized
     */
    private function makeGradient()
    {
        $gradient = new Regularized(new Linear(2));

        return $gradient->ignoreFirstFeature(true)
                        ->setLambda(1.0)
                        ->setLevel(2);
    }

    public function testGradient()
    {
        $gradient = $this->makeGradient();
        static::assertEquals([16.0, 17.0], $gradient->gradient([1.0, 1.0], [2.0, 2.0], 3.0));
    }
}

Test the gradient descent regularizer.

Test the gradient descent regularizer.


<?php namespace Intergy\Storage;

use GuzzleHttp\Exception\RequestException;
use Log;
use \Exception;
use Cache;
use Intergy\Exceptions\MissingParameterException;
use Intergy\Exceptions\IntergyRequestError;
use Intergy\Exceptions\IntergyLogonError;

/**
 * Class Intergy Repository
 * It is a wrapper for the restful api
 * @package App\Services\Repositories
 *
 * In this repository you will find functionality that will allow you to send notifications
 * using the Intergys API.
 */
class UserStorage extends AbstractStorage
{
    /**
     * Search for a patient using the patientId into a specific practice
     *
     * @param   Integer     $providerId     Id of the user(provider) we want to notify.
     * @param   String      $subject        Text we want to see in the subject of the notification
     * @param   String      $subject        Text we will send as the notification's body
     * @return  Integer                     TaskId returned by Intergy's Api
     */
    public function getUsers( $practiceId )
    {
        // Get the pactice Id in case we haven't received one
        if( empty($practiceId) )
        {
            $practiceId = $this->getDefaultPractice();
        }

        // We need to be logged into the practice we want to search
        $this->logonToPractice( $practiceId, $this->userId, $this->licenseId, $this->sessionId, $this->userLogon, $this->applicationName );

        // Get Url to the search patient endpoint
        $uri = $this->getUrl( 'user-list-get' );

        // Create a Request
        $queryData = [
            'Credential' => [
                "LicenseID" => $this->licenseId,
                "SessionID" => $this->sessionId,
                "UserLogon" => $this->userLogon,
                "ApplicationName" => $this->applicationName,
                "UserMachineName" => "",
            ]
        ];

        // Send the request to the server and wait for the response
        $response = $this->callAPI( 'POST', $uri, $queryData );
        return $this->getUsersFromResult( $response );
    }

    /**
     * Extract the TaskID from the Notification Create Task request
     *
     * @param   Object     $response    Response returned by the server when send notification to Intergy
     * @return  Int                     Task Id
     */
    private function getUsersFromResult( $response )
    {
        // Checks parameters
        if( empty($response) )
        {
            throw new MissingParameterException( __FUNCTION__ );
        }

        return $response->UserList;
    }
}

PILOT-4895: Add functionality to get users from intergy api


<?php
class FlipsideCAPTCHA
{
    private $random_id;
    /*TODO - Replace with DB or something */
    private $questions = array('How much water should you bring to Burning Flipside?',
                               'Will you bring anything to sell at the event?',
                               'What does "no" mean?',
                               'What does MOOP stand for?'
                              );
    private $answers   = array('3 gallons per day',
                               'no',
                               'no',
                               'matter out of place');

    public function __construct()
    {
        $this->random_id = mt_rand(0, count($this->questions)-1);
    }

    public function get_question()
    {
        return $this->questions[$this->random_id];
    }

    public function is_answer_right($answer)
    {
        if(strcasecmp($answer, $this->answers[$this->random_id]) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function draw_captcha($explination = true, $return = false)
    {
        $string = '';
        if($explination)
        {
            $string .= 'The answer to this question may be found in the Burning Flipside Survival Guide. It may be found here.
';
        }

        $string .= '<form id="flipcaptcha" name="flipcaptcha">
            '.$this->get_question().'<input type="text" id="captcha" name="captcha"/>
        </form>';

        if(!$return)
        {
            echo $string;
        }
        else
        {
            return $string;
        }
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
?>

Add Flipside Survival Guide CAPTCHA test


<?php

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

class AddUserValidationHash extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('hashValidation')->nullable();
        });
    }

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

Add sha256 for user account validation

Add sha256 for user account validation


<?php

namespace DCS\User\CoreBundle\Tests\Event;

use DCS\User\CoreBundle\Event\UserEvent;
use DCS\User\CoreBundle\Model\UserInterface;

class UserEventTest extends \PHPUnit_Framework_TestCase
{
    public function testMethodGetUser()
    {
        $user = $this->getMockBuilder(UserInterface::class)->getMock();
        $userEvent = new UserEvent($user);
        $this->assertInstanceOf(UserInterface::class, $userEvent->getUser());
    }
}

Add test for UserEvent class

Add test for UserEvent class


<?php
namespace Particle\Tests\Filter\FilterRule;

use Particle\Filter\Filter;

class EachTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Filter
     */
    protected $filter;

    /**
     * Prepare the filter
     */
    public function setUp()
    {
        $this->filter = new Filter();
    }

    public function testBasicEach()
    {
        $this->filter->value('test')->each(function (Filter $filter) {
            $filter->value('test')->upper();
            $filter->value('test2')->lower();
        });

        $result = $this->filter->filter([
            'test' => [
                [
                    'test' => 'lower',
                    'test2' => 'UPPER'
                ],
                [
                    'test' => 'john',
                    'test2' => 'DOE',
                ],
            ],
        ]);

        $this->assertSame([
            'test' => [
                [
                    'test' => 'LOWER',
                    'test2' => 'upper'
                ],
                [
                    'test' => 'JOHN',
                    'test2' => 'doe',
                ],
            ],
        ], $result);
    }

    public function testEachDoesNotDoAnythingWhenNotArray()
    {
        $this->filter->value('test')->each(function (Filter $filter) {
            $filter->value('test')->upper();
            $filter->value('test2')->lower();
        });

        $result = $this->filter->filter([
            'test' => 'test',
        ]);

        $this->assertSame([
            'test' => 'test',
        ], $result);
    }
}

Add each rule test for repeated nested array support


<?php

require_once('tests/php/base.php');

class CASHRequestTests extends UnitTestCase {

    function testCASHRequest(){
		$cr = new CASHRequest(array(
			'cash_request_type' => 'asset',
			'cash_action'       => 'unlock',
			'asset_id'          => 42,
		));
        $this->assertIsa($cr, 'CASHRequest');
    }

}
?>

Add a test for CASHRequest

Add a test for CASHRequest


<?php
defined('C5_EXECUTE') or die('Access Denied.');
?>

        <?php require dirname(__FILE__) . '/worldskills_content.php'; ?>

Add wide template for Page Attribute Display block


<?php

namespace webignition\IsHttpStatusCode;

class CheckInvalidValuesTest extends \PHPUnit_Framework_TestCase {

    public function testCheck() {
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check(true));
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check(false));
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check(3.14));
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check(-1));
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check(99));
        $this->assertFalse(\webignition\IsHttpStatusCode\IsHttpStatusCode::check('foo'));
    }

}

Add test for invalid values

Add test for invalid values


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

namespace Soflomo\Common\Hydrator\Strategy;

use DateTime;
use Zend\Stdlib\Hydrator\Strategy\DefaultStrategy;

class DateTimeStrategy extends DefaultStrategy
{
    protected $allowNull;

    public function __construct($allowNull = true)
    {
        $this->allowNull = (bool) $allowNull;
    }

    /**
     * {@inheritdoc}
     *
     * Convert a string value intoa DateTime object
     */
    public function hydrate($value)
    {
        if (empty($value) && true === $this->allowNull) {
            $value = null;
        } elseif (is_string($value)) {
            $value = new DateTime($value);
        }

        return $value;
    }
}

Create strategy for hydrating datetime stamps


<?php

namespace Application\Migrations;

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

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

        $this->addSql('ALTER TABLE user CHANGE is_admin admin TINYINT(1) NOT NULL');
    }

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

        $this->addSql('ALTER TABLE user CHANGE admin is_admin TINYINT(1) NOT NULL');
    }
}

Add missing migration for new version of redmine login


<?php
namespace Ttree\Moltin\TypeConverter;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Property\PropertyMappingConfigurationInterface;
use TYPO3\Flow\Property\TypeConverter\AbstractTypeConverter;
use TYPO3\TYPO3CR\Domain\Model\NodeInterface;

/**
 * This Processor updates the Product NodeType with the existing
 * Categories from the Moltin API
 * @license http://www.opensource.org/licenses/mit-license.html MIT License
 */
class ProductConverter extends AbstractTypeConverter {

	/**
	 * @var array
	 */
	protected $sourceTypes = array('TYPO3\TYPO3CR\Domain\Model\NodeInterface');

	/**
	 * @var string
	 */
	protected $targetType = 'array';

	/**
	 * @var integer
	 */
	protected $priority = 1;

	/**
	 * {@inheritdoc}
	 */
	public function canConvertFrom($source, $targetType) {
		/** @var NodeInterface $source */
		return $source->getNodeType()->isOfType('Ttree.Moltin:ProductMixins');
	}

	/**
	 * {@inheritdoc}
	 */
	public function convertFrom($source, $targetType, array $convertedChildProperties = array(), PropertyMappingConfigurationInterface $configuration = NULL) {
		/** @var NodeInterface $source */
		return [
			'title' => $source->getProperty('title'),
			'slug' => $source->getIdentifier(),
			'sku' => $source->getProperty('productSku'),
			'price' => $source->getProperty('productPrice'),
			'sale_price' => $source->getProperty('productSalePrice'),
			'status' => $source->getProperty('productStatus'),
			'category' => $source->getProperty('productCategory'),
			'stock_level' => (integer)$source->getProperty('productStockLevel'),
			'stock_status' => $source->getProperty('productStockStatus'),
			'requires_shipping' => $source->getProperty('productRequiresShipping') ? 1 : 0,
			'catalog_only' => $source->getProperty('productCatalogOnly') ? 1 : 0,
			'tax_band' => (integer)$source->getProperty('productTaxband'),
			// todo use content dimensions to edit product description
			'description' => $source->getProperty('title')
		];
	}

}

[TASK] Add default type converter to get product data from a Node


<?php

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Migrations\Migration;

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

        Permission::firstOrCreate(['name' => 'create-payments-cash']);
        Permission::firstOrCreate(['name' => 'create-payments-check']);
        Permission::firstOrCreate(['name' => 'create-payments-swipe']);
        Permission::firstOrCreate(['name' => 'create-payments-square']);
        Permission::firstOrCreate(['name' => 'create-payments-squarecash']);

        $role = Role::firstOrCreate(['name' => 'admin']);
        $role->givePermissionTo('create-payments-cash');
        $role->givePermissionTo('create-payments-check');

        $role = Role::firstOrCreate(['name' => 'officer-ii']);
        $role->givePermissionTo('create-payments-cash');
        $role->givePermissionTo('create-payments-check');

        $role = Role::firstOrCreate(['name' => 'officer-i']);
        $role->givePermissionTo('create-payments-cash');
        $role->givePermissionTo('create-payments-check');
    }

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

        Permission::where('name', 'create-payments-cash')->delete();
        Permission::where('name', 'create-payments-check')->delete();
        Permission::where('name', 'create-payments-swipe')->delete();
        Permission::where('name', 'create-payments-square')->delete();
        Permission::where('name', 'create-payments-squarecash')->delete();
    }
}

Add create-payments-* permissions for different payment methods


<?php

namespace Apricot\Component;

trait Cache
{
    public static function cache($key, $value = null, $expire = 3600)
    {
        // add data into cache
        if (null !== $value) {
            if (function_exists('apc_add')) {
                if (!apc_add($key, $value, $expire)) {
                    throw new \RuntimeException(sprintf("Could not store data into cache (with name '%s')", $key));
                }
            }
        } else {
            if (function_exists('apc_fetch')) {
                return apc_fetch($key);
            }
        }
    }

    public static function purge()
    {
        if (function_exists('apc_clear_cache')) {
            return apc_clear_cache('user');
        }
    }
}

Add cache features with APC

Add cache features with APC


<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App\Models\Earning;
use App\Models\Spending;
use App\Models\Space;

class SpaceTest extends TestCase {
    public function testMonthlyBalance() {
        $space = factory(Space::class)->create();

        factory(Earning::class)->create([
            'space_id' => $space->id,
            'amount' => (int) ('39' * 100),
            'happened_on' => now()
        ]);

        $this->assertEquals('3900', $space->monthlyBalance(now()->year, now()->month));

        factory(Spending::class)->create([
            'space_id' => $space->id,
            'amount' => (int) ('12' * 100),
            'happened_on' => now()
        ]);

        $this->assertEquals('2700', $space->monthlyBalance(now()->year, now()->month));

        factory(Spending::class)->create([
            'space_id' => $space->id,
            'amount' => (int) ('50' * 100),
            'happened_on' => now()
        ]);

        // Monthly balance can be negative
        $this->assertEquals('-2300', $space->monthlyBalance(now()->year, now()->month));

        factory(Earning::class)->create([
            'space_id' => $space->id,
            'amount' => (int) ('10' * 100),
            'happened_on' => date_create_from_format('Y-m-d', '2018-01-01')
        ]);

        // First is same as before, because earning happened on a different month
        $this->assertEquals('-2300', $space->monthlyBalance(now()->year, now()->month));
        $this->assertEquals('1000', $space->monthlyBalance(2018, 01));

        factory(Earning::class)->create([
            'space_id' => 2,
            'amount' => (int) ('10' * 100),
            'happened_on' => date_create_from_format('Y-m-d', '2020-01-01')
        ]);

        // 0 because different space-id
        $this->assertEquals('0', $space->monthlyBalance(2020, 01));
    }
}

Test Space model's monthlyBalance method


<?php

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

class MoreEntityUniqueness extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::transaction(function() {
            DB::statement("update entities set validated=0;");
            DB::statement("update entities inner join entity_iso_names on entity_iso_names.name=entities.name set entities.code=entity_iso_names.code, validated=1;");

            DB::statement("create temporary table unique_entities (select e.id as orig_id, e.code as code, (select min(id) from entities where entities.code=e.code) as uniq_id from entities as e where e.code != '');");

            $pairs = DB::select("select orig_id, uniq_id from unique_entities where orig_id != uniq_id;");
            $oldToUnique = [];
            foreach ($pairs as $pair) {
                $oldToUnique[$pair->orig_id] = $pair->uniq_id;
            }

            $charts = Chart::all();
            foreach ($charts as $chart) {
                $config = json_decode($chart->config);
                $countries = $config->{'selected-countries'};
                if (empty($countries)) continue;

                foreach ($countries as $country) {
                    if (array_key_exists($country->id, $oldToUnique)) {
                        echo("Updating chart config for " . $chart->id . " changing entity id from " . $country->id . " to " . $oldToUnique[$country->id] . "\n");
                        $country->id = $oldToUnique[$country->id];
                    }
                }

                $chart->config = json_encode($config);
                $chart->save();
            }

            DB::statement("update data_values as dv inner join unique_entities as e on e.orig_id=dv.fk_ent_id set dv.fk_ent_id=e.uniq_id;");
            DB::statement("delete from entities where entities.id in (select orig_id from unique_entities where orig_id != uniq_id);");

            Schema::table("entities", function($table) {
                $table->string('code')->nullable()->change();
            });

            DB::statement("update entities set code=NULL where code='';");

            Schema::table("entities", function($table) {
                $table->unique('code');
            });

            DB::statement("update entities inner join entity_iso_names on entity_iso_names.code=entities.code and entities.code IS NOT NULL set entities.name=entity_iso_names.name, validated=1;");

            Schema::drop("entity_iso_names");
        });
    }

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

Refactor entity_iso_names into entities table and make it more rigorous


<?php

namespace Cs278\BankModulus\Spec;

/**
 * @covers Cs278\BankModulus\Spec\SimpleSpecFactory
 */
final class SimpleSpecFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testCreate()
    {
        $spec = new VocaLinkV390();
        $factory = new SimpleSpecFactory($spec);

        // Both calls should return the same object.
        $this->assertSame($spec, $factory->create());
        $this->assertSame($spec, $factory->create());
    }
}

Add tests for simple spec factory

Add tests for simple spec factory


<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130122121234_set_default_Job_type_id extends BaseMigration
{
    public function up(Schema $schema)
    {

        $this->statements['mysql'] = array(
            "UPDATE Job SET type_id = 1"
        );

        $this->statements['sqlite'] = array(
            "UPDATE Job SET type_id = 1"
        );

        parent::up($schema);
    }

    public function down(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "SELECT 1 + 1"
        );

        $this->statements['sqlite'] = array(
            "SELECT 1 + 1"
        );

        parent::down($schema);
    }
}

Set Job type_id to 1 for all jobs

Set Job type_id to 1 for all jobs


<?php
/**
 * Plugin Name: Disable Login Autofocus
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

add_filter( 'enable_login_autofocus', '__return_false' );

Disable login autofocus during e2e.

Disable login autofocus during e2e.


<?php

require_once('Classloader.php');
require_once('xmlrpc.inc');

$classLoader = new Infusionsoft_Classloader();
spl_autoload_register(array(&$classLoader, "loadClass"));

require('config.php');

<?php

require_once('Classloader.php');

if(!function_exists('xmlrpc_encode_entitites') && !class_exists('xmlrpcresp')) {
	require_once('xmlrpc.inc');
}

$classLoader = new Infusionsoft_Classloader();
spl_autoload_register(array(&$classLoader, "loadClass"));

require('config.php');

Check whether functions and class before loading file


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * This is the full name extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class FullNameExtractorTest extends AbstractGenericExtractorTest
{
    public function testExtractFullName()
    {
        $text = [
            'CARLA SOFIA LEITÃO DA SILVA (Telf: 912345678)' => 'CARLA SOFIA LEITÃO DA SILVA',
            'PINGO DA UVA UNIPESSOAL LDA'                   => 'PINGO DA UVA UNIPESSOAL LDA',
        ];

        foreach ($text as $input => $expected) {
            $this->assertSame($expected, $this->extractor->fullName($input));
        }
    }
}

Add full name extractor test

Add full name extractor test


<?php

class Broken_Taxonomy_Type extends Papi_Taxonomy_Type {

	/**
	 * Define our Taxonomy Type meta data.
	 *
	 * @return array
	 */
	public function meta2() {
		return [
			'id'          => 'custom-taxonomy-type-id',
			'name'        => 'Broken taxonomy',
			'description' => 'This is a broken taxonomy',
			'template'    => 'pages/broken-taxonomy.php'
		];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
	}
}

Add broken taxonomy type test file

Add broken taxonomy type test file


<?php

require_once(TESTDIR . 'simpletest/autorun.php');
require_once(TESTDIR . '../SSI.php');
require_once(SOURCEDIR . '/Errors.class.php');

/**
 * TestCase class for Error_Context class.
 * Tests adding and removing errors and few other options
 */
class TestError_Context extends UnitTestCase
{
	function testSimpleError()
	{
		$error_context = Error_Context::context();

		// Let's add an error and see
		$error_context->addError('test');
		$this->assertTrue($error_context->hasErrors());
		$this->assertTrue($error_context->hasError('test'));
		$this->assertFalse($error_context->hasError('test2'));
		$this->assertEqual($error_context->getErrorType(), Error_Context::MINOR);

		// Now the error can be removed
		$error_context->removeError('test');
		$this->assertFalse($error_context->hasErrors());
		$this->assertFalse($error_context->hasError('test'));
		$this->assertFalse($error_context->hasError('test2'));
		$this->assertFalse($error_context->getErrors());
	}
}

Add some basic testing for Error_Context

Signed-off-by: emanuele <ac2faa8b943b3fcadaf05ed2541f4eebde440ed7@gmail.com>


@foreach ($comments as $comment)

                @if ($comment->isDeletable())
                     $comment->getId(),
                                            ]) }}">

                @endif
                @if ($comment->isEditable())
                     $comment->getId(),
                                            ]) }}" data-comment-id="{{ $comment->getId() }}">

                @endif
                {{ $comment->getUser()->getName() }}

                        getCreatedAt()->format("Y-m-d H:i:s") }}"
                              data-vulnerability-id="{{ $comment->getVulnerability()->getId() }}">
                                                    {{ $comment->getTimeSinceComment() }}

getId() }}" class="chat-content">
                {!! $comment->getContent() !!}

            @if ($comment->isEditable())

getId() }}" class="comment-editor">

                        <form class="comment-edit-form" action="{{ route('comment.edit', ['commentId' => $comment->getId()]) }}" method="POST">
                            {{ csrf_field() }}
                            <textarea class="comment-edit-txt post-form-control" name="comment-{{ $comment->getId() }}" rows="1" placeholder="Type your comment here...">
                                                        {!! $comment->getContent() !!}
                                                    </textarea>
                        </form>

                        <button class="primary-btn btn-edit-chat" data-comment-id="{{ $comment->getId() }}">Save Changes</button>
                        <button class="btn btn-cancel edit-comment-cancel" data-comment-id="{{ $comment->getId() }}">Cancel</button>

            @endif

@endforeach

Create a new partial to display the list item HTML for each comment so that it can be reused by the ajax request that fetches new comments.


<?php
    date_default_timezone_set('America/Chicago');

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python read.py $target");
    $output = shell_exec($command);
    echo "<pre>";
    print_r($output);
    echo "</pre>";

//  Re-route to directory to download the file.
    $domain = $_SERVER['HTTP_HOST'];
    $path = implode("/",$fullPath);
    $toLogin = 'http://'.$domain.$path."/out";
    header('Location:'.$toLogin);
?>

Include file to pass uploaded file from php to the python file that changes the format to csv


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

namespace Darvin\ContentBundle\Form\Type\Autocomplete;

use Symfony\Component\Form\AbstractType;

/**
 * Entity autocomplete form type
 */
class EntityAutocompleteType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function getParent(): string
    {
        return AutocompleteType::class;
    }

    /**
     * {@inheritDoc}
     */
    public function getBlockPrefix(): string
    {
        return 'darvin_content_entity_autocomplete';
    }
}

Add dummy entity autocomplete form type.


<?php
/**
 * doctrine custom type to handle reading and writing $refs attributes
 */

namespace Graviton\DocumentBundle\Types;

use Doctrine\ODM\MongoDB\Mapping\Types\Type;

/**
 * based on http://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/basic-mapping.html#custom-mapping-types
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     http://swisscom.ch
 */
class ExtReference extends Type
{
    /**
     * get php value when field is used as identifier
     *
     * @param \MongoDBRef $value ref from mongodb
     *
     * @return string
     */
    public function convertToPHPValue(\MongoDBRef $value)
    {
        // @todo use router to generate an absolute url from $value
    }

    /**
     * return a closure as string that sets $return if field is a regular field
     *
     * @return string
     */
    public function closureToPHP()
    {
        // @todo figure out how to inject a router into this string closure stuff
    }

    /**
     * return the mongodb representation from a php value
     *
     * @param string $value value of reference as URI
     *
     * @return mixed
     */
    public function convertToDatabaseValue($value)
    {
        // @todo generate these using an injected router
        $collection = 'foo';
        $id = 1234;
        return \MongoDBRef::create($collection, $id);
    }
}

Add scaffolding for doctrine custom type

[ci skip]


<?php

namespace Swarrot\Broker\MessagePublisher;

use Prophecy\Prophet;
use Prophecy\Argument;

use PhpAmqpLib\Message\AMQPMessage;

use Swarrot\Broker\MessagePublisher\PhpAmqpLibMessagePublisher;
use Swarrot\Broker\Message;

class PhpAmqpLibMessagePublisherTest extends \PHPUnit_Framework_TestCase
{
    /** @var Prophet */
    protected $prophet;

    public function setUp()
    {
        $this->prophet = new Prophet;
    }

    public function tearDown()
    {
        $this->prophet->checkPredictions();
    }

    public function test_publish_with_valid_message()
    {
        $channel = $this->prophet->prophesize('PhpAmqpLib\Channel\AMQPChannel');

        $channel->basic_publish(
            Argument::that(function(AMQPMessage $message) {
                $properties = $message->get_properties();

                return 'body' === $message->body && empty($properties);
            }),

            Argument::exact('swarrot'),
            Argument::exact('')
        )->shouldBeCalledTimes(1);

        $provider = new PhpAmqpLibMessagePublisher($channel->reveal(), 'swarrot');
        $return = $provider->publish(
            new Message('body')
        );

        $this->assertNull($return);
    }
}

Add some tests on PhpAmqpLibMessagePublisher


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

use App\Controller\DashboardController;
use Cake\TestSuite\IntegrationTestCase;

/**
 * App\Controller\OperationsController Test Case
 */
class DashboardControllerTest extends IntegrationTestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [];

    /**
     * Test index method
     *
     * @return void
     */
    public function testIndexUnauthenticaded()
    {
        $this->get('/dashboard');

        $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
    }

	public function testIndexAuthenticaded()
    {
		$this->session([
			'Auth' => [
				'User' => [
					'id' => 1,
					'username' => 'admin',
				]
			]
		]);
		$this->get('/dashboard');

		$this->assertResponseOk();
    }

}

Test index of Dashboard controller.

Test index of Dashboard controller.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class CandidateStep7Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
			     ->add('public_values', 'choice', array(
			     		'multiple' => TRUE,
			     		'expanded' => TRUE,
			     		'choices' => array(
			     				'1' => 'HONESTIDAD',
			     				'2' => 'TRANSPARENCIA',
			     				'3' => 'RESPETO',
			     				'4' => 'RESPONSABILIDAD',
			     				'5' => 'COMPROMISO',
			     				'6' => 'INTEGRIDAD',
			     				'7' => 'IGUALDAD',
			     				'8' => 'TOLERANCIA',
			     				'9' => 'COOPERACIÓN',
			     				'10' => 'SOLIDARIDAD',
			     				'11' => 'JUSTICIA',
			     		),
			     		'data_class' => NULL,
			     		'constraints' => array(
			     				new Assert\Count(array(
						            'max'        => 3,
						            'minMessage' => 'You must specify at least one email',
						            'maxMessage' => 'Sólo puedes seleccionar hasta {{ limit }} opciones como máximo',
						        ))
			     		)
			     ))
			     ->add('motivation_text', 'textarea', array(
			     		'attr' => array('class' => 'tinymce', 'style' => 'width:100%;height:200px'),
			     		'required' => FALSE
			     ))
			     ->add('town_activities_explanation', 'textarea', array(
			     		'attr' => array('class' => 'tinymce', 'style' => 'width:100%;height:200px'),
			     		'required' => FALSE
			     ))
			     ->add('additional_info', 'textarea', array(
			     		'attr' => array('class' => 'tinymce', 'style' => 'width:100%;height:200px'),
			     		'required' => FALSE
			     ))
			     ->add('profile_image', 'file', array(
			     		'required' => FALSE,
			     		'data_class' => NULL,
			     		'constraints' => array(
			     				new Assert\File(array('maxSize' =>'1024k')),
			     		)
			     	)
			     )
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add candidate step 7 type form

Add candidate step 7 type form


<?php

/**
 * (Sample) Localization Configuration File
 * This config file contains localization config values needed
 * by the l10n libraries, including:
 *

 *
Localization Domain

 *
Location of the language files

 *
Default language

 *
...

 *

 * You can override these values in an application
 * specific config file.
 *
 * PHP Version 5.3
 *
 * @category   Config
 * @package    L10n
 * @subpackage Config
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

$config['l10n'] = array();

/**
 * Localization Domain
 * @global String $config['l10n']['domain']
 */
$config['l10n']['domain'] = 'Lunr';

/**
 * Language file location
 *
 * By default this points to a top-level 'l10n' directory.
 *
 * @global String $config['l10n']['locales']
 */
$config['l10n']['locales'] = dirname(__FILE__) . '/../../l10n';

/**
 * Default interface language (POSIX locale)
 * @global String $config['l10n']['default_language']
 */
$config['l10n']['default_language'] = 'en_US';

?>

Add sample l10n config file

system: Add sample l10n config file


<?php

namespace Tests\AppBundle\API\Details;

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

class OrganismsTest extends WebTestCase
{

    public function testExecute()
    {
        $client = static::createClient();
        $default_db = $client->getContainer()->getParameter('default_db');
        $session = null;
        $organisms = $client->getContainer()->get('app.api.webservice')->factory('details', 'organisms');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "organism_id" => 42,
            "scientific_name" => "Artocarpus pithecogallus",
            "rank" => "species",
            "common_name" => null,
            "eol_accession" => "",
            "ncbi_accession" => "1679377"
        );
        $this->assertEquals($expected, $results);
    }
}

Add test for details organisms webservice


<?php

namespace Test\Phinx\Console\Command;

use Phinx\Console\PhinxApplication;
use Symfony\Component\Console\Tester\ApplicationTester;

class ListTest extends \PHPUnit_Framework_TestCase
{
    public function testVersionInfo()
    {
        $application = new PhinxApplication();
        $application->setAutoExit(false); // Set autoExit to false when testing
        $application->setCatchExceptions(false);

        $appTester = new ApplicationTester($application);
        $appTester->run(['command' => 'list', '--format' => 'txt']);
        $stream = $appTester->getOutput()->getStream();
        rewind($stream);

        $this->assertEquals(1, substr_count(stream_get_contents($stream), 'Phinx by CakePHP - https://phinx.org'));
    }
}

<?php

namespace Test\Phinx\Console\Command;

use Phinx\Console\PhinxApplication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\ApplicationTester;

class ListTest extends TestCase
{
    public function testVersionInfo()
    {
        $application = new PhinxApplication();
        $application->setAutoExit(false); // Set autoExit to false when testing
        $application->setCatchExceptions(false);

        $appTester = new ApplicationTester($application);
        $appTester->run(['command' => 'list', '--format' => 'txt']);
        $stream = $appTester->getOutput()->getStream();
        rewind($stream);

        $this->assertEquals(1, substr_count(stream_get_contents($stream), 'Phinx by CakePHP - https://phinx.org'));
    }
}

Move test to use namespaced PHPUnit TestCase


<?php
namespace Bolt\Assets\File;

/**
 * Cascading stylesheet file object class.
 *
 * @author Gawain Lynch <gawain.lynch@gmaill.com>
 */
class Stylesheet extends AssetBase
{
    /**
     * Return a string representation of the class.
     *
     * @return string
     */
    public function __toString()
    {
        return sprintf('<link rel="stylesheet" href="%s" media="screen">', $this->fileName);
    }
}

Add a class for CSS asset injection

Add a class for CSS asset injection


@if ($item->$field_name != null && $item->$field_name != '')
	<img src="{!! Croppa::url_resize('uploads/' . $route_prefix . '/' . $item->$field_name, 180) !!}" />
@endif

Add admin list image field

Add admin list image field


<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130425133722_create_AccountPlanConstraint extends BaseMigration
{
    public function up(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "CREATE TABLE AccountPlanConstraint (
                id INT AUTO_INCREMENT NOT NULL,
                name VARCHAR(255) NOT NULL,
                `limit` INT DEFAULT NULL,
                isAvailable TINYINT(1) NOT NULL,
                UNIQUE INDEX UNIQ_E18FF0B75E237E06 (name),
                PRIMARY KEY(id))
                DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"
        );

        $this->statements['sqlite'] = array(
            "CREATE TABLE AccountPlanConstraint (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                name VARCHAR(255) NOT NULL,
                `limit` INT DEFAULT NULL,
                isAvailable TINYINT(1) NOT NULL)",
            "CREATE UNIQUE INDEX UNIQ_E18FF0B75E237E06 ON AccountPlanConstraint (name)"
        );

        parent::up($schema);
    }

    public function down(Schema $schema)
    {
        $this->addCommonStatement("DROP TABLE AccountPlanConstraint");

        parent::down($schema);
    }
}

Add migration to create AccountPlanConstraint


<?php

namespace App\Http\Controllers;

use App\Rental;
use Illuminate\Http\Request;

use App\Http\Requests;

class RentalController extends Controller
{

    /**
     * Get all the requested rentals.
     *
     * @param string $type, the database selector, where the data range will set on.
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function indexAdmin($type)
    {
        if ($type == 'all' || empty($type))
        {
            $data['rentals'] = Rental::paginate(15);
        } elseif($type == 'new') {
            $data['rentals'] = Rental::where('status', 0)->paginate(15);
        } elseif($type == 'option') {
            $data['rentals'] = Rental::where('status', 1)->paginate(15);
        }

        return view('backend.rental.overview', $data);
    }

    /**
     * Insert view for a backend rental insert.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function insert()
    {
        return view('backend.rental.insert');
    }

    /**
     * Insert a new rental.
     *
     * @param Requests\RentalValidator $input
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Requests\RentalValidator $input)
    {
        Rental::insert($input->except('_token'));
        session()->flash('message', 'Nieuwe verhuring toegevoegd');

        return redirect()->back(302);
    }

    /**
     * Delete a rental.
     *
     * @param  int, $id, the rental id in the database.
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        Rental::destroy($id);
        session()->flash('message', 'U hebt een verhuring verwijderd');

        return redirect()->back(302);
    }

    /**
     * Set a rental to confirmed.
     *
     * @param  int, $id, the rental id in the database.
     * @return \Illuminate\Http\RedirectResponse
     */
    public function confirmed($id)
    {
        $rental = Rental::find($id);
        $rental->Status = 2;
        $rental->save();

        session()->flash('message', 'U hebt een verhuring de status bevestgd gegeven.');

        return redirect()->back(302);
    }

    /**
     * Set a rental to option status.
     *
     * @param int, $id, The rental id in the database.
     * @return \Illuminate\Http\RedirectResponse
     */
    public function option($id)
    {
        $rental = Rental::find($id);
        $rental->Status = 1;
        $rental->save();

        session()->flash('message', 'U hebt een verhuring de status optie gegeven');

        return redirect()->back(302);
    }
}

Add the rental controller - backend

Add the rental controller - backend


<?php
header('Content-Type: text/plain');
exec('git fetch --all ; git checkout --force origin/master 2>&1', $output, $status);
if ($status != 0) http_response_code(500);
echo implode("\n", $output);
echo "\n";

Add web hook endpoint for auto-checkout

Add web hook endpoint for auto-checkout


<?php

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

class CreateSessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->unique();
            $table->text('payload');
            $table->integer('last_activity');
        });
    }

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

Add db table to support db based sessions


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

use \Skeleton\Database\Database;

class Migration_20200925_133303_Paid_default_value extends \Skeleton\Database\Migration {

	/**
	 * Migrate up
	 *
	 * @access public
	 */
	public function up() {
		$db = Database::get();
		$db->query("
			ALTER TABLE `invoice`
			CHANGE `paid` `paid` tinyint(4) NOT NULL DEFAULT '0' AFTER `customer_contact_id`;
		", []);
	}

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

	}
}

Fix default value of invoice paid column


<?php

namespace App\Console\Commands\Report;

use App\Models\Collections\Artwork;

use League\Csv\Writer;
use Illuminate\Support\Facades\Storage;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportNoImages extends BaseCommand
{

    protected $signature = 'report:no-images';

    protected $description = "Report all artworks that have no preferred images set";

    public static $filename = 'artwork-no-images.csv';

    protected $csv;

    public function handle()
    {

        // Not an ideal solution, but some models are really heavy
        ini_set("memory_limit", "-1");

        $this->csv = Writer::createFromPath( $this->getCsvPath(), 'w' );

        $this->csv->insertOne([
            'artwork_id',
            'main_reference_number',
            'title',
        ]);

        // The rest we'll have to filter manually for now
        $this->getArtworksWithoutPreferredImages();

        // Any artwork that doesn't have images automatically qualifies
        $this->getArtworksWithoutAnyImages();

    }

    private function getArtworksWithoutAnyImages()
    {
        $artworks = Artwork::whereDoesntHave('images');

        foreach ($artworks->cursor() as $artwork)
        {
            $this->insertOne( $artwork );
        }
    }

    private function getArtworksWithoutPreferredImages()
    {
        $artworks = Artwork::whereHas('images');

        foreach ($artworks->cursor() as $artwork)
        {
            if (!$artwork->image()) {
                $this->insertOne( $artwork );
            }
        }
    }

    private function insertOne( $artwork )
    {
        $row = [
            'artwork_id' => $artwork->citi_id,
            'main_reference_number' => $artwork->main_id,
            'title' => $artwork->title,
        ];

        $this->csv->insertOne($row);
    }

    private function getCsvPath()
    {

        return Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix() . self::$filename;

    }

}

Add command to report artworks w/o preferred images


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Extractors;

/**
 * This is the property extractor wrapper.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class PropertyExtractorWrapper extends AbstractExtractorWrapper
{
    const EXTRACTORS = [];
}

Add the property extractor wrapper

Add the property extractor wrapper


<?php

/*
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI 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.

Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

class SearchOptionsTest extends CommonTestCase
{
    /**
     * @test
     */
    public function checkAll()
    {
        $classes = array('Alert',
                         'Agent',
                         'Job',
                         'Scan',
                         'ScanConfig',
                         'State');

        foreach( $classes as $class )
        {
            $class = 'PluginArmadito'.$class;
            $item = new $class();
            $item->getSearchOptions();
        }
    }
}

Add missing Search it test dir

Add missing Search it test dir


<?php

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

class AddCroppedImageColumnToItems extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('reportback_items', function (Blueprint $table) {
            $table->string('cropped_file_url')->nullable()->after('file_url');
        });
    }

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

Add a column to the items table to store cropped image


<?php

namespace ThisData\Api\RequestHandler;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class SynchronousRequestHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandle()
    {
        $client = $this->getMockBuilder(Client::class)
            ->getMock();

        $request = new Request('get', 'uri');

        $client->expects($this->once())
            ->method('send')
            ->with($request);

        $handler = new SynchronousRequestHandler();
        $handler->handle($client, $request);
    }
}

Add test for sync handler

Add test for sync handler


<?php

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

class AddTrackingSourceToTracks extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('tracks', function($table) {
            DB::statement('SET SQL_MODE = "ALLOW_INVALID_DATES";');
            DB::statement('ALTER TABLE tracks ALTER COLUMN `point_time` DROP DEFAULT');
            DB::statement('ALTER TABLE tracks CHANGE COLUMN `point_time` `point_time` DATETIME NOT NULL');
            $table->string('tracks_source', 16)->nullable(true)->default(null);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('tracks', function($table) {
            $table->dropColumn('tracks_source');
            DB::statement('ALTER TABLE tracks CHANGE COLUMN `point_time` `point_time` TIMESTAMP NOT NULL');
        });
    }
}

Add tracks_source to gliding.tracks Change point_time from TIMESTAMP to DATETIME. DROP DEFAULT from point_time.


<?php

namespace Collector\Data;

trait InvoiceDeliveryMethodTrait
{
    static public $InvoiceDeliveryMethodNormalMail = 1;
    static public $InvoiceDeliveryMethodEmail = 2;

    /**
     * @var int
     */
    protected $InvoiceDeliveryMethod;

    /**
     * @param int $InvoiceDeliveryMethod
     */
    public function setInvoiceDeliveryMethod($InvoiceDeliveryMethod)
    {
        $this->InvoiceDeliveryMethod = $InvoiceDeliveryMethod;
    }

    /**
     * @return int
     */
    public function getInvoiceDeliveryMethod()
    {
        return $this->InvoiceDeliveryMethod;
    }
}

Append invoice delivery method trait

Append invoice delivery method trait


<?php

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

namespace spec\FreeDSx\Ldap\Server;

use FreeDSx\Ldap\Server\ChildProcess;
use FreeDSx\Socket\Socket;
use PhpSpec\ObjectBehavior;

class ChildProcessSpec extends ObjectBehavior
{
    public function let(Socket $socket)
    {
        $this->beConstructedWith(9001, $socket);
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType(ChildProcess::class);
    }

    public function it_should_get_the_pid()
    {
        $this->getPid()->shouldBeEqualTo(9001);
    }

    public function it_should_get_the_socket()
    {
        $this->getSocket()->shouldBeAnInstanceOf(Socket::class);
    }
}

Add a simple spec for the child process.


<?php

require dirname(__FILE__).'/_global.php';

echo "Please enter the ID of the user whose reports you wish to retrieve: ";
$id = trim(fgets(STDIN));

print_r($api->getReportsForUser($id));

Add example for GET /users/ID/reports

Add example for GET /users/ID/reports


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

namespace PH7\Test\Unit\Framework\Ajax;

use PH7\Framework\Ajax\Ajax;

class AjaxTest extends \PHPUnit_Framework_TestCase
{
    public function testJsonMsg()
    {
        $sActualResult = Ajax::jsonMsg(1, 'Yaaay!');
        $this->assertEquals('{"status":1,"txt":"Yaaay!"}', $sActualResult);
    }
 }

Add unit test for Ajax class

Add unit test for Ajax class


<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

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

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

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

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

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

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

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

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

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

        return $result;
    }
}

<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

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

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

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

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

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

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

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

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

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

        return $result;
    }
}

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


<?php

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

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

class CensusStep2Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Update form type for step 2

Update form type for step 2


<?php

require __DIR__.'/autoload.php';

use LaravelLb\LogicBoxesComodo;

// Setup user id and api key
$userId = getenv('LB_AUTH_USERID');
$apiKey = getenv('LB_API_KEY');

$orderId = "71784811";
$csr = 'CSR';
$verificationEmail = "test@example.com";

$comodo = new LogicBoxesComodo();

/** No need to set user id if you're using Laravel, it will automatically get the credential from config/logicboxes.php */
$comodo->setUserId($userId)->setApiKey($apiKey);

$response = $comodo->enroll($orderId, $csr, $verificationEmail)->toArray();

print_r($response);

Add ssl comodo enrol example.

Add ssl comodo enrol example.


<?php namespace Modules\Translation\Jobs;

use App\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Modules\Translation\Repositories\DatabaseTranslationRepository;
use Modules\Translation\Repositories\FileTranslationRepository;
use Modules\Translation\ValueObjects\TranslationGroup;

class BuildTranslationsCache extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    /**
     * @var FileTranslationRepository
     */
    private $fileTranslations;
    /**
     * @var DatabaseTranslationRepository
     */
    private $databaseTranslations;

    public function __construct()
    {
        $this->fileTranslations = app(FileTranslationRepository::class);
        $this->databaseTranslations = app(DatabaseTranslationRepository::class);
    }

    public function handle()
    {
        $this->cacheAll(new TranslationGroup($this->getFileAndDatabaseMergedTranslations()));

        logger()->info('All translations have been cached.');

        $this->delete();
    }

    /**
     * Cache the given TranslationGroup
     * @param TranslationGroup $group
     */
    public function cacheAll(TranslationGroup $group)
    {
        Cache::tags('global', 'translations')->forever('allTranslations', $group);
    }

    /**
     * Get the file translations & the database translations, overwrite the file translations by db translations
     * @return array
     */
    private function getFileAndDatabaseMergedTranslations()
    {
        $allFileTranslations = $this->fileTranslations->all();
        $allDatabaseTranslations = $this->databaseTranslations->all();

        foreach ($allFileTranslations as $locale => $fileTranslation) {
            foreach ($fileTranslation as $key => $translation) {
                if (isset($allDatabaseTranslations[$locale][$key])) {
                    $allFileTranslations[$locale][$key] = $allDatabaseTranslations[$locale][$key];
                }
            }
        }
        return $allFileTranslations;
    }
}

Create a queued job to cache all translations


<?php
/**
 * This file is part of the beebot package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2015
 * @author    Stephane HULARD <s.hulard@chstudio.fr>
 * @package   Test\Bee4\RobotsTxt
 */

namespace Test\Bee4\RobotsTxt;

use Bee4\RobotsTxt\Parser;

/**
 * Parser unit test
 * @package Test\Bee4\RobotsTxt
 */
class ParserTest extends \PHPUnit_Framework_TestCase
{
	protected $content = "User-agent: *
Disallow: /mentions-legales/

User-agent: google-bot
Allow: /truite.php
disallow: /";

	public function testParse() {
		$object = new Parser($this->content);
		$rules = $object->parse();

		$rule = $rules->get('*');
		$this->assertInstanceOf('\Bee4\RobotsTxt\Rule', $rule);

		$this->assertFalse($rule->match('/mentions-legales/'));
		$this->assertTrue($rule->match('/another-page.html'));

		$this->assertFalse($rules->match('Google-Bot v01', '/toto'));
		$this->assertTrue($rules->match('Google-Bot v01', '/truite.php'));
	}
}

Add tests on Parser + Rules

Add tests on Parser + Rules

Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for reject Mimic library function.
 *
 * @since 0.1.0
 */
class RejectFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		$range = range(0, 10);
		return array(
			array($range, array(), function() { return true; }),
			array($range, $range, function() { return false; }),
			array($range, array(0 => 0, 2 => 2, 4 => 4, 6 => 6, 8 => 8, 10 => 10), function($element) { return ! (($element % 2) === 0); }),
			array($range, array(1 => 1, 3 => 3, 5 => 5, 7 => 7, 9 => 9), function($element) { return (($element % 2) === 0); }),
			array($range, array(0 => 0, 2 => 2, 4 => 4, 6 => 6, 8 => 8, 10 => 10), function($element, $index) { return ! (($index % 2) === 0); }),
			array($range, array(1 => 1, 3 => 3, 5 => 5, 7 => 7, 9 => 9), function($element, $index) { return (($index % 2) === 0); }),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\reject
	 */
	public function testResults($collection, $expected, $callback) {
		$this->assertEquals($expected, F\reject($collection, $callback));
	}
}

Add reject function test suite.

Add reject function test suite.


<?php namespace Aedart\Scaffold\Collections\Utility;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Collections\Templates;

/**
 * Template Collection Parser Trait
 *
 * Utility that is able to parse an array into a
 * template collection
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Collections\Utility
 */
trait TemplateCollectionParser
{

    /**
     * Parse the given properties list and return a collection
     *
     * @param array $templates
     *
     * @return Templates
     */
    public function parseTemplatesCollection(array $templates = [])
    {
        $ioc = IoC::getInstance();

        return $ioc->make(Templates::class, $templates);
    }
}

Add template collection parser utility

Add template collection parser utility

Needed by multiple Tasks, which is why this deserves its own trait


<?php

namespace duncan3dc\ExceptionsTests;

use duncan3dc\Exceptions\Catcher;

class CatcherTest extends \PHPUnit_Framework_TestCase
{
    private $catcher;

    public function setUp()
    {
        $this->catcher = new Catcher;
    }

    public function testNoExceptions()
    {
        $result = $this->catcher->throw();
        $this->assertNull($result);
    }

    public function testSecondCodeRuns()
    {
        $this->catcher->try(function () {
            throw new \Exception("Fail1");
        });

        $result = false;
        $this->catcher->try(function () use (&$result) {
            $result = true;
        });

        $this->assertTrue($result);

        $this->setExpectedException(\Exception::class, "Fail1");
        $this->catcher->throw();
    }

    public function testGetExceptions()
    {
        $exceptions = [
            new \Exception("Fail1"),
            new \Exception("Fail2"),
        ];

        $this->catcher->try(function () use ($exceptions) {
            throw $exceptions[0];
        });
        $this->catcher->try(function () use ($exceptions) {
            throw $exceptions[1];
        });

        $this->assertSame($exceptions, $this->catcher->getExceptions());

        $this->catcher->clear();
    }

    public function testClear()
    {
        $exception = new \Exception("Nope");

        $this->catcher->try(function () use ($exception) {
            throw $exception;
        });

        $this->assertSame([$exception], $this->catcher->getExceptions());

        $this->catcher->clear();

        $this->assertSame([], $this->catcher->getExceptions());
    }

    public function testMultipleExceptions()
    {
        $this->catcher->try(function () {
            throw new \Exception("Fail1");
        });
        $this->catcher->try(function () {
            throw new \Exception("Fail2");
        });

        $this->expectOutputRegex("/^Exception: Fail1 in /");
        $this->setExpectedException(\Exception::class, "Fail2");
        $this->catcher->throw();
    }

    public function testDestruct()
    {
        $this->catcher->try(function () {
            throw new \Exception("Nope");
        });

        $this->setExpectedException(\Exception::class, "Nope");
        unset($this->catcher);
    }
}

Add some tests for the Catcher class

Add some tests for the Catcher class


<?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 AddEndsAtIndexToMultiplayerRooms extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('multiplayer_rooms', function (Blueprint $table) {
            $table->index('ends_at');
        });
    }

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

Add index for rooms' ends_at column

Add index for rooms' ends_at column


<?php

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

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

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

Make `sponsor_id` nullable on events

Make `sponsor_id` nullable on events [WEB-1173]


<?php

namespace LightSaml\Tests\Tests;

use LightSaml\SamlConstants;

class SamlConstantsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider methodsProvider
     */
    public function test__is_not_valid($method)
    {
        $this->assertFalse(SamlConstants::$method('Nonsense'));
    }

    /**
     * @dataProvider constantsProvider
     */
    public function test__is_valid_method($method, $constant)
    {
        $value = constant('\LightSaml\SamlConstants::' . $constant);
        $this->assertTrue(SamlConstants::$method($value));
    }

    public function methodsProvider()
    {
        return array(
            array('isProtocolValid'),
            array('isNsValid'),
            array('isNameIdFormatValid'),
            array('isBindingValid'),
            array('isStatusValid'),
            array('isConfirmationMethodValid'),
            array('isAuthnContextValid'),
            array('isLogoutReasonValid')
        );
    }

    public function constantsProvider()
    {
        return array_merge(
            $this->getConstants('Protocol'),
            $this->getConstants('Ns'),
            $this->getConstants('NameIdFormat'),
            $this->getConstants('Binding'),
            $this->getConstants('Status'),
            $this->getConstants('ConfirmationMethod'),
            $this->getConstants('AuthnContext'),
            $this->getConstants('LogoutReason')
        );
    }

    public function getConstants($method)
    {
        $ret = array();
        $ref = new \ReflectionClass('\LightSaml\SamlConstants');
        $prefix = strtoupper(
            preg_replace('/([a-z])([A-Z])/', '$1_$2', $method)
        );
        $method = 'is' . $method . 'Valid';

        foreach($ref->getConstants() as $constant => $value) {
            if (strpos($constant, $prefix) === 0) {
                $ret[] = array($method, $constant);
            }
        }

        return $ret;
    }
}

Add unit tests for SamlConstants is...Valid methods


Add a validation class for the form-handler.


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ElasticsearchBundle\Tests\Functional\Mapping;

use ONGR\ElasticsearchBundle\Test\ElasticsearchTestCase;

/**
 * Tests proxy classes.
 */
class ProxyTest extends ElasticsearchTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getDataArray()
    {
        return [
            'default' => [
                'product' => [
                    [
                        '_id' => 1,
                        'title' => 'foo',
                    ],
                ],
            ],
        ];
    }

    /**
     * Tests if documents have initialization flag set.
     */
    public function testIsInitialized()
    {
        $manager = $this->getManager();
        $product = $manager->getRepository('AcmeTestBundle:Product')->find(1);

        $this->assertInstanceOf(
            'ONGR\ElasticsearchBundle\Mapping\Proxy\ProxyInterface',
            $product,
            'Recieved document should be a proxy.'
        );
        $this->assertTrue($product->__isInitialized(), 'Document should have initialized flag set.');
    }
}

Test for proxy isInitialized flag

Test for proxy isInitialized flag


<?php
require('/www/auth/webkit-blog-config.php');

define('WP_CACHE', true); //Added by WP-Cache Manager
define('ABSPATH', dirname(__FILE__).'/');
require_once(ABSPATH.'wp-settings.php');
?>

<?php
require('/var/www/config/webkit-blog-config.php');

define('WP_CACHE', true); //Added by WP-Cache Manager
define('ABSPATH', dirname(__FILE__).'/');
require_once(ABSPATH.'wp-settings.php');
?>

Update website for new hardware.

Update website for new hardware.

git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@123400 bbb929c8-8fbe-4397-9dbb-9b2b20218538


<?php
/**
 * @package Mimic\Functional
 * @since 0.1.0
 * @license MIT
 *
 * @typedef MapCollectionCallback \Closure {
 *     @param mixed $element
 *       Item in the collection.
 *     @param string|int $index
 *       Index of element in the collection.
 *     @param \Traversable|array $collection
 *       Collection. Writes to collection will not do anything.
 *     @return mixed
 * }
 *
 * @typedef ReduceCollectionCallback \Closure {
 *     @param mixed $element
 *       Item in the collection.
 *     @param mixed $current
 *       Current value after modification.
 *     @param string|int $index
 *       Index of element in the collection.
 *     @param \Traversable|array $collection
 *       Collection. Writes to collection will not do anything.
 *     @return mixed
 * }
 */

/** @package Mimic\Functional */
namespace Mimic\Functional;

function compose() {
	/** @todo Incomplete */
}

function pipeline() {

}

Add new file for composing functions. Might add curry functions to this as well.


<?php
namespace Test\Hal\Component\OOP\Resolver;

use Hal\Component\OOP\Resolver\NameResolver;
use PHPUnit_Framework_TestCase as TestCase;

class NameResolverTest extends TestCase
{
    /** @var NameResolver */
    private $resolver;

    protected function setUp()
    {
        $this->resolver = new NameResolver();
    }

    public function testAlreadyNamespacedClassNamesShouldNotBeChanged()
    {
        $this->assertSame('\\foo\\bar', $this->resolver->resolve('\\foo\\bar'));
    }

    public function testAliasedClassesShouldBeResolvedToItsOriginalFQCN()
    {
        $this->resolver->pushAlias((object) array('alias' => 'baz', 'name' => '\\foo\\bar'));
        $this->assertSame('\\foo\\bar', $this->resolver->resolve('baz'));
    }

    public function testUsedClassesShouldBeResolvedToItsOriginalFQCN()
    {
        $this->resolver->pushAlias((object) array('alias' => '\\foo\\bar', 'name' => '\\foo\\bar'));
        $this->assertSame('\\foo\\bar', $this->resolver->resolve('bar'));
    }

    public function testClassesThatAreNotUsedShouldBelongToTheCurrentNamespace()
    {
        $this->assertSame('\\foo\\bar', $this->resolver->resolve('bar', '\\foo'));
        $this->assertSame('\\foo\\bar', $this->resolver->resolve('bar', '\\foo\\'));
        $this->assertSame('\\baz', $this->resolver->resolve('baz'));
    }
}

Add tests for the current nameresolver implementation


<?php

/**
 * BioPHP
 *
 * @category   BioInformatics
 * @package    BioPHP
 * @author     Kenny Pavan  <kenpavan@gmail.com>
 * @license    MIT
 */

class BioPHP {

	public function DnaToRna()
 	{

		return $result;

	}
}

?>

Add a blank class to get started

Add a blank class to get started


<?php

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

class AddAddressAndCommentColumnsToOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->string("comment")->default("");
            $table->integer("addressId")->default(-1);
        });
    }

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

Add address and comment columns to orders table


<?php

declare(strict_types = 1);

namespace unreal4u\TelegramAPI\Telegram\Methods;

use Psr\Log\LoggerInterface;
use unreal4u\TelegramAPI\Abstracts\TelegramMethods;
use unreal4u\TelegramAPI\Abstracts\TelegramTypes;
use unreal4u\TelegramAPI\InternalFunctionality\TelegramRawData;
use unreal4u\TelegramAPI\Telegram\Types\Custom\ResultBoolean;

/**
 * Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such
 * recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can
 * delete any message. If the bot is an administrator in a supergroup, it can delete messages from any other user and
 * service messages about people joining or leaving the group (other types of service messages may only be removed by
 * the group creator). In channels, bots can only remove their own messages. Returns True on success
 *
 * Objects defined as-is May 2017
 *
 * @see GetUpdates
 * @see https://core.telegram.org/bots/api#deletemessage
 */
class DeleteMessage extends TelegramMethods
{
    /**
     * Unique identifier for the target chat or username of the target channel (in the format @channelusername)
     * @var string
     */
    public $chat_id = '';

    /**
     * Identifier of the message to delete
     * @var int
     */
    public $message_id = 0;

    public static function bindToObject(TelegramRawData $data, LoggerInterface $logger): TelegramTypes
    {
        return new ResultBoolean($data->getResultBoolean(), $logger);
    }

    public function getMandatoryFields(): array
    {
        return [
            'chat_id',
            'message_id',
        ];
    }
}

Allow the bot to delete messages

Allow the bot to delete messages


<?php

/**
 * FurryBear
 *
 * PHP Version 5.3
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://github.com/lobostome/FurryBear
 */

namespace FurryBear\Tests\Output\Strategy;

/**
 * Test for XmlToObject output strategy.
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://github.com/lobostome/FurryBear
 */
class XmlToObjectTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test the xml gets converted to an object.
     */
    public function testConvert()
    {
        $data = '<?xml version="1.0"?><root><bill id="abc-113"></bill></root>';

        $output = new \FurryBear\Output\Strategy\XmlToObject();
        $obj = $output->convert($data);

        $this->assertInternalType('object', $obj);
        $this->assertObjectHasAttribute('bill', $obj);
        $this->assertInstanceOf('\SimpleXMLElement', $obj->bill);
    }

    /**
     * Test the invalid json exception.
     */
    public function testInvalidXmlOutput()
    {
        $data = '<?xml version="1.0"?><root<bill id="abc-113"></bill></root>';
        $output = new \FurryBear\Output\Strategy\XmlToObject();

        try {
            $output->convert($data);
        } catch (\FurryBear\Exception\InvalidXmlException $e) {
            $this->setExpectedException('\\FurryBear\\Exception\\InvalidXmlException', 'Invalid xml');
            throw new \FurryBear\Exception\InvalidXmlException('Invalid xml');
        }
    }
}

Add test for XmlToObject output strategy


<?php

namespace Ehann\Tests\RediSearch;

use Ehann\RediSearch\Query\Builder;
use Ehann\RediSearch\Redis\RedisClient;
use Ehann\Tests\Stubs\TestIndex;
use PHPUnit\Framework\TestCase;

class BuilderTest extends TestCase
{
    private $indexName;
    /** @var Builder */
    private $subject;
    /** @var RedisClient */
    private $redisClient;

    public function setUp()
    {
        $this->indexName = 'QueryBuilderTest';
        $this->redisClient = new RedisClient(
            \Redis::class,
            getenv('REDIS_HOST') ?? '127.0.0.1',
            getenv('REDIS_PORT') ?? 6379,
            getenv('REDIS_DB') ?? 0
        );
        $index = (new TestIndex($this->redisClient, $this->indexName))
            ->addTextField('title')
            ->addTextField('author')
            ->addNumericField('price')
            ->addNumericField('stock');
        $index->create();
        $index->makeDocument();
        $index->add([
            'title' => 'How to be awesome.',
            'author' => 'Jack',
            'price' => 9.99,
            'stock' => 231,
        ]);
        $index->add([
            'title' => 'Shoes in the 22st Century',
            'author' => 'Jessica',
            'price' => 18.85,
            'stock' => 32,
        ]);
        $this->subject = (new Builder($this->redisClient, $this->indexName));
    }

    public function tearDown()
    {
        $this->redisClient->flushAll();
    }

    public function testSearch()
    {
        $result = $this->subject->search('awesome');

        $this->assertTrue($result->getCount() === 1);
    }

    public function testSearchWithScores()
    {
        $result = $this->subject->withScores()->search('awesome');

        $this->assertTrue($result->getCount() === 1);
    }
}

Add query builder test class

Add query builder test class


<?php

/**
 * ディスプレイのテンプレート
 *
 * 拡張されたサブクラスに指定されたメソッドの実装を強制する
 *
 * @access public
 * @author ku2ma2 <motorohi.tsumaniku@gmail.com>
 * @copyright ku2ma2
 */
abstract class AbstractDisplay
{
    abstract public function open();
    abstract public function print();
    abstract public function close();

    // Common method
    public function display()
    {
        // TODO: 5回繰り返す
    }
}

Add abstract class for display

Add abstract class for display


<?php

use Phinx\Migration\AbstractMigration;

class AdjustShowUniqueKey extends AbstractMigration {
  public function up() {
    $this->table('show')
      ->removeIndex(['season', 'episode'])
      ->addIndex(['season', 'episode', 'generation'], ['unique' => true])
      ->update();
  }

  public function down() {
    $this->table('show')
      ->removeIndex(['season', 'episode', 'generation'])
      ->addIndex(['season', 'episode'], ['unique' => true])
      ->update();
  }
}

Adjust the unique key on the show table to account for generations


<?php

return [

    'regular' => '定時',
    'extra' => '随時',
    'eqvol' => '地震火山',
    'other' => 'その他',

];

Add japanese language for feed types

Add japanese language for feed types


<?php

/**
 * @author Petr Pliska <petr.pliska@post.cz>
 */

namespace App\Shared\Behaviour\Common;

use DI\Container;

trait DiContainerTrait
{
    /**
     * @var Container
     */
    protected $diContainer;

    public function setDiContainer(Container $diContainer)
    {
        $this->diContainer = $diContainer;
    }
}

Add trait for DI container

Add trait for DI container


<?php
namespace Concrete\Core\Application;

/**
 * Interface ApplicationAwareInterface
 * This interface declares awareness of the concrete5 application.
 *
 * @package Concrete\Core\Application
 */
interface ApplicationAwareInterface
{
    /**
     * Set the application object
     *
     * @param \Concrete\Core\Application\Application $application
     */
    public function setApplication(Application $application);
}

Add an interface that declares awareness of the application instance

Former-commit-id: 690e1dbf2c2dd460e81e5cef151c5458242c60a1
Former-commit-id: 3509727bbd266ddf1796c40060c3349c6d19c1a5


<?php

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

class ChangeValueColumnInSettingsTableToText extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('settings', function (Blueprint $table)
        {
            $table->text('value')->nullable()->change();
        });
    }

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

Add migration to change value column to text


<?php
/*
 * @package    klout-sdk-php
 * @author     Mike Tougeron <github+klout-sdk-php@tougeron.com>
 * @copyright  Copyright (c) 2013 Mike Tougeron <github+klout-sdk-php@tougeron.com>
 * @license    http://opensource.org/licenses/MIT
 * @link       https://github.com/mtougeron/klout-sdk-php
 */

namespace Klout\Exception;

class LogicException extends \LogicException implements KloutException {}

Add a new exception type

Add a new exception type


<?php
namespace Swarrot\Processor\RPC;

use Psr\Log\LoggerInterface;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Swarrot\Broker\Message;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\Processor\ConfigurableInterface;
use Swarrot\Processor\SleepyInterface;

/**
 * Act as a RPC client that waits for a certain message to terminate
 *
 * This processor is a leaf processor ; other processors cannot be nested under
 * this processor.
 *
 * It waits for a certain message (with a proper `correlation_id`) to tell the
 * consumer that the message was processed, and that the consumer should be
 * killed afterwards.
 *
 * @author Baptiste Clavié <clavie.b@gmail.com>
 */
class RpcClientProcessor implements ProcessorInterface, ConfigurableInterface, SleepyInterface
{
    /** @var LoggerInterface */
    private $logger;

    /** @var ProcessorInterface */
    private $processor;

    /** @var boolean */
    private $awoken = false;

    public function __construct(ProcessorInterface $processor = null, LoggerInterface $logger = null)
    {
        $this->processor = $processor;
        $this->logger = $logger;
    }

    /** {@inheritDoc} */
    public function process(Message $message, array $options)
    {
        $properties = $message->getProperties();

        // check for invalid correlation_id properties (not set, or invalid)
        if (!isset($properties['correlation_id'])) {
            return;
        }

        if ($properties['correlation_id'] !== $options['rpc_client_correlation_id']) {
            return;
        }

        $result = null;

        $this->logger and $this->logger->info('Message received from the RPC Server ; terminating consumer', ['correlation_id' => $properties['correlation_id']]);
        $this->awoken = true;

        if (null !== $this->processor) {
            $this->logger and $this->logger->info('Sending message to sub-processor');
            $result = $this->processor->process($message, $options);
        }

        return $result;
    }

    /** {@inheritDoc} */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(['rpc_client_correlation_id']);
    }

    /** {@inheritDoc} */
    public function sleep(array $options)
    {
        return !$this->awoken;
    }
}

Add a RPC Client Processor

[RPC] Add a RPC Client Processor


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Membuat relation pada database
 */
class Migration_expandcitizen extends CI_Migration {

    public function up() {
        $this->db->query("ALTER TABLE `citizens` DROP `data`;");
        $this->db->query("ALTER TABLE `citizens` ADD `provinsi` VARCHAR(256) NOT NULL , ADD `kotakabupaten` VARCHAR(256) NOT NULL , ADD `nama` VARCHAR(256) NOT NULL , ADD `tempatlahir` VARCHAR(128) NOT NULL , ADD `tanggallahir` DATE NULL , ADD `jeniskelamin` VARCHAR(64) NOT NULL , ADD `goldarah` VARCHAR(32) NOT NULL , ADD `alamat` VARCHAR(256) NOT NULL , ADD `rt` VARCHAR(16) NOT NULL , ADD `rw` VARCHAR(16) NOT NULL , ADD `desakel` VARCHAR(64) NOT NULL , ADD `kecamatan` VARCHAR(64) NOT NULL , ADD `agama` VARCHAR(64) NOT NULL , ADD `pekerjaan` VARCHAR(64) NOT NULL , ADD `kewarganegaraan` VARCHAR(64) NOT NULL ;");
        $this->db->query("INSERT INTO `ktprame`.`citizens` (`nik`, `provinsi`, `kotakabupaten`, `nama`, `tempatlahir`, `tanggallahir`, `jeniskelamin`, `goldarah`, `alamat`, `rt`, `rw`, `desakel`, `kecamatan`, `agama`, `pekerjaan`, `kewarganegaraan`) VALUES ('3461607886316458', 'JAWA BARAT', 'KOTA BANDUNG', 'KURUKUTAFUTO', 'JAKARTA', '1984-12-01', 'PEREMPUAN', 'A+', '3558 VIKING DRIVE', '008', '004', 'PUNGKUR', 'REGOL', 'KATHOLIK', 'PELUKIS', 'WNI');");
    }

}

Expand citizen table fields and one example data


<?php

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

class CreateArticleViewsSnapshotsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_views_snapshots', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamp('time');
            $table->string('property_token');
            $table->integer('article_id')->unsigned();
            $table->string('derived_referer_medium')->nullable();
            $table->string('explicit_referer_medium')->nullable();
            $table->integer('count')->unsigned();

            $table->foreign('article_id')->references('id')->on('articles');
            $table->index('time');
        });
    }

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

Create table for article views snapshots

remp/remp#442