<?php
/**
 * Test case for the PermissionEntity class
 * Date: 8/10/16
 * Time: 16:33
 * @copyright Marcos Zuriaga Miguel 2016
 * @license AGPLv3
 */
use \OCA\Passman\Utility\PermissionEntity;

class PermissionsEntityTest extends PHPUnit_Framework_TestCase {
	/**
	 * @var PermissionEntity
	 */
	protected $permission;

	public function setUp() {
		$this->permission = new PermissionEntity();
		$this->permission->permissions = 0;
	}

	public function testPermissionConstants(){
		$this->assertTrue(PermissionEntity::READ    === 0b00000001);
		$this->assertTrue(PermissionEntity::WRITE   === 0b00000010);
		$this->assertTrue(PermissionEntity::FILES   === 0b00000100);
		$this->assertTrue(PermissionEntity::HISTORY === 0b00001000);
		$this->assertTrue(PermissionEntity::OWNER   === 0b10000000);
	}

	public function testAddPermission(){
		// Start with an empty permission
		$this->permission->setPermissions(0);
		$this->assertTrue($this->permission->getPermissions() === 0);

		// Add read permission
		$this->permission->addPermission(PermissionEntity::READ);
		$this->assertTrue($this->permission->getPermissions() === PermissionEntity::READ);

		// Try adding another permission and check if it has both
		$this->permission->addPermission(PermissionEntity::FILES);
		$this->assertTrue($this->permission->getPermissions() === (PermissionEntity::READ | PermissionEntity::FILES));
	}

	public function testRemovePermission(){
		$base_permissions = PermissionEntity::READ | PermissionEntity::WRITE | PermissionEntity::HISTORY;

		// Start with a set of permissions
		$this->permission->setPermissions($base_permissions);
		$this->assertTrue($this->permission->getPermissions() === $base_permissions);

		// Remove write permission
		$expected_permissions = PermissionEntity::READ | PermissionEntity::HISTORY;
		$this->permission->removePermission(PermissionEntity::WRITE);
		$this->assertTrue($this->permission->getPermissions() === $expected_permissions);

		// Remove history permission
		$expected_permissions = PermissionEntity::READ;
		$this->permission->removePermission(PermissionEntity::HISTORY);
		$this->assertTrue($this->permission->getPermissions() === $expected_permissions);
	}

	public function testHasPermission() {
		$base_permissions = PermissionEntity::READ | PermissionEntity::WRITE | PermissionEntity::HISTORY;

		// Start with a set of permissions
		$this->permission->setPermissions($base_permissions);
		$this->assertTrue($this->permission->getPermissions() === $base_permissions);

		// Test some conditions
		$this->assertFalse($this->permission->hasPermission(PermissionEntity::OWNER));
		$this->assertTrue($this->permission->hasPermission(PermissionEntity::READ));
		$this->assertTrue($this->permission->hasPermission(PermissionEntity::HISTORY));
	}
}

Add permissions entity backend uint tests


<?php
class Infusionsoft_FileServiceBase extends Infusionsoft_Service{

    public static function getFile($fileId, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId
        );

        return parent::send($app, "FileService.getFile", $params);
    }

    public static function getDownloadUrl($fileId, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId
        );

        return parent::send($app, "FileService.getDownloadUrl", $params);
    }

    public static function uploadFile($contactId, $fileName, $base64encoded, Infusionsoft_App $app = null){
        $params = array(
            (int) $contactId,
            $fileName,
            $base64encoded
        );

        return parent::send($app, "FileService.uploadFile", $params);
    }

    public static function replaceFile($fileId, $base64encoded, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId,
            $base64encoded
        );

        return parent::send($app, "FileService.replaceFile", $params);
    }

    public static function renameFile($fileId, $fileName, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId,
            $fileName
        );

        return parent::send($app, "FileService.renameFile", $params);
    }

}

<?php
class Infusionsoft_FileServiceBase extends Infusionsoft_Service{

    public static function getFile($fileId, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId
        );

        return parent::send($app, "FileService.getFile", $params);
    }

    public static function getDownloadUrl($fileId, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId
        );

        return parent::send($app, "FileService.getDownloadUrl", $params);
    }

    public static function uploadFile($contactId, $fileName, $base64encoded, Infusionsoft_App $app = null){
        // If contactId is null, do not include it in the params
        if ($contactId === null) {
            $params = array(
                $fileName,
                $base64encoded
            );
        } else {
            $params = array(
                (int) $contactId,
                $fileName,
                $base64encoded
            );
        }

        return parent::send($app, "FileService.uploadFile", $params);
    }

    public static function replaceFile($fileId, $base64encoded, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId,
            $base64encoded
        );

        return parent::send($app, "FileService.replaceFile", $params);
    }

    public static function renameFile($fileId, $fileName, Infusionsoft_App $app = null){
        $params = array(
            (int) $fileId,
            $fileName
        );

        return parent::send($app, "FileService.renameFile", $params);
    }

}

Make it possible to upload files to Company Images


<?php
/**
 * Config class
 * Configuration for Skeleton\Object
 *
 * @author David Vandemaele <david@tigron.be>
 */

namespace Skeleton\Object;

class Config {

	/**
	 * Auto update the slug
	 *
	 * This flag will be used to allow auto updating the slug
	 *
	 * @access public
	 * @var bool $auto_update_slug
	 */
	public static $auto_update_slug = false;

}

Add config setting to allow auto update of slug


<?php

namespace spec\App\Http\Handlers;

use App\Http\Handlers\BackToWebsite;
use Illuminate\Container\Container;
use Orchestra\Contracts\Foundation\Foundation;
use Orchestra\Widget\Handlers\Menu;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class BackToWebsiteSpec extends ObjectBehavior
{
    function let(Container $app)
    {
        $this->beConstructedWith($app);
    }

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

    function it_can_be_display_when_is_installed(Container $app, Foundation $foundation, Menu $menu)
    {
        $app->offsetGet('orchestra.app')->willReturn($foundation);
        $app->make('orchestra.platform.menu')->willReturn($menu);

        $foundation->installed()->willReturn(true);

        $this->authorize()->shouldReturn(true);
    }

    function it_cant_be_display_when_is_not_installed(Container $app, Foundation $foundation, Menu $menu)
    {
        $app->offsetGet('orchestra.app')->willReturn($foundation);
        $app->make('orchestra.platform.menu')->willReturn($menu);

        $foundation->installed()->willReturn(false);

        $this->authorize()->shouldReturn(false);
    }
}

Add back to website spec.

Add back to website spec.

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


<?php

namespace OpenCFP\Test\Domain\Services;

use OpenCFP\Domain\Services\Pagination;
use OpenCFP\Test\BaseTestCase;
use Pagerfanta\Pagerfanta;

class PaginationTest extends BaseTestCase
{
    /**
     * @var Pagination
     */
    private $pagination;
    public function setUp()
    {
        parent::setUp();
        $this->pagination = new Pagination([1,2,3,4,5,6,7,8,9,10],2);
    }

    /**
     * @test
     */
    public function currentPageGetterAndSetterWork()
    {
        $this->pagination->setCurrentPage(null);
        $this->assertSame(1, $this->pagination->getCurrentPage());
        $this->pagination->setCurrentPage('');
        $this->assertSame(1, $this->pagination->getCurrentPage());
        $this->pagination->setCurrentPage(2);
        $this->assertSame(2, $this->pagination->getCurrentPage());
    }

    /**
     * @test
     */
    public function getFantaWorks()
    {
        $this->assertInstanceOf(Pagerfanta::class, $this->pagination->getFanta());
    }

    /**
     * @test
     */
    public function createViewWorks()
    {
        $view = $this->pagination->createView('/help/example?');
        $this->assertContains('/help/example?', $view);
        $this->assertContains('page=2', $view);

        $otherView = $this->pagination->createView('/help/example?',['filter' => 'bam']);
        $this->assertContains('/help/example?', $otherView);
        $this->assertContains('page=2', $otherView);
        $this->assertContains('filter=bam', $otherView);

    }

}

Add a test for pagination

Add a test for pagination

This class didn't have its own tests yet, and all coverage of it was
from the controller tests.


<?php

use App\User;
use App\Company;

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class CompanyDeleteTest extends TestCase
{
	use DatabaseTransactions;

    public function test_users_can_delete_a_company()
    {
        $user = factory(User::class, 'admin')->create();

        $user->companies()->save($companyOne = factory(Company::class)->create());
        $user->companies()->save($companyTwo = factory(Company::class)->create());

        $this->actingAs($user)
             ->visit('/companies')
             ->see($companyOne->name)
             ->see($companyTwo->name)
             ->press('delete-company-'.$companyOne->id)
             ->dontSeeInDatabase('companies', ['name' => $companyOne->name])
             ->dontSee($companyOne->name)
             ->see($companyTwo->name);
    }

    public function test_users_can_delete_companies_of_other_users()
    {
        // $this->withoutMiddleware();

        $userOne = factory(User::class, 'admin')->create();
        $userTwo = factory(User::class, 'admin')->create();

        $userOne->companies()->save($companyOne = factory(Company::class)->create());
        $userTwo->companies()->save($companyTwo = factory(Company::class)->create());

        $this->actingAs($userOne)
             ->visit('/companies')
             ->see($companyOne->name)
             ->see($companyTwo->name)
             ->press('delete-company-'.$companyOne->id)
             ->press('delete-company-'.$companyTwo->id)
             ->dontSeeInDatabase('companies', ['name' => $companyOne->name])
             ->dontSeeInDatabase('companies', ['name' => $companyTwo->name])
             ->dontSee($companyOne->name)
             ->dontSee($companyTwo->name);

        //  REST =>> $this->delete('/company/'.$companyTwo->id)->assertResponseStatus(200);
    }

}

Add test for Delete Company Form

Add test for Delete Company Form

- company can be deleted by admin
- admin can delete company that is created by other user


<?php

namespace PhpAbac\Loader;

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Yaml\Yaml;

class YamlAbacLoader extends FileLoader
{
    public function load($resource, $type = null)
    {
        return Yaml::parse(file_get_contents($resource));
    }

    public function supports($resource, $type = null)
    {
        return is_string($resource) && 'yml' === pathinfo(
            $resource,
            PATHINFO_EXTENSION
        );
    }
}

Implement yaml loader for the configuration file


<?php
namespace ComplexPie\Atom10\Content;

class Person
{
    protected $node;

    protected $name;
    protected $uri;
    protected $email;

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

        $names = \ComplexPie\Misc::xpath($node, 'atom:name', array('atom' => XMLNS));
        if ($names->length)
        {
            $this->name = \ComplexPie\Content::from_textcontent($names->item(0));
        }

        $uris = \ComplexPie\Misc::xpath($node, 'atom:name', array('atom' => XMLNS));
        if ($uris->length)
        {
            $this->uri = new \ComplexPie\Content\IRINode($uris->item(0));
        }

        $emails = \ComplexPie\Misc::xpath($node, 'atom:email', array('atom' => XMLNS));
        if ($emails->length)
        {
            $this->email = \ComplexPie\Content::from_textcontent($emails->item(0));
        }
    }

    public function __get($name)
    {
        if (
            $name === 'name' ||
            $name === 'uri' ||
            $name === 'email'
        )
        {
            return $this->$name;
        }
    }
}

Add class for Atom Person Constructs.

Add class for Atom Person Constructs.


<?php
use Galahad\LaravelAddressing\Country;
use Galahad\LaravelAddressing\CountryCollection;

/**
 * Class CountryCollectionTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class CountryCollectionTest extends PHPUnit_Framework_TestCase
{
    public function testCountryCollectionClass()
    {
        $collection = new CountryCollection();
        $country = new Country;
        $countries = ['Brazil', 'United States', 'Argentina', 'Canada', 'Chile'];
        foreach ($countries as $countryName) {
            $collection->insert($country->findByName($countryName));
        }
        /** @var Country $country */
        foreach ($collection as $key => $country) {
            $this->assertEquals($country->getName(), $countries[$key]);
        }
    }
}

Test method for country collections

Test method for country collections


<?php

if ($argc !=2) {
    throw new DomainException('Please provide a threshold parameter to measure TTLs of redis keys');
}

$threshold = (int) $argv[1];
if ($threshold < 1) {
    throw new DomainException('Threshold parameter must be a stricly positive integer');
}

$redis = new Redis();
$redis->connect('127.0.0.1:6379');

$keys = $redis->keys('md*');

$data = array();

foreach($keys as $key) {
    $metadata = unserialize($redis->get($key));

    $dateString = $metadata[0][1]['date'][0];
    $date = new Datetime($dateString);

    $currentTime =  time() - $date->format('U');
    $data[$currentTime] []= "$currentTime\t$dateString\t$key :\t" . $metadata[0][1]['cache-control'][0] . "\n";
}

ksort($data, SORT_NUMERIC);
foreach($data as $ts => $elem) {
    foreach($elem as $key => $val){
        $side = $ts>$threshold ? '>': '';
        echo "$side\t$key : \t$val";
    }
}

Add a script to follow easily the cache entries


<?php

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

namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Tests\EventHandling;

use Broadway\Domain\DomainEventStream;
use Broadway\Domain\DomainMessage;
use Broadway\EventHandling\EventListenerInterface;
use Surfnet\StepupMiddleware\CommandHandlingBundle\EventHandling\BufferedEventBus;

class RecordEventsAndPublishToBusOnFirstCallEventListener implements EventListenerInterface
{
    /**
     * @var integer
     */
    private $callCount = 0;

    /**
     * @var BufferedEventBus
     */
    private $eventBus;

    /**
     * @var DomainEventStream
     */
    private $toPublish;

    /**
     * @var DomainMessage[]
     */
    private $recordedEvents = [];

    /**
     * @param BufferedEventBus $eventBus
     * @param DomainEventStream $toPublish
     */
    public function __construct(BufferedEventBus $eventBus, DomainEventStream $toPublish)
    {
        $this->eventBus  = $eventBus;
        $this->toPublish = $toPublish;
    }

    /**
     * @param DomainMessage $domainMessage
     */
    public function handle(DomainMessage $domainMessage)
    {
        $this->recordedEvents[] = $domainMessage;

        if ($this->callCount === 0) {
            $this->eventBus->publish($this->toPublish);
            $this->callCount = 1;
        }
    }

    /**
     * @return DomainMessage[]
     */
    public function getRecordedEvents()
    {
        return $this->recordedEvents;
    }
}

Introduce event listener to test nested events in buffered event bus


	Downtown
	East Side
	Hillyard
	Indian Trail
	Shadle
	South Hill

	STA Plaza
	East Side
	Hillyard
	Indian Trail
	South Hill
	Downtown
	Shadle

Add STA Plaza to meeting room jump list

Add STA Plaza to meeting room jump list


<?php

use yii\db\Migration;

/**
 * Handles the creation for table `table_test`.
 */
class m160529_025942_create_table_test extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->createTable('table_test', [
            'id' => $this->primaryKey(),
        ]);
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropTable('table_test');
    }
}

Create an example migration class

Create an example migration class


<?php

require_once("sso_api.php");

class AnimeKitaHooks {

	public static function onUserLoadFromSession($user, &$result) {

		$si_sso = new SelvbetjeningIntegrationSSO("wiki");

		try {
			$authenticated = $si_sso->is_authenticated();
		} catch (Exception $e) {
			return false;
		}

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

		$username = ucwords($authenticated);

		$dbr =& wfGetDB( DB_SLAVE );
        $s = $dbr->selectRow('user', array('user_id'), array('user_name' => $username));

		if ($s === false) {
			// User not in database, add her

			try {
				$user_info = $si_sso->get_session_info();
			} catch (Exception $e) {
				return true;
			}

			$u = new User();
			$u->loadDefaults($username);
			$u->addToDatabase();

			$u->mEmail = $user_info['email'];
			$u->mName = $username;
			$u->mRealName = $user_info['first_name'] . " " . $user_info['last_name'];
			$u->mEmailAuthenticated = wfTimestamp();
            $u->mTouched = wfTimestamp();
            $u->saveSettings();

		} else {
			$user->mId = $s->user_id;
		}

		$user->loadFromDatabase();
		$user->saveToCache();

        $result = 1;
        return false;

	}

}

Add mediawiki integration to Selvbetjening


<?php
/* This is a list of packages and versions
 * that will be used to create the PEAR folder
 * in the windows snapshot.
 * See win32/build/mkdist.php for more details
 * $Id$
 */
$packages  = array(
"PEAR"					=>	"1.3b6",
"Mail"					=>	"1.1.2",
"Net_SMTP"				=>	"1.2.2",
"Net_Socket"			=>	"1.0.1",
"PHPUnit"				=>	"1.0.0alpha3",
"Console_Getopt"		=>	"1.2",
"DB"					=>	"1.6.0RC6",
"HTTP"					=>	"1.2.2",
"Archive_Tar"			=>	"1.1",
"Pager"					=>	"1.0.8",
"HTML_Template_IT"		=>	"1.1",
"XML_Parser"			=>	"1.0.1",
"XML_RPC"				=>	"1.0.4",
"Net_UserAgent_Detect"	=>	"1.0",
"PEAR_Frontend_Web"		=>	"0.1"
);

?>

Add this list here, so that pear-core guys can manipulate the PEAR bundle
for the win32 snapshot.

git-svn-id: 4b064e69dc630d28214c1e1442d27300cccf8e9a@155547 c90b9560-bf6c-de11-be94-00142212c4b1


<?php

namespace Bolt\Composer\Action;

use Bolt\Composer\PackageManager;

use Composer\Factory;
use Composer\Repository\CompositeRepository;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;

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

    /**
     * Search for packages
     *
     * @param  $packages array Indexed array of package names to search for
     * @return array List of matching packages
     */
    public function execute($packages)
    {
        $platformRepo = new PlatformRepository();

        if ($this->composer) {
            $localRepo = $this->composer->getRepositoryManager()->getLocalRepository();
            $installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
            $repos = new CompositeRepository(array_merge(array($installedRepo), $this->composer->getRepositoryManager()->getRepositories()));
        } else {
            $defaultRepos = Factory::createDefaultRepositories($this->io);

            //No composer.json found in the current directory, showing packages from local repo
            $installedRepo = $platformRepo;
            $repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
        }

        $flags = $this->onlyname ? RepositoryInterface::SEARCH_NAME : RepositoryInterface::SEARCH_FULLTEXT;

        return $repos->search(implode(' ', $packages), $flags);
    }
}

Add Composer class to search for package(s) by name


<?php

class TopController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function getIndex()
	{
        $memes = Meme::all();

        //Get all memes that have more than 10 votes
        foreach($memes as $meme){
            if($meme->codes()->whereNotNull('vote')->count() > 10){
                $stats[$meme->id] = [
                    'meme_id' => $meme->id,
                    'like_percentage' => $meme->codes()->where('vote', '=', '1')->count() / $meme->codes()->whereNotNull('vote')->count(),
                ];
            }
        }

        //Sort them by approval percentage
        usort($stats, function($a, $b) {
            return $b['like_percentage'] > $a['like_percentage'] ? 1 : -1;
        });

        //Get 10 top memes
        $stats = array_slice($stats, 0, 10);

        $top10Memes = [];

        foreach($stats as $top10Meme){
            $top10Memes[] = Meme::whereId($top10Meme['meme_id'])->first();
        }

        //Counter of memes
        $i=1;
        return View::make('topmemes')->with('memes', $top10Memes)->with('i', $i);
	}

}

Add top memes display controller

Add top memes display controller


<?php

namespace spec\RulerZ\Executor;

use Elasticsearch\Client;
use PhpSpec\ObjectBehavior;

use RulerZ\Executor\Executor;

class ElasticsearchExecutorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('RulerZ\Executor\ElasticsearchExecutor');
    }

    function it_supports_satisfies_mode(Client $client)
    {
        $this->supports($client, Executor::MODE_SATISFIES)->shouldReturn(true);
    }

    function it_can_filter_using_a_client(Client $client)
    {
        $this->supports($client, Executor::MODE_FILTER)->shouldReturn(true);
    }

    function it_can_not_filter_other_types()
    {
        foreach ($this->unsupportedTypes() as $type) {
            $this->supports($type, Executor::MODE_FILTER)->shouldReturn(false);
        }
    }

    function it_can_filter_a_client_with_a_rule(Client $client)
    {
        $expectedQuery = [
            'bool' => [
                'must' => [
                    'range' => ['points' => ['gt' => 30]],
                ]
            ]
        ];

        $client->search([
            'index' => 'es_index',
            'type'  => 'es_type',
            'body'  => ['query' => $expectedQuery],
        ])->willReturn('result');

        $this->filter($client, $this->getSimpleRule(), [
            'index' => 'es_index',
            'type'  => 'es_type',
        ])->shouldReturn('result');
    }

    private function unsupportedTypes()
    {
        return [
            'string',
            42,
            new \stdClass,
            [],
        ];
    }

    private function getSimpleRule()
    {
        // serialized rule for "points > 30"
        $rule = 'O:21:"Hoa\\Ruler\\Model\\Model":1:{s:8:"' . "\0" . '*' . "\0" . '_root";O:24:"Hoa\\Ruler\\Model\\Operator":3:{s:8:"' . "\0" . '*' . "\0" . '_name";s:1:">";s:13:"' . "\0" . '*' . "\0" . '_arguments";a:2:{i:0;O:27:"Hoa\\Ruler\\Model\\Bag\\Context":2:{s:6:"' . "\0" . '*' . "\0" . '_id";s:6:"points";s:14:"' . "\0" . '*' . "\0" . '_dimensions";a:0:{}}i:1;O:26:"Hoa\\Ruler\\Model\\Bag\\Scalar":1:{s:9:"' . "\0" . '*' . "\0" . '_value";i:30;}}s:12:"' . "\0" . '*' . "\0" . '_function";b:0;}}';

        return unserialize($rule);
    }
}

Write specs for the ElasticsearchExecutor


<?php namespace App\Http\Controllers;

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

use Illuminate\Http\Request;

class NotesController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

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

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

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

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

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

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

}

Add the notes controller to define the CRUD action.


<?php

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

class AddProcessingFeeToPayments extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('payments', function (Blueprint $table) {
            $table->decimal('processing_fee')->after('amount')->nullable();
        });
    }

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

Create migration to add processing_fee column to payments table


<?php

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

class DropVirtualColumnsUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('name');
            $table->dropColumn('full_name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('name')
                ->virtualAs("concat_ws(' ',`first_name`,`last_name`)")->nullable()->after('preferred_name');
            $table->string('full_name')
                ->virtualAs("concat_ws(' ',`first_name`,`middle_name`,`last_name`)")->after('preferred_name');
        });
    }
}

Add migration to drop the virtual columns from the DB


<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class Release extends BaseCommand
{

    protected $signature = 'release {version : Version number to set}';

    protected $description = 'Bump the version number and run some small tasks';

    public function handle()
    {
        $this->info('Bumping version number...');
        $this->bumpVersionNumber();

        $this->info('Downloading CSS and JS...');
        $this->call('docs:download-css-js');

        $this->info('Creating endpoints docs...');
        $this->call('docs:endpoints');

        $this->info('Creating fields docs...');
        $this->call('docs:fields');

        $this->info('Creating swagger docs...');
        $this->call('docs:swagger');

    }

    private function bumpVersionNumber() {
        $version = $this->argument('version');

        Storage::disk('local')->put('VERSION', $version);

        $dest = base_path('VERSION');

        copy(storage_path('app/VERSION'), $dest);
    }
}

Add 'release' artisan command that bumps version number and generates docs [WEB-1807]


<?php

namespace Ivory\GoogleMapBundle\Templating\Helper;

/**
 * Map type ID helper
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class MapTypeIdHelper
{
    /**
     * Renders javascript map map type ID
     *
     * @param string $mapTypeId Map type ID
     * @return string HTML output
     */
    public function render($mapTypeId)
    {
        switch($mapTypeId)
        {
            case 'hybrid':
                return 'google.maps.MapTypeId.HYBRID';
            break;

            case 'roadmap':
                return 'google.maps.MapTypeId.ROADMAP';
            break;

            case 'satellite':
                return 'google.maps.MapTypeId.SATELLITE';
            break;

            case 'terrain':
                return 'google.maps.MapTypeId.TERRAIN';
            break;

            default:
                throw new \InvalidArgumentException('The map type id is not valid.');
            break;
        }
    }
}

Create map type id helper

Create map type id helper


<?php

/*
 * This file is part of the easypay-php package.
 *
 * (c) Samuel Gordalina <https://github.com/gordalina/easypay-php>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gordalina\Easypay\Response;

abstract class AbstractResponse
{
    /**
     * @param  array  $input
     * @param  array  $scheme
     * @return null
     */
    protected function parse(array $input, array $scheme)
    {
        foreach ($scheme as $key => $value) {
            if (!isset($input[$key])) {
                continue;
            }

            if (is_array($value)) {
                list($property, $processor) = $value;
                $this->{$property} = $processor($input[$key]);
            } else {
                $this->{$value} = $input[$key];
            }
        }
    }
}

Add parse function for optional fields to avoid accessing non existent properties


<?php namespace Prezly\DraftPhp\Tests\Model;

use InvalidArgumentException;
use PHPUnit_Framework_TestCase;
use Prezly\DraftPhp\Constants\BlockType;
use Prezly\DraftPhp\Model\CharacterMetadata;
use Prezly\DraftPhp\Model\ContentBlock;

class ContentBlockTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_should_construct_empty_text_instances()
    {
        $block = new ContentBlock('0', BlockType::UNSTYLED, '', [], 0);

        $this->assertEquals('', $block->text);
        $this->assertEquals([], $block->characterList);
    }

    /**
     * @test
     */
    public function it_should_construct_non_empty_text_instances()
    {
        $text = 'Hello';
        $chars = array_pad([], mb_strlen($text), CharacterMetadata::create([]));

        $block = new ContentBlock('0', BlockType::UNSTYLED, $text, $chars, 0);

        $this->assertEquals($text, $block->text);
        $this->assertEquals($chars, $block->characterList);
    }

    /**
     * @test
     */
    public function it_should_throw_if_invalid_character_list_array_given()
    {
        $this->expectException(InvalidArgumentException::class);
        new ContentBlock('0', BlockType::UNSTYLED, '?', ['Not a CharacterMetadata'], 0);
    }

    /**
     * @test
     */
    public function it_should_throw_if_text_length_not_matching_character_list_length()
    {
        $this->expectException(InvalidArgumentException::class);
        new ContentBlock('0', BlockType::UNSTYLED, '?', [/* should have 1 CharacterMetadata item */], 0);
    }
}

Implement tests for ContentBlock model class


<?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Section for featured users
 *
 * PHP version 5
 *
 * LICENCE: This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Widget
 * @package   Laconica
 * @author    Evan Prodromou <evan@controlyourself.ca>
 * @copyright 2009 Control Yourself, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://laconi.ca/
 */

if (!defined('LACONICA')) {
    exit(1);
}

/**
 * Section for featured users
 *
 * @category Widget
 * @package  Laconica
 * @author   Evan Prodromou <evan@controlyourself.ca>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://laconi.ca/
 */

class FeaturedUsersSection extends ProfileSection
{
    function getProfiles()
    {
        $featured_nicks = common_config('nickname', 'featured');

        if (!$featured_nicks) {
            return null;
        }

        $quoted = array();

        foreach ($featured_nicks as $nick) {
            $quoted[] = "'$nick'";
        }

        $qry = 'SELECT profile.* ' .
          'FROM profile JOIN user on profile.id = user.id ' .
          'WHERE user.nickname in (' . implode(',', $quoted) . ') ' .
          'ORDER BY profile.created DESC ';

        $limit = PROFILES_PER_SECTION + 1;
        $offset = 0;

        if (common_config('db','type') == 'pgsql') {
            $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        } else {
            $qry .= ' LIMIT ' . $offset . ', ' . $limit;
        }

        $profile = Memcached_DataObject::cachedQuery('Profile',
                                                     $qry,
                                                     6 * 3600);
        return $profile;
    }

    function title()
    {
        return _('Featured users');
    }

    function divId()
    {
        return 'featured_users';
    }
}

Add a featured user section

Add a featured user section


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

namespace Zend\ServiceManager\Factory;

use Interop\Container\ContainerInterface;

/**
 * Factory to create newable classes
 */
final class InvokableFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = [])
    {
        return new $requestedName($options);
    }
}

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

namespace Zend\ServiceManager\Factory;

use Interop\Container\ContainerInterface;

/**
 * Factory to create newable classes
 */
final class InvokableFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new $requestedName($options);
    }
}

Use null as default value for $options

Use null as default value for $options

- FactoryInterface does this already; InvokableFactory should as well.


<?php
// Check if we are a user
OCP\JSON::checkLoggedIn();

// Set the session key for the file we are about to edit.
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$filename = isset($_GET['file']) ? $_GET['file'] : '';
if(!empty($filename))
{
	$path = $dir.'/'.$filename;
	$maxsize = \OCP\Config::getSystemValue("max_size_root_file", 4194304); // default of 4MB
	$size = \OC\Files\Filesystem::filesize($path);
	if($size > $maxsize) {
		OCP\JSON::error(array('data' => array( 'message' => "The maximun file size for opening root files is $maxsize bytes.")));
		return;
	}
	OCP\JSON::success(array('data' => array('message' => "The file is allowed to be open in the ROOT Viewer")));

} else {
	OCP\JSON::error(array('data' => array( 'message' => 'Invalid file path supplied.')));
}

Add route to check for maximun size to open ROOT files


<?php

// Recreate a message
// This code is used in BackendIMAP:GetMessage - for MIME format (iOS devices), and will try to fix the encoding
// Will parse all the sample messages and reencode them, saving the result in /tmp/. The samples dir contains broken messages, feel free to add your samples!!

// RUN FROM Z-Push-contrib ROOT FOLDER (NOT FROM TESTING FOLDER)

// MODIFY THIS IF YOU MUST
$dir = 'testing/samples/messages';
$tmpdir = '/tmp/';

if ($handle = opendir($dir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            printf("========== TEST FILE: $entry\n");
            testMimeDecode($dir . "/" . $entry, $tmpdir . $entry . ".eml");
        }
    }
    closedir($handle);
}

function getBodyRecursive($message, $subtype, &$body) {
    if(!isset($message->ctype_primary)) return;
    if(strcasecmp($message->ctype_primary,"text")==0 && strcasecmp($message->ctype_secondary,$subtype)==0 && isset($message->body))
        $body .= $message->body;

    if(strcasecmp($message->ctype_primary,"multipart")==0 && isset($message->parts) && is_array($message->parts)) {
        foreach($message->parts as $part) {
            // Content-Type: text/plain; charset=us-ascii; name="hareandtoroise.txt" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="hareandtoroise.txt"
            // We don't want to show that file, so if we have content-disposition not apply recursive
            if(!isset($part->disposition))  {
                getBodyRecursive($part, $subtype, $body);
            }
        }
    }
}

function testMimeDecode($file, $new_file) {
    require_once('include/ForceUTF8/Encoding.php');
    require_once('include/mimeDecode.php');
    require_once('include/mimePart.php');
    require_once('backend/imap/mime_encode.php');

    printf("TEST MIME DECODE\n");
    $mobj = new Mail_mimeDecode(file_get_contents($file));
    $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
    $handle = fopen($new_file, "w");
    fwrite($handle, build_mime_message($message));
    fclose($handle);

    foreach ($message->headers as $k => $v) {
        printf("Header <%s> <%s>\n", $k, $v);
    }

    $text = $html = "";
    getBodyRecursive($message, "plain", $text);
    getBodyRecursive($message, "html", $html);

    printf("TEXT Body <%s>\n", $text);

    printf("HTML Body <%s>\n", $html);
}
?>

Test - Reencode all the MIME messages in the samples folder fixing the encodings


<?php
namespace DelayedJobs\Worker;

use Cake\Datasource\ModelAwareTrait;

/**
 * Class BaseWorker
 */
abstract class BaseWorker
{
    use ModelAwareTrait;

    /**
     * Construct the listener
     *
     * @param array $options Allow child listeners to have options
     */
    public function __construct(array $options = [])
    {
        $this->modelFactory('Table', ['Cake\ORM\TableRegistry', 'get']);
    }
}

Add a base worker shell

Add a base worker shell


<?php
 //WARNING: The contents of this file are auto-generated

/**
 * Advanced OpenWorkflow, Automating SugarCRM.
 * @package Advanced OpenWorkflow for SugarCRM
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program 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.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author SalesAgility <info@salesagility.com>
 */

if (!isset($hook_array) || !is_array($hook_array)) {
    $hook_array = array();
}
if (!isset($hook_array['after_save']) || !is_array($hook_array['after_save'])) {
    $hook_array['after_save'] = array();
}
$hook_array['after_save'][] = array(99, 'AOW_Workflow', 'modules/AOW_WorkFlow/AOW_WorkFlow.php','AOW_WorkFlow', 'run_bean_flows');

Revert "removing an accidently added custom"

This reverts commit 67739dd33ef781726d44fa9ebc5cc01fc7fc54ee.


<?php

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

namespace Psy\Test\CodeCleaner;

use Psy\CodeCleaner\LegacyEmptyPass;

class LegacyEmptyPassTest extends CodeCleanerTestCase
{
    public function setUp()
    {
        $this->setPass(new LegacyEmptyPass());
    }

    /**
     * @dataProvider invalidStatements
     * @expectedException \Psy\Exception\FatalErrorException
     */
    public function testProcessInvalidStatement($code)
    {
        $stmts = $this->parse($code);
        $this->traverser->traverse($stmts);
    }

    public function invalidStatements()
    {
        return array(
            array('empty()'),
            array('empty(null)'),
            array('empty(PHP_EOL)'),
            array('empty("wat")'),
            array('empty(1.1)'),
        );
    }

    /**
     * @dataProvider validStatements
     */
    public function testProcessValidStatement($code)
    {
        $stmts = $this->parse($code);
        $this->traverser->traverse($stmts);
    }

    public function validStatements()
    {
        $data = array(
            array('empty($foo)'),
            array('empty(Bar::$baz)'),
        );

        return $data;
    }
}

Add test coverage for LegacyEmptyPass.

Add test coverage for LegacyEmptyPass.


<?php

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

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

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

Add migration to make a signup_id index on the events table


<?php

/*
 * This file is part of composer/semver.
 *
 * (c) Composer <https://github.com/composer>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Composer\Semver\Constraint;

trigger_error('The ' . __CLASS__ . ' abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED);

/**
 * Base constraint class.
 */
abstract class AbstractConstraint implements ConstraintInterface
{
    /** @var string */
    protected $prettyString;

    /**
     * @param ConstraintInterface $provider
     *
     * @return bool
     */
    public function matches(ConstraintInterface $provider)
    {
        if ($provider instanceof $this) {
            // see note at bottom of this class declaration
            return $this->matchSpecific($provider);
        }

        // turn matching around to find a match
        return $provider->matches($this);
    }

    /**
     * @param string $prettyString
     */
    public function setPrettyString($prettyString)
    {
        $this->prettyString = $prettyString;
    }

    /**
     * @return string
     */
    public function getPrettyString()
    {
        if ($this->prettyString) {
            return $this->prettyString;
        }

        return $this->__toString();
    }

    // implementations must implement a method of this format:
    // not declared abstract here because type hinting violates parameter coherence (TODO right word?)
    // public function matchSpecific(<SpecificConstraintType> $provider);
}

<?php

/*
 * This file is part of composer/semver.
 *
 * (c) Composer <https://github.com/composer>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Composer\Semver\Constraint;

trigger_error('The ' . __NAMESPACE__ . '\AbstractConstraint abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED);

/**
 * Base constraint class.
 */
abstract class AbstractConstraint implements ConstraintInterface
{
    /** @var string */
    protected $prettyString;

    /**
     * @param ConstraintInterface $provider
     *
     * @return bool
     */
    public function matches(ConstraintInterface $provider)
    {
        if ($provider instanceof $this) {
            // see note at bottom of this class declaration
            return $this->matchSpecific($provider);
        }

        // turn matching around to find a match
        return $provider->matches($this);
    }

    /**
     * @param string $prettyString
     */
    public function setPrettyString($prettyString)
    {
        $this->prettyString = $prettyString;
    }

    /**
     * @return string
     */
    public function getPrettyString()
    {
        if ($this->prettyString) {
            return $this->prettyString;
        }

        return $this->__toString();
    }

    // implementations must implement a method of this format:
    // not declared abstract here because type hinting violates parameter coherence (TODO right word?)
    // public function matchSpecific(<SpecificConstraintType> $provider);
}

Use __NAMESPACE__ because ::class won't work in php 5.3

Patched version of #64


<?php
namespace Universal\Http;

class FilesParameter extends Parameter
{
    public $hash;
    public $files;

    function __construct( $hash )
    {
        $files = array();
        foreach( array_keys($hash) as $name ) {

            // multiple files
            if( is_array($hash[ $name ][ 'error' ]) ) {
                $files[ $name ] = array();
                for( $i = 0 ; $i < count( $hash[ $name ]['error'] ) ; ++$i ) {
                    $attributes = array(
                        'name' => $hash[$name]['name'],
                        'size' => $hash[$name]['size'],
                        'type' => $hash[$name]['type'],
                        'error' => $hash[$name]['error'],
                        'tmp_name' => $hash[$name]['tmp_name'],
                    );
                    $files[ $name ][] = new self( $attributes );
                }
            }
            else {
                // single file
                $files[ $name ] = new self( $hash[ $name ] );
            }
        }
        $this->hash = $files;

    }

        /*
        foreach ($_FILES["pictures"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK) {
                $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
                $name = $_FILES["pictures"]["name"][$key];
                move_uploaded_file($tmp_name, "data/$name");
            }
        }
     */
}

Convert Files array to normal list.

Convert Files array to normal list.


<?php namespace Exolnet\Database\Eloquent;

use Exolnet\Core\Exceptions\RepositoryException;
use Exolnet\Database\Repository\Repository;
use Illuminate\Database\Eloquent\Model;

class EloquentRepository implements Repository
{
	/**
	 * @var string
	 */
	protected $model;

	/**
	 * @return \Illuminate\Database\Eloquent\Model
	 * @throws \Exolnet\Core\Exceptions\RepositoryException
	 */
	public function newModel()
	{
		$model = new $this->model();

		if ( ! $model instanceof Model) {
			throw new RepositoryException('Class '. $this->model .' must be an instance of Illuminate\\Database\\Eloquent\\Model.');
		}

		return $model;
	}

	/**
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	public function newQuery()
	{
		return $this->newModel()->newQuery();
	}

	/**
	 * @param array $columns
	 * @return \Illuminate\Database\Eloquent\Collection
	 */
	public function all(array $columns = ['*'])
	{
		return $this->newQuery()->get($columns);
	}

	/**
	 * @param mixed $id
	 * @param array $columns
	 * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
	 */
	public function find($id, array $columns = ['*'])
	{
		return $this->newQuery()->find($id, $columns);
	}

	/**
	 * @param \Illuminate\Database\Eloquent\Model $model
	 * @return static
	 */
	public function create(Model $model)
	{
		return $model->create();
	}

	/**
	 * @param \Illuminate\Database\Eloquent\Model $model
	 * @return bool|int
	 */
	public function update(Model $model)
	{
		return $model->update();
	}

	/**
	 * @param \Illuminate\Database\Eloquent\Model $model
	 * @return bool
	 */
	public function save(Model $model)
	{
		return $model->save();
	}

	/**
	 * @param \Illuminate\Database\Eloquent\Model $model
	 * @return bool|null
	 * @throws \Exception
	 */
	public function delete(Model $model)
	{
		return $model->delete();
	}
}

Add a base Eloquent Repository

Add a base Eloquent Repository


<?php
namespace Listabierta\Bundle\MunicipalesBundle\Command;

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

class RememberVoteDelayedCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('census:remembervotedelayed')
             ->setDescription('Send a remember email for remaining voters');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	// Force to set host in command console
    	$this->getContainer()->get('router')->getContext()->setHost('censo.participasevilla.org');

    	$logger = $this->getContainer()->get('logger');

    	$logger->info('Executing command census:remembervotedelayed');

    	$entity_manager = $this->getContainer()->get('doctrine')->getManager();

    	$census_user_repository = $entity_manager->getRepository('Listabierta\Bundle\MunicipalesBundle\Entity\CensusUser');
    	$census_users = $census_user_repository->findAll();

    	if(!empty($census_users))
    	{
    		foreach($census_users as $census_user)
    		{
    			$census_user_token = $census_user->getToken();
    			if(!empty($census_user_token))
    			{
					//if($census_user->getId() == 1)
					//{
						try
						{
							// Send mail with login link for admin
							$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'censo.participasevilla.org';

							$message = \Swift_Message::newInstance()
							->setSubject('Ampliación de plazo para la votación de investidura de la alcaldía de Sevilla')
							->setFrom('info@' . rtrim($host, '.'), 'Participa Sevilla')
							->setTo($census_user->getEmail())
							->setBody(
									$this->getContainer()->get('templating')->render(
											'MunicipalesBundle:Mail:remember_vote_delayed.html.twig',
											array(
												'token' => $census_user_token,
											)
									), 'text/html'
							);

							$this->getContainer()->get('mailer')->send($message);

	    					$output->writeln('Sent remember vote mail with token [' . $census_user_token .  '] for user ID ' . $census_user->getId() . '.');
    					}
    					catch(\Exception $e)
    					{
    						$output->writeln($census_user->getEmail() . ' error: ' . $e->getMessage());
    					}
					//}
    			}
    		}
    	}

        $output->writeln('Done.');
    }
}

Add remember vote delayed command

Add remember vote delayed command


<?php

namespace QCloudSDKTests\TIM;

use GuzzleHttp\Psr7\Uri;
use QCloudSDK\TIM\Status;
use QCloudSDKTests\TestCase;

class StatusTest extends TestCase
{
    /**
     * @var Status
     */
    protected $status;

    protected function setUp()
    {
        parent::setUp();
        $this->status = new Status($this->configForTest(), $this->http);
    }

    public function testSingleStatus()
    {
        $time = time();
        $this->status->queryDelivery()->pullSingleStatus('86', '13712345678', $date = date('Y-m-d H:i:s', $time), $date, 5);
        $this->assertMyRequestUri(function (Uri $uri){
            $this->assertStringEndsWith('pullstatus4mobile', $uri->getPath());
        });
        $this->assertMyRequestJson(function ($json) use ($time) {
            $this->assertSame(Status::TYPE_DELIVERY, $json['type']);
            $this->assertSame(5, $json['max']);
            $this->assertSame($time, $json['begin_time']);
            $this->assertSame($time, $json['end_time']);
            $this->assertSame('86', $json['nationcode']);
            $this->assertSame('13712345678', $json['mobile']);
        });
    }

    public function testMultiStatus()
    {
        $time = time();
        $this->status->queryReply()->pullMultiStatus(20);
        $this->assertMyRequestUri(function (Uri $uri){
            $this->assertStringEndsWith('pullstatus', $uri->getPath());
        });
        $this->assertMyRequestJson(function ($json) use ($time) {
            $this->assertSame(Status::TYPE_REPLY, $json['type']);
            $this->assertSame(20, $json['max']);
        });
    }

    public function testSendStatus()
    {
        $time = time();
        $this->status->pullSendStatus($time, $time);
        $this->assertMyRequestUri(function (Uri $uri){
            $this->assertStringEndsWith('pullsendstatus', $uri->getPath());
        });
        $this->assertMyRequestJson(function ($json) use ($time) {
            $this->assertSame(intval(date('YmdH', $time)), $json['begin_date']);
            $this->assertSame(intval(date('YmdH', $time)), $json['end_date']);
        });
    }

    public function testCallbackStatus()
    {
        $time = time();
        $this->status->pullCallbackStatus($time, $time);
        $this->assertMyRequestUri(function (Uri $uri){
            $this->assertStringEndsWith('pullcallbackstatus', $uri->getPath());
        });
        $this->assertMyRequestJson(function ($json) use ($time) {
            $this->assertSame(intval(date('YmdH', $time)), $json['begin_date']);
            $this->assertSame(intval(date('YmdH', $time)), $json['end_date']);
        });
    }

}

Add tests for TIM status

Add tests for TIM status


<?php

use Mimic\Functional as F;

/**
 * Unit Test for short Mimic library function.
 *
 * @since 0.1.0
 *
 * @todo Need to use QuickTest library.
 */
class ShortFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		$values = array_fill(0, 5, 1);
		$keys = array_fill_keys(array('index1', 'index2', 'index3', 'index4', 'index5'), 1);
		return array(
			array(true, false, true, 11, $values),
			array(true, false, false, 3, $values),
			array(true, false, true, 11, $keys),
			array(true, false, false, 3, $keys),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\short
	 */
	public function testResults($passed, $default, $expected, $stop, $data) {
		$executed = 0;
		$self = $this;

		$callback = function($element, $index, $collection) use ($data, $stop, $self, &$executed) {
			$executed += 1;
			$self->assertTrue((is_string($index) || is_numeric($index)), 'index is not correct type');
			$self->assertTrue(array_key_exists($index, $data), 'index does not exist in given data');
			$self->assertEquals($data[$index], $element, 'existing array does not match given element');
			$self->assertEquals($data, $collection, 'given collection does not match data');
			return $executed > $stop;
		};

		$actual = F\short($data, $passed, $default, $callback);

		$this->assertEquals(count($data), $executed);
		$this->assertEquals($expected, $actual);
	}
}

Complete short function unit tests.

Complete short function unit tests.


<?php

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

class AddRsvpDeadlineToApplicationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('applications', function (Blueprint $table) {
            $table->timestamp('rsvp_deadline')->nullable();
        });
    }

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

Add a RSVP deadline column 🕐 (todo: implement this)


<?php

namespace Oro\Bundle\OrganizationBundle\Autocomplete;

use Doctrine\Bundle\DoctrineBundle\Registry;

use Oro\Bundle\FormBundle\Autocomplete\SearchHandler;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;

class BusinessUnitOwnerSearchHandler extends SearchHandler
{
    /** @var  Registry */
    protected $doctrine;

    public function __construct($entityName, array $properties, Registry $doctrine)
    {
        parent::__construct($entityName, $properties);
        $this->doctrine = $doctrine;
    }

    /**
     * {@inheritdoc}
     */
    public function convertItem($item)
    {
        $result = parent::convertItem($item);

        $businessUnit = $this->doctrine->getManager()->getRepository('OroOrganizationBundle:BusinessUnit')
            ->find($result[$this->idFieldName]);

        $result['treePath'] = $this->getPath($businessUnit, []);
        $result['organization_id'] = $businessUnit->getOrganization()->getId();

        return $result;
    }

    /**
     * @param BusinessUnit $businessUnit
     * @param $path
     *
     * @return mixed
     */
    protected function getPath($businessUnit, $path)
    {
        array_unshift($path, ['name'=> $businessUnit->getName()]);

        $owner = $businessUnit->getOwner();
        if ($owner) {
            $path = $this->getPath($owner, $path);
        }

        return $path;
    }
}

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


<?php
namespace Bolt\Tests\Extensions;

use Bolt\Tests\BoltUnitTest;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Base class for extension specific testing.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 *
 * @runTestsInSeparateProcesses
 */
abstract class AbstractExtensionsUnitTest extends BoltUnitTest
{
    public function setup()
    {
        $this->php = \PHPUnit_Extension_FunctionMocker::start($this, 'Bolt')
            ->mockFunction('file_exists')
            ->mockFunction('is_readable')
            ->mockFunction('is_dir')
            ->mockFunction('copy')
            ->mockFunction('file_get_contents')
            ->getMock();

        $this->php2 = \PHPUnit_Extension_FunctionMocker::start($this, 'Bolt\Tests\Extensions\Mock')
            ->mockFunction('file_get_contents')
            ->getMock();
    }

    public function tearDown()
    {
        \PHPUnit_Extension_FunctionMocker::tearDown();

        $fs = new Filesystem();
        if ($fs->exists(PHPUNIT_WEBROOT . '/app/cache/config_cache.php')) {
            $fs->remove(PHPUNIT_WEBROOT . '/app/cache/config_cache.php');
        }
        if ($fs->exists(PHPUNIT_WEBROOT . '/extensions/local/')) {
            $fs->remove(PHPUNIT_WEBROOT . '/extensions/local/');
        }
    }

    public function localExtensionInstall()
    {
        $fs = new Filesystem();
        $fs->mirror(PHPUNIT_ROOT . '/resources/extensions/local/', PHPUNIT_WEBROOT . '/extensions/local/', null, ['delete' => true]);
    }
}

[Tests] Add an abstract class for extensions tests


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First Steps Into PHP</title>
</head>

<body>
<form>
    N: <input type="text" name="num1" />
    M: <input type="text" name="num2" />
    <input type="submit" />
</form>

<?php
if (isset($_GET['num1']) && isset($_GET['num2'])) {
    $n = intval($_GET['num1']);
    $m = intval($_GET['num2']);
    echo $n * $m;
}
?>

</body>
</html>

Create Multiply Two N Number

Create Multiply Two N Number


<?php

$router->post('menuitem/update', ['as' => 'api.menuitem.update', 'uses' => 'MenuItemController@update']);
$router->post('menuitem/delete', ['as' => 'api.menuitem.delete', 'uses' => 'MenuItemController@delete']);

<?php

$router->group(['prefix' => '/menuitem'], function () {
    post('/update', [
        'as' => 'api.menuitem.update',
        'uses' => 'MenuItemController@update',
        'middleware' => 'can:menu.menuitem.update',
    ]);
    post('/delete', [
        'as' => 'api.menuitem.delete',
        'uses' => 'MenuItemController@delete',
        'middleware' => 'can:menu.menuitem.destroy'
    ]);
});

Use new middleware as discussed in chat.

Previousely, any user could update or delete any menu item. Permissions had no effect for api call.


%begin_globals_site_metadata_jcu.site.logox^eq::1:%

If statement passed

%end_globals%

Add negative conditional keyword block

Add negative conditional keyword block


<?php namespace App\Services;

class Markdown {

    public function __construct()
    {

    }

    public function convertHtmlToMarkdown($html)
    {

    }

    public function convertMarkdownToHtml($markdown)
    {

    }

}

Add the actual markdown service.

Add the actual markdown service.


<?php
require "classe/Produto.php";

$livro = new Produto;
$livro->setNome("Livro da casa do codigo");
$livro->setPreco(10);

$livro2 = new Produto;
$livro2->setNome("Livro da casa do codigo");
$livro2->setPreco(10);

$livro2 = $livro;

if($livro === $livro2) {
  echo "sao iguais";
} else {
  echo "sao diferentes";
}
?>

Update files, Alura, PHP e Orientação a Objetos, Aula 5


<?php
class RolesTableSeeder extends Seeder {
  /**
   * Seed the Roles table.
   *
   * @return void
   */
  public function run()
  {
    Role::truncate();
    Role::create(['name' => 'admin']);
  }
}

Create admin role with a seed.

Create admin role with a seed.


<?php

go(function(){
    $db = new Swoole\Coroutine\Mysql;
    $server = [
        'host'     => 'unix:/tmp/mysql.sock',
        'user'     => 'root',
        'password' => 'root',
        'database' => 'test'
    ];
    $db->connect($server);
    $stmt = $db->prepare('SELECT * FROM `user` WHERE id=?');
    $ret = $stmt->execute([1]);
    var_dump($ret);
});

Add example for mysql unix socket.

Add example for mysql unix socket.


<?php

declare(strict_types=1);

use PhpParser\BuilderFactory;

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

$factory = new BuilderFactory();
$voidCall = $factory->methodCall(
    $factory->var('this'),
    '_intercept',
    [$factory->funcCall('func_get_args'), $factory->constFetch('__FUNCTION__')]
);

$returnCall = new PhpParser\Node\Stmt\Return_(
    $factory->methodCall(
        $factory->var('this'),
        '_intercept',
        [$factory->funcCall('func_get_args'), $factory->constFetch('__FUNCTION__')]
    )
);

$nodeVoid = $factory->namespace('a')->addStmt($voidCall)->getNode();
$nodeReturn = $factory->namespace('a')->addStmt($returnCall)->getNode();

$prettyPrinter = new PhpParser\PrettyPrinter\Standard();

echo $prettyPrinter->prettyPrintFile([$nodeVoid]);
echo $prettyPrinter->prettyPrintFile([$nodeReturn]);

Create test code to create call intercept method


<?php

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

class AddKits extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('kit_item', [ 'signed' => false ]);
      $table
        ->addColumn('kit_id', 'integer', [
          'signed' => false,
          'null' => false,
        ])
        ->addColumn('item_id', 'integer', [
          'signed' => false,
          'null' => false,
        ])
        ->addColumn('sort', 'integer', [
          'signed' => false,
          'null' => false,
          'default' => 0,
        ])
        ->addColumn('description', 'text', [
                      'limit' => MysqlAdapter::TEXT_MEDIUM,
                      'null' => true,
                    ])
        ->addColumn('created', 'datetime', [
          'default' => 'CURRENT_TIMESTAMP'
        ])
        ->addColumn('modified', 'datetime', [
          'default' => 'CURRENT_TIMESTAMP',
          'update' => 'CURRENT_TIMESTAMP'
        ])
        ->addIndex(['kit_id'])
        ->create();

      $table= $this->table('item', [ 'signed' => false ]);
      $table
        ->addColumn('is_kit', 'integer', [
                      'limit' => MysqlAdapter::INT_TINY,
                      'default' => 0,
                      'after' => 'tic',
                    ])
        ->save();

      $table= $this->table('txn_line', [ 'signed' => false ]);
      $table
        ->addColumn('kit_id', 'integer', [
          'after' => 'item_id',
          'signed' => false,
          'null' => true
        ])
        ->save();
    }
}

Add kits to db schema

Add kits to db schema


<?php

namespace Bolt;

/**
 * Class for Bolt's generic library functions
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Library
{

}

Add a class outline for the library functions


<?php
namespace Dms\Web\Expressive\Tests\Unit\Renderer\Action;

use Dms\Web\Expressive\Renderer\Action\ActionButton;
use PHPUnit\Framework\TestCase;

/**
 * @author Hari KT <kthari85@gmail.com>
 */
class ActionButtonTest extends TestCase
{
    public function testGetUrl()
    {
        $actionButton = new ActionButton(
            false,
            'edit',
            'Edit',
            function (string $objectId) {
                return str_replace('__object__', $objectId, '/hello/__object__');
            }
        );

        $this->assertSame('edit', $actionButton->getName());
        $this->assertSame('Edit', $actionButton->getLabel());
        $this->assertSame('/hello/123', $actionButton->getUrl(123));
        $this->assertFalse($actionButton->hasObjectSupportedCallback());
        $this->assertFalse($actionButton->isPost());
        $this->assertFalse($actionButton->isDisabled());
    }
}

Add a unit test for ActionButton

Add a unit test for ActionButton


<?php

namespace JWX\JWS\Algorithm;

use JWX\JWK\Feature\AsymmetricPrivateKey;
use JWX\JWK\Feature\AsymmetricPublicKey;
use JWX\JWS\SignatureAlgorithm;

/**
 * Base class for algorithms employing asymmetric signature computation
 * using OpenSSL extension.
 */
abstract class OpenSSLSignatureAlgorithm implements SignatureAlgorithm
{
	/**
	 * Public key.
	 *
	 * @var AsymmetricPublicKey $_publicKey
	 */
	protected $_publicKey;

	/**
	 * Private key.
	 *
	 * @var AsymmetricPrivateKey|null $_privateKey
	 */
	protected $_privateKey;

	/**
	 * Get the message digest method name supported by OpenSSL.
	 *
	 * @return string
	 */
	abstract protected function _mdMethod();

	public function computeSignature($data) {
		/**
		 * NOTE: OpenSSL uses PKCS #1 v1.5 padding by default, so no explicit
		 * padding is required by sign and verify operations.
		 */
		if (!isset($this->_privateKey)) {
			throw new \LogicException("Private key not set.");
		}
		$key = openssl_pkey_get_private($this->_privateKey->toPEM()->string());
		if (!$key) {
			throw new \RuntimeException(
				"openssl_pkey_get_private() failed: " .
					 $this->_getLastOpenSSLError());
		}
		$result = @openssl_sign($data, $signature, $key, $this->_mdMethod());
		if (!$result) {
			throw new \RuntimeException(
				"openssl_sign() failed: " . $this->_getLastOpenSSLError());
		}
		return $signature;
	}

	public function validateSignature($data, $signature) {
		$key = openssl_pkey_get_public($this->_publicKey->toPEM()->string());
		if (!$key) {
			throw new \RuntimeException(
				"openssl_pkey_get_public() failed: " .
					 $this->_getLastOpenSSLError());
		}
		$result = @openssl_verify($data, $signature, $key, $this->_mdMethod());
		if (false === $result || -1 == $result) {
			throw new \RuntimeException(
				"openssl_verify() failed: " . $this->_getLastOpenSSLError());
		}
		return $result == 1;
	}

	/**
	 * Get the last OpenSSL error message.
	 *
	 * @return string|null
	 */
	protected function _getLastOpenSSLError() {
		$msg = null;
		while (false !== ($err = openssl_error_string())) {
			$msg = $err;
		}
		return $msg;
	}
}

Add base class for OpenSSL signature algorithms


<?php

class testsCli extends PHPUnit_Framework_TestCase {

	function test_string_length() {
		$this->assertEquals( \cli\Colors::length( 'x' ), 1 );
	}

	function test_encoded_string_length() {

		$this->assertEquals( \cli\Colors::length( 'hello' ), 5 );
		$this->assertEquals( \cli\Colors::length( 'óra' ), 3 );

		$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'hello', 6 ) ), 6 );
		$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'óra', 6 ) ), 6 );

	}

	function test_colorized_string_length() {
		$this->assertEquals( \cli\Colors::length( \cli\Colors::colorize( '%Gx%n', true ) ), 1 );
	}

}

<?php

class testsCli extends PHPUnit_Framework_TestCase {

	function test_string_length() {
		$this->assertEquals( \cli\Colors::length( 'x' ), 1 );
	}

	function test_encoded_string_length() {

		$this->assertEquals( \cli\Colors::length( 'hello' ), 5 );
		$this->assertEquals( \cli\Colors::length( 'óra' ), 3 );

		$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'hello', 6 ) ), 6 );
		$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'óra', 6 ) ), 6 );

	}

	function test_colorized_string_length() {
		$this->assertEquals( \cli\Colors::length( \cli\Colors::colorize( '%Gx%n', true ) ), 1 );
	}

	function test_colorize_string_is_colored() {
		$original = '%Gx';
		$colorized = "\033[32;1mx";

		$this->assertEquals( \cli\Colors::colorize( $original, true ), $colorized );
	}

	function test_colorize_when_colorize_is_forced() {
		$original = '%gx%n';

		$this->assertEquals( \cli\Colors::colorize( $original, false ), 'x' );
	}

	function test_binary_string_is_converted_back_to_original_string() {
		$string            = 'x';
		$string_with_color = '%b' . $string;
		$colorized_string  = "\033[34m$string";

		// Ensure colorization is applied correctly
		$this->assertEquals( \cli\Colors::colorize( $string_with_color, true ), $colorized_string );

		// Ensure that the colorization is reverted
		$this->assertEquals( \cli\Colors::decolorize( $colorized_string ), $string );
	}
}

Add tests for colorization and decolorization.


<?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 AddUserReadNotificationToUserNotifications extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('user_notifications', function (Blueprint $table) {
            $table->index(['user_id', 'is_read'], 'user_read');
        });
    }

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

Add read index to user notifications

Add read index to user notifications


<?php

declare(strict_types=1);

namespace CultuurNet\UDB3\Event\ValueObjects;

use Broadway\Serializer\SerializableInterface;
use InvalidArgumentException;

class Status implements SerializableInterface
{
    private const SCHEDULED = 'EventScheduled';
    private const POSTPONED = 'EventPostponed';
    private const CANCELLED = 'EventCancelled';

    /**
     * @var string
     */
    private $value;

    /**
     * @var string[]
     */
    private const ALLOWED_VALUES = [
        self::SCHEDULED,
        self::POSTPONED,
        self::CANCELLED,
    ];

    private function __construct(string $value)
    {
        if (!\in_array($value, self::ALLOWED_VALUES, true)) {
            throw new InvalidArgumentException('Status does not support the value "' . $value . '"');
        }
        $this->value = $value;
    }

    public static function scheduled(): Status
    {
        return new Status(self::SCHEDULED);
    }

    public static function postponed(): Status
    {
        return new Status(self::POSTPONED);
    }

    public static function cancelled(): Status
    {
        return new Status(self::CANCELLED);
    }

    public function toNative(): string
    {
        return $this->value;
    }

    public static function fromNative(string $value): Status
    {
        return new Status($value);
    }

    public function equals(Status $status): bool
    {
        return $this->value === $status->toNative();
    }

    public static function deserialize(array $data): Status
    {
        new Status($data['eventStatus']);
    }

    public function serialize(): array
    {
        return [
            'eventStatus' => $this->value,
        ];
    }
}

Add value object for status

Add value object for status


<?php
/**
 *
 * @author newloki
 */

class Parser_Stemmer_Porter_Parser extends Parser_Abstract implements Parser_Interface
{

    /**
     * @var array
     * 'word' => 'format'
     */
    protected $_result = array();

    /**
     * @return array
     */
    public function parse()
    {
        foreach($this->_splitText as $word) {
            if(!array_key_exists($word, $this->_result)) {
                $this->_result[$word] = $this->getFormat($word);
            }
        }
        //@todo
        //maybe it is usefull to give a text back
        //where each word is replaced by himself followed by his format
        //in braces
        //e.g.: but(CVC) falling(CVCVC) computer(CVCVCVC)
        return $this->_result;
    }

    //@todo implement special cases, for example, Y is an vocal in english,
    //but if he is followed by a vocal he is an consonant
    protected function getFormat($_word)
    {
        //iterate over each char
        //for each char look if it is consonant or vocal
        $wordVC = '';
        $mapping = $this->_language->getMapping();

        $chars = $this->getWordAsArray($_word);
        foreach($chars as $char) {
            $wordVC .= $mapping[$char];
        }

        $result = preg_replace('/\b(.)\1+/is', '\1', $wordVC);

        return $result;
    }
}

Add parser for porter staemming algorithm


<?php

namespace Scarlett\Tests;

use Scarlett\Framework;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;

class FrameworkTest extends \PHPUnit_Framework_TestCase
{
    public function testNotFoundHandling()
    {
        $framework = $this->getFrameworkForException(new ResourceNotFoundException());

        $response = $framework->handle(new Request());

        $this->assertEquals(404, $response->getStatusCode());
    }

    protected function getFrameworkForException($exception)
    {
        $matcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $matcher
            ->expects($this->once())
            ->method('match')
            ->will($this->throwException($exception))
        ;
        $resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');

        return new Framework($matcher, $resolver);
    }
}

Test sample for the framework class

Test sample for the framework class


<?php
class CoreTest extends PHPUnit_Framework_TestCase {
    public function testIsInstalledExitsWith1IfWordPressNotInstalled() {
        $temp_dir = self::create_temporary_directory();
        $result = self::run_wp_cli("core is-installed --path=$temp_dir");
        $this->assertEquals(1, $result->return_code);
    }

    private static function create_temporary_directory() {
        return sys_get_temp_dir() . '/' . uniqid("wp-cli-test-", TRUE);
    }

    private static function run_wp_cli( $wp_cli_command ) {
        $wp_cli_path = self::find_wp_cli();
        return self::run_command("$wp_cli_path $wp_cli_command");
    }

    private static function find_wp_cli() {
        return "src/bin/wp";
    }

    private static function run_command( $command ) {
        $output = array();
        $return_code = 0;
        exec( $command, $output, $return_code );
        return new ExecutionResult( $return_code );
    }
}

class ExecutionResult {
    public function __construct( $return_code ) {
        $this->return_code = $return_code;
    }
}

Add test for wp core is-installed when WordPress is not installed


<?php

use tests\common\TestCommon;

$I = new FunctionalTester($scenario);
TestCommon::logMeIn($I);

$I->wantTo('ensure that view tem page works');

$I->amOnPage('/item/1');
$I->expectTo('see Back button');
$I->seeElement('a.btn');
$I->expectTo('see table with item info');
$I->seeElement('table.table');

$I->wantTo('click to Back button');
$I->click('Back');
$I->expectTo('to be redirected to front page');
$I->see(TestCommon::FRONT_PAGE_HEADER, 'h1');
$I->seeCurrentUrlEquals('/');

TestCommon::logMeOut($I);

Add func test for ItemView page

Add func test for ItemView page


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3;

use Broadway\Domain\DomainEventStream;

/**
 * Class SimpleEventBus
 * @package CultuurNet\UDB3
 *
 * Extension of Broadway's SimpleEventBus with a configurable callback to be
 * executed before the first message is published. This callback can be used to
 * subscribe listeners.
 */
class SimpleEventBus extends \Broadway\EventHandling\SimpleEventBus
{
    private $first = true;

    /**
     * @var nul|callable
     */
    private $beforeFirstPublicationCallback;

    /**
     * @param callable $callback
     */
    public function beforeFirstPublication($callback) {
        $this->beforeFirstPublicationCallback = $callback;
    }

    private function callBeforeFirstPublicationCallback() {
        if ($this->beforeFirstPublicationCallback) {
            $callback = $this->beforeFirstPublicationCallback;
            $callback($this);
        }
    }

    public function publish(DomainEventStream $domainMessages)
    {
        if ($this->first) {
            $this->first = false;
            $this->callBeforeFirstPublicationCallback();
        }

        parent::publish($domainMessages);
    }
}

iii-105: Add event bus extension with method to act on first publication of messages


<?php

use Northstar\Models\Client;
use Northstar\Models\User;

class OAuthTest extends TestCase
{
    /**
     * Test that the password grant rejects invalid credentials.
     */
    public function testPasswordGrantWithInvalidCredentials()
    {
        $user = User::create(['email' => 'login-test@dosomething.org', 'password' => 'secret']);
        $client = Client::create(['app_id' => 'phpunit']);

        $this->post('v2/auth/token', [
            'grant_type' => 'password',
            'client_id' => $client->client_id,
            'client_secret' => $client->client_secret,
            'username' => $user->email,
            'password' => 'letmein',
        ]);

        $this->assertResponseStatus(401);
    }

    /**
     * Test that the password grant provides a JWT for valid credentials.
     */
    public function testPasswordGrant()
    {
        $user = User::create(['email' => 'login-test@dosomething.org', 'password' => 'secret']);
        $client = Client::create(['app_id' => 'phpunit']);

        $this->post('v2/auth/token', [
            'grant_type' => 'password',
            'client_id' => $client->client_id,
            'client_secret' => $client->client_secret,
            'username' => $user->email,
            'password' => 'secret',
        ]);

        $this->assertResponseStatus(200);
        $this->seeJsonStructure([
            'token_type',
            'expires_in',
            'access_token',
            'refresh_token',
        ]);
    }

    /**
     * Test that the client credentials grant provides a JWT for valid credentials.
     */
    public function testClientCredentials()
    {
        $client = Client::create(['app_id' => 'phpunit']);

        $this->post('v2/auth/token', [
            'grant_type' => 'client_credentials',
            'client_id' => $client->client_id,
            'client_secret' => $client->client_secret,
        ]);

        $this->assertResponseStatus(200);
        $this->seeJsonStructure([
            'token_type',
            'expires_in',
            'access_token',
        ]);
    }
}

Add some tests for OAuth endpoints.

Add some tests for OAuth endpoints.


<?php
/*
* MyUCP
* File Version 4.0.0.1
* Date: 15.07.2015
* Developed by Maksa988
*/

final class pdoDriver {
	private $pdo;
	private $count = 0;
	public function __construct($hostname, $username, $password, $database, $type) {
		if (!$this->pdo = new PDO("mysql:host={$hostname};dbname={$database};charset=utf8", $username, $password)) {
	  		exit('Ошибка: Не удалось соединиться с базой данных!');
		}
  	}

  	public function query($sql) {
		$resource = $this->pdo->query($sql);

		$this->count++;

		if ($resource) {
			if(preg_match("/SELECT/i", $sql)){
				$i = 0;
				$data = array();

				while($result = @$resource->fetch(PDO::FETCH_ASSOC)) {
					$data[$i] = $result;
					$i++;
				}

				$query = new stdClass();
				$query->row = isset($data[0]) ? $data[0] : array();
				$query->rows = $data;
				$query->num_rows = $i;

				unset($data);
				return $query;
			} else {
				return true;
			}
		} else {
			exit('Ошибка: ' . $this->pdo->errorInfo[2] . '
Номер ошибки: ' . $this->pdo->errorCode() . '
' . $sql);
		}
  	}

	public function escape($value) {
		return $this->pdo->quote($value);
	}

  	public function countAffected() {
		return $this->pdo->exec;
  	}

  	public function getLastId() {
		return $this->pdo->lastInsertId();
  	}

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

	public function __destruct() {
		unset($this->pdo);
	}
}
?>

Add new DB driver: PDO

Add new DB driver: PDO


<?php
include '../app/essentials.php';

class Backend {
  private $categories = array();

  public function __get($category) {
    if (!isset($categories[$category])) {
      $this->categories[$category] = new BackendCategory();
    }
    return $this->categories[$category];
  }
}

echo '<pre>';

echo '</pre>';

Add new backend system experiments

Add new backend system experiments


<?php

/*
 * This file is part of the package bk2k/bootstrap-package.
 *
 * For the full copyright and license information, please read the
 * LICENSE file that was distributed with this source code.
 */

namespace BK2K\BootstrapPackage\ViewHelpers\Format;

use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;

/**
 * LowercaseDashedViewHelper
 */
class LowercaseDashedViewHelper extends AbstractViewHelper
{
    use CompileWithRenderStatic;

    /**
     * Initialize arguments.
     *
     * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception
     */
    public function initializeArguments()
    {
        parent::initializeArguments();
    }

    /**
     * Formats a float to currency formatting
     *
     * @param array $arguments
     * @param \Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     *
     * @return string the formatted amount
     */
    public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
    {
        preg_match_all(
            '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
            $renderChildrenClosure(),
            $matches
        );
        $ret = $matches[0];
        foreach ($ret as &$match) {
            $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
        }
        return implode('-', $ret);
    }
}

[FEATURE] Add lowercase dashed formatting viewhelper


<?php

use Phinx\Migration\AbstractMigration;

class AddTurnNumberToGame extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $game = $this->table('game');

        $game->addColumn('turn_number', 'integer', array('signed' => false));

        $game->update();
    }
}

Add turn number on game structure

Add turn number on game structure


<?php
namespace Snapshoter\Command;

use Herrera\Phar\Update\Manager;
use Herrera\Phar\Update\Manifest;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateCommand extends ContainerAwareCommand
{
    const MANIFEST_FILE = 'http://solilokiam.github.io/SnapshoterDist/manifest.json';

    protected function configure()
    {
        $this->setName('update')
            ->setDescription('Updates Snapshoter.phar to the latest version');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $manager = new Manager(Manifest::loadFile(self::MANIFEST_FILE));
        $manager->update($this->getApplication()->getVersion(), true);
    }

}

Add autoupdate capabilities to snapshoter.phar


<?php
/*
 * 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.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace ProxyManagerTestAsset;

/**
 * Class with one protected method
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
abstract class ClassWithProtectedMethod
{
    protected function protectedMethod() : void
    {
    }
}

Test asset: class with a protected method


<?php
/*
	Table.class.php

	Copyright© 2015 Rubicon Communications, LLC (Netgate)
	This file is a part of pfSense®

	Copyright (C) 2015 Sjon Hortensius

	All rights reserved.

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

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``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
	AUTHOR 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.
*/

/*
	class expects a title and an 'array of arrrays', representing an array of rows in the table
	Row 0 is assumed to contain the table column headers, rows 1 -> X contain the tablke data
*/
class Form_Table extends Form_Input
{
	protected $_text;

	public function __construct($title, $data)
	{
		parent::__construct(null, $title);

		$text = "

";
		$text .= "
";

		/* Assume the number of elements in row 0 represents hte width of hte table */
		$rows = count($data);
		$columns = count($data[0]);

		/* Draw the table tile row */
		for($c=0; $c<$columns; $c++)
			$text .= "" . $data[0][$c] . "	";

		$text .= "

";
		$text .= "
";

		/* Draw each row */
		for($r=1; $r<$rows; $r++) {
			$text .= "
";

			for($c=0; $c<$columns;$c++) {
				$text .= "" . $data[$r][$c] . "	";
			}

			$text .= "
";
		}

		$text .= "

";

		$this->_text = $text;
	}

	protected function _getInput()
	{
		return $this->_text;
	}
}

Add a table to a section by passing it a two-dimensional array

Is there a better way to do this? Can the table position be controlled?


<?php
	require_once('IP2Country.php');

	$conf = array(
	    'db_server' => 'localhost',
	    'db_port' => 3306,
	    'db_name' => 'dnscheck',
	    'db_user' => 'dnscheck_webui',
	    'db_pass' => 'n5k4nbfnfn',
	);

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());

	/* Provide a place where settings can be overridden, to make Debian packaging easier. */
	if (is_readable('/etc/dnscheck/webui_config.php')) {
		require_once('/etc/dnscheck/webui_config.php');
	}

?>

<?php
	require_once('IP2Country.php');

	$conf = array(
	    'db_server' => 'localhost',
	    'db_port' => 3306,
	    'db_name' => 'dnscheck',
	    'db_user' => 'dnscheck_webui',
	    'db_pass' => 'demo_pwd',
	);

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());

	/* Provide a place where settings can be overridden, to make Debian packaging easier. */
	if (is_readable('/etc/dnscheck/webui_config.php')) {
		require_once('/etc/dnscheck/webui_config.php');
	}

?>

Replace password with more obvious example.


<?php
/**
 * Created by PhpStorm.
 * User: sonja
 * Date: 1/26/18
 * Time: 10:30 AM
 */

namespace AppBundle\API\Sharing;

class Projects
{

}

Create new class for sharing projects

Create new class for sharing projects


<?php
/**
 * Util_Rewrite class
 *
 * Contains rewrite utils
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 */

namespace Skeleton\Email;

class Util {
	/**
	 * Fetches the mime type for a certain file
	 *
	 * @param string $file The path to the file
	 * @return string $mime_type
	 */
	public static function mime_type($file)  {
		$handle = finfo_open(FILEINFO_MIME);
		$mime_type = finfo_file($handle,$file);

		if (strpos($mime_type, ';')) {
			$mime_type = preg_replace('/;.*/', ' ', $mime_type);
		}

		return trim($mime_type);
	}
}

Add a general utilities class

Add a general utilities class


@extends('layouts.app')

@section('content')

Dashboard

                    You are logged in!

@endsection

Index page for registered users template


<?php
/**
 * Slim Framework (http://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2016 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/master/LICENSE.md (MIT License)
 */
namespace Slim\Tests\Handlers;

use Slim\Handlers\AbstractHandler;

class AbstractHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testHalfValidContentType()
    {
        $req = $this->getMockBuilder('Slim\Http\Request')->disableOriginalConstructor()->getMock();
        $req->expects($this->any())->method('getHeaderLine')->will($this->returnValue('unknown/json'));

        $abstractHandler = $this->getMockForAbstractClass(AbstractHandler::class);

        $class = new \ReflectionClass(AbstractHandler::class);
        $method = $class->getMethod('determineContentType');
        $method->setAccessible(true);

        $return = $method->invoke($abstractHandler, $req);

        $this->assertEquals('text/html', $return);
    }
}

Test to check if half valid content type returns default


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2018, 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\Utils\Form\DataTransformer;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\DataTransformerInterface;

/**
 * Entity to ID form data transformer
 */
class EntityToIDTransformer implements DataTransformerInterface
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * @var string
     */
    private $entityClass;

    /**
     * @param \Doctrine\ORM\EntityManager $em          Entity manager
     * @param string                      $entityClass Entity class
     */
    public function __construct(EntityManager $em, $entityClass)
    {
        $this->em = $em;
        $this->entityClass = $entityClass;
    }

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

        $ids = $this->em->getClassMetadata($this->entityClass)->getIdentifierValues($value);

        return reset($ids);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (empty($value)) {
            return null;
        }

        return $this->em->find($this->entityClass, $value);
    }
}

Add entity-to-ID form data transformer.

Add entity-to-ID form data transformer.


<?php

namespace Risan\OAuth1\Test\Unit\Provider;

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Provider\Trello;
use Risan\OAuth1\Signature\HmacSha1Signer;
use Risan\OAuth1\Provider\ProviderInterface;

class TrelloTest extends TestCase
{
    private $trello;

    function setUp()
    {
        $this->trello = new Trello();
    }

    /** @test */
    function it_implements_provider_interface()
    {
        $this->assertInstanceOf(ProviderInterface::class, $this->trello);
    }

    /** @test */
    function it_has_correct_uri_config()
    {
        $this->assertEquals([
            'temporary_credentials_uri' => 'https://trello.com/1/OAuthGetRequestToken',
            'authorization_uri' => 'https://trello.com/1/OAuthAuthorizeToken',
            'token_credentials_uri' => 'https://trello.com/1/OAuthGetAccessToken',
            'base_uri' => 'https://api.trello.com/1/',
        ], $this->trello->getUriConfig());
    }

    /** @test */
    function it_has_hmac_sha1_signer()
    {
        $this->assertInstanceOf(HmacSha1Signer::class, $this->trello->getSigner());
    }
}

Add test for trello provider.

:white_check_mark: Add test for trello provider.