<?php

class Renderobject extends Resultset {
# TODO find out why this is different than Resultset and merge or extend

	var $title = 'Results';
    var $user = $_SESSION['user'];
    var $host = $_SESSION['host'];
    var $database = $_SESSION['database'];
    var $results = null;
	var $datapoints = [];
    var $columns = [];
    var $is_series_list = false; // TODO switch to enum
    var $start_pagination = 1;
    var $end_pagination = 1;
    var $timestamp_column = "";
}
?>

Add switch to handle database response differently depending on version.


<?php

namespace Doctrine\ODM\MongoDB\Tests\Tools;

use Doctrine\ODM\MongoDB\Events;
use Doctrine\ODM\MongoDB\Tools\ResolveTargetDocumentListener;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

class ResolveTargetDocumentListenerTest extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
    /**
     * @var \Doctrine\ODM\MongoDB\DocumentManager
     */
    protected $dm;

    /**
     * @var ResolveTargetDocumentListener
     */
    protected $listener;

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

         $this->listener = new ResolveTargetDocumentListener();
    }

    public function testResolveTargetDocumentListenerCanResolveTargetDocument()
    {
        $evm = $this->dm->getEventManager();

        $this->listener->addResolveTargetDocument(
            'Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetInterface',
            'Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetDocument',
            array()
        );

        $this->listener->addResolveTargetDocument(
            'Doctrine\ODM\MongoDB\Tests\Tools\TargetInterface',
            'Doctrine\ODM\MongoDB\Tests\Tools\TargetDocument',
            array()
        );

        $evm->addEventListener(Events::loadClassMetadata, $this->listener);

        $cm = $this->dm->getClassMetadata('Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetDocument');
        $meta = $cm->associationMappings;

        $this->assertSame('Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetDocument', $meta['refOne']['targetDocument']);
        $this->assertSame('Doctrine\ODM\MongoDB\Tests\Tools\TargetDocument', $meta['refMany']['targetDocument']);
        $this->assertSame('Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetDocument', $meta['embedOne']['targetDocument']);
        $this->assertSame('Doctrine\ODM\MongoDB\Tests\Tools\TargetDocument', $meta['embedMany']['targetDocument']);
    }
}

interface ResolveTargetInterface
{
    public function getId();
}

interface TargetInterface extends ResolveTargetInterface
{
}

/**
 * @ODM\Document
 */
class ResolveTargetDocument implements ResolveTargetInterface
{
    /**
     * @ODM\Id
     */
    private $id;

    /**
     * @ODM\ReferenceOne(targetDocument="Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetInterface")
     */
    private $refOne;

    /**
     * @ODM\ReferenceMany(targetDocument="Doctrine\ODM\MongoDB\Tests\Tools\TargetInterface")
     */
    private $refMany;

    /**
     * @ODM\EmbedOne(targetDocument="Doctrine\ODM\MongoDB\Tests\Tools\ResolveTargetInterface")
     */
    private $embedOne;

    /**
     * @ODM\EmbedMany(targetDocument="Doctrine\ODM\MongoDB\Tests\Tools\TargetInterface")
     */
    private $embedMany;

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

/**
 * @ODM\Document
 */
class TargetDocument implements TargetInterface
{
    /**
     * @ODM\Id
     */
    private $id;

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

Test case: resolve target document listener


<?php
/**
 * Created by jacob.
 * User: jacob
 * Date: 16/5/20
 * Time: 下午8:31
 */
namespace Jacobcyl\AliOSS\Plugins;
use League\Flysystem\Config;
use League\Flysystem\Plugin\AbstractPlugin;
class PutRemoteFile extends AbstractPlugin
{
    /**
     * Get the method name.
     *
     * @return string
     */
    public function getMethod()
    {
        return 'putRemoteFile';
    }

    public function handle($path, $remoteUrl, array $options = []){
        $config = new Config($options);
        if (method_exists($this->filesystem, 'getConfig')) {
            $config->setFallback($this->filesystem->getConfig());
        }

        //Get file stream from remote url
        $resource = fopen($remoteUrl, 'r');

        return (bool)$this->filesystem->getAdapter()->writeStream($path, $resource, $config);
    }
}

Add plugin to upload file from remote url

Add plugin to upload file from remote url. Usage: Storage::putRemoteFile($storagePath, $remoteUrl, $options)


<?php

use Phinx\Migration\AbstractMigration;

class RemoveUniquenessFromPlayerToken extends AbstractMigration
{
    public function up()
    {
        $player = $this->table('player');

        $player->removeIndex(array('token'));
        $player->addIndex(array('token'));

        $player->save();
    }

    public function down()
    {
        $player = $this->table('player');

        $player->removeIndex(array('token'));
        $player->addIndex(array('token'), array('unique' => true));

        $player->save();
    }
}

Remove uniqueness from player token

Remove uniqueness from player token


<?php

namespace Fuel\Migrations;

class Alter_is_valid
{
    public function up()
    {
        \DBUtil::add_fields('reports', array(
            'is_valid' => array('type' => 'boolean'),
        ));
    }

    public function down()
    {
        \DBUtil::drop_fields('reports', array(
            'is_valid'
        ));
    }
}

Add is_valid flag to report

Add is_valid flag to report


<?php

/*
 * Mustache PHP Compiler
 *
 * This is a straight port of the ruby mustache compiler.
 *
 * (c) July 2011 - Manuel Odendahl - wesen@ruinwesen.com
 */

class Mustache {
  public function __construct() {
    $this->templatePath = ".";
    $this->templateExtension = "mustache";
    $this->raiseOnContextMiss = false;
  }

  public function render() {
  }

  /**
   * Given a file name and an optional context, attemps to load and
   * render the file as a template.
   **/
  public function renderFile($name, $context = array()) {
  }

  /**
   * Given a name, attemps to read a file and return the contents as a
   * string. The file is not rendered, so it might contain
   * {{mustaches}}.
   **/
  public static function __partial($name) {
    return file_get_contents($name);
  }

  /**
   * Override this in your subclass if you want to do fun things like
   * reading templates from a database. It will be rendered by the
   * context, so all you need to do is return a string.
   **/
  public function partial($name) {
    return static::__partial($name);
  }

  /** Memoization array for camelcasing. **/
  protected static $__camelizeHash = array();

  /**
   * camelcases a name to get a class name.
   **/
  public static function classify($name) {
    if (array_key_exists($name, self::$__camelizeHash)) {
      return self::$__camelizeHash[$name];
    }

    $orig = $name;

    $name = str_replace(array('-', '_'), ' ', $name);
    $name = ucwords($name);
    $name = ucfirst(str_replace(' ', '', $name));

    self::$__camelizeHash[$orig] = $name;

    return $name;
  }

  protected static $__uncamelizeHash = array();

  /**
   * Uncamelizes a string.
   **/
  public static function underscore($name) {
    if (array_key_exists($name, self::$__uncamelizeHash)) {
      return self::$__uncamelizeHash[$name];
    }

    $orig = $name;

    $name = lcfirst($name);
    $name = preg_replace("/([A-Z])/e", '"_".lcfirst("$1")', $name);
    self::$__uncamelizeHash[$orig] = $name;
    return $name;
  }
}

?>

Add beginning of mustache class implementation


<?php

declare (strict_types = 1);

namespace Crell\Document\Document\Test;

class AccessTest extends \PHPUnit_Framework_TestCase
{
    public function testHydrate()
    {
        $s = Super::create();
    }
}

class Super {
    protected $superProtected = 'Super protected';
    private $superPrivate = 'Super private';

    public static function create() : self {
        $c = new Child();

        print $c->superPrivate . PHP_EOL;
        print $c->superProtected . PHP_EOL;
        print $c->protected . PHP_EOL;
        //print $c->private . PHP_EOL;

        return $c;
    }
}

class Child extends Super {
    protected $protected = 'Child protected';
    private $private = 'Child private';
}

Add test to verfy PHP behavior.

Add test to verfy PHP behavior.


<?php
/**
 * @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
 *    Confidential and Proprietary. Any dissemination outside of Quicken Loans
 *    is strictly prohibited.
 */

namespace QL\Panthor\Slim;

use Slim\Slim;

/**
 * Simple proxy for Slim::halt
 */
class Halt
{
    /**
     * @type Slim
     */
    private $slim;

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

    /**
     * @see Slim::halt
     *
     * @param int $status
     * @param string $message
     */
    public function __invoke($status, $message = '')
    {
        return call_user_func_array([$this->slim, 'halt'], func_get_args());
    }
}

Add simple callable proxy for slim::halt


<?php

namespace Wanjee\Shuwee\AdminBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Wanjee\Shuwee\AdminBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'username',
                TextType::class,
                [
                    'label' => 'Username',
                    'required' => true,
                    'attr' => [
                        'autocomplete' => 'off',
                    ]
                ]
            )
            ->add(
                'plainPassword',
                PasswordType::class,
                [
                    'required' => false,
                    'mapped' => true,
                    'attr' => [
                        'autocomplete' => 'off',
                    ]
                ]
            )
            ->add(
                'roles',
                ChoiceType::class,
                [
                    'choices' => [
                        'Admin' => 'ROLE_ADMIN',
                        'Super admin' => 'ROLE_SUPER_ADMIN',
                    ],
                    'multiple' => true,
                    'expanded' => true,
                ]
            );
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => User::class,
            )
        );
    }
}

Add a default edit form for Shuwee users


<?php

function permute(string $entry, int $level = 0)
{
    static $num = 0;
    $length = strlen($entry);

    if ($level === $length) {
        print(++$num.". $entry\n");
        return;
    }

    for($ix = $level; $ix < $length; $ix++) {
        $entry = swap($entry, $level, $ix);
        permute($entry, $level + 1);
    }
}

function swap(string $input, int $fromIndex, int $toIndex) : string
{
    $swapFrom = $input[$fromIndex];
    $input[$fromIndex] = $input[$toIndex];
    $input[$toIndex] = $swapFrom;

    return $input;
}

permute('abc');

Add permutation algo in PHP language

Add permutation algo in PHP language


<?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 OpenConext\EngineBlockBundle\Exception;

use RuntimeException;

final class StuckInAuthenticationLoopException extends RuntimeException
{
}

Add custom exception for when stuck in authentication loop


<?php
/**
 * Plugin Name: E2E Tests Proxy Credentials Plugin
 * Plugin URI:  https://github.com/google/site-kit-wp
 * Description: Utility plugin for forcing proxy OAuth credentials during E2E tests.
 * Author:      Google
 * Author URI:  https://opensource.google.com
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

add_filter(
	'googlesitekit_oauth_secret',
	function () {
		return array(
			'web' => array(
				'client_id'     => '1234567890-asdfasdfasdfasdfzxcvzxcvzxcvzxcv.apps.sitekit.withgoogle.com',
				'client_secret' => 'x_xxxxxxxxxxxxxxxxxxxxxx',
			),
		);
	}
);

Add proxy credentials e2e plugin.

Add proxy credentials e2e plugin.


<?php

/*
 * Copyright (C) 2013 Kolibre
 *
 * This file is part of Kolibre-KADOS.
 * Kolibre-KADOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * at your option) any later version.
 *
 * Kolibre-KADOS 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Kolibre-KADOS. If not, see <http://www.gnu.org/licenses/>.
 */

$includePath = dirname(realpath(__FILE__)) . '/../../../include/types';
set_include_path(get_include_path() . PATH_SEPARATOR . $includePath);

require_once('logOffResponse.class.php');

class logOffResponseTest extends PHPUnit_Framework_TestCase
{
    /**
     * @group logOffResponse
     * @group validate
     */
    public function testLogOffResult()
    {
        $instance = new logOffResponse();
        $this->assertFalse($instance->validate());
        $this->assertContains('logOffResponse.logOffResult', $instance->getError());
        $instance->logOffResult = 'logOffResult';
        $this->assertFalse($instance->validate());
        $this->assertContains('logOffResponse.logOffResult', $instance->getError());
        $instance->logOffResult = true;
        $this->assertTrue($instance->validate());
    }
}

?>

Add unit tests for logOffResponse class

Add unit tests for logOffResponse class


<?php

use Ob\CampaignBundle\Utils\Snapshot;

class SnapshotTest extends \PHPUnit_Framework_TestCase
{
    public function test_render_image()
    {
        $binaryPath = '/usr/local/bin/wkhtmltoimage';

        if (!file_exists($binaryPath)) {
            $this->markTestSkipped(
                'The wkhtmltoimage binary is not available.'
            );
        }

        $html = '
bar
';

        $snappy = new Snapshot('/tmp/', $binaryPath);

        $file = $snappy->render($html);

        $this->assertFileExists('/tmp/' . $file);
    }
}

Add the snapshot util test suite

Add the snapshot util test suite


<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\Assembly;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class AssemblyTest extends TestCase
{
    use DatabaseMigrations;

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

        // Create two test assemblies.
        $chamber = factory(Assembly::class)->create([
            'id' => 'k',
            'name_en' => 'Chamber of Representatives',
            'name_fr' => 'Chambre des représentants',
            'name_nl' => 'Kamer van Volksvertegenwoordigers',
        ]);
        $senate = factory(Assembly::class)->create([
            'id' => 's',
            'name_en' => 'Senate',
            'name_fr' => 'Sénat',
            'name_nl' => 'Senaat',
        ]);
    }

    /** @test */
    function can_get_the_list_of_assemblies_as_json()
    {
        // Make the request.
        $response = $this->get('/assemblies', [
            'accept' => 'application/json',
        ]);

        // Verify the response.
        $response
            ->assertStatus(Response::HTTP_OK)
            ->assertContentType('application/json')
            ->assertContentEquals(__DIR__.'/fixtures/assemblies.json');
    }

    /** @test */
    function can_get_the_list_of_assemblies_as_csv()
    {
        // Make the request.
        $response = $this->get('/assemblies', [
            'accept' => 'text/csv',
        ]);

        // Verify the response.
        $response
            ->assertStatus(Response::HTTP_OK)
            ->assertContentType('text/csv')
            ->assertContentEquals(__DIR__.'/fixtures/assemblies.csv');
    }

    /** @test */
    function can_get_the_list_of_assemblies_as_html()
    {
        // Make the request.
        $response = $this->get('/assemblies', [
            'accept' => 'text/html',
        ]);

        // Verify the response.
        $response
            ->assertStatus(Response::HTTP_OK)
            ->assertContentType('text/html')
            ->assertSeeText('Chambre des représentants')
            ->assertSeeText('Sénat');
    }

    /** @test */
    function can_get_the_list_of_assemblies_as_xml()
    {
        // Make the request.
        $response = $this->get('/assemblies', [
            'accept' => 'text/xml',
        ]);

        // Verify the response.
        $response
            ->assertStatus(Response::HTTP_OK)
            ->assertContentType('text/xml')
            ->assertContentEquals(__DIR__.'/fixtures/assemblies.xml');
    }
}

Add tests for getting the list of assemblies in several formats


<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  foreach (apache_request_headers() as $header => $value)
    echo $header . ': ' . $value . PHP_EOL;

  exit;
}
?>
<!doctype html>

Fetching self...

Test case to see what headers fetch() sends


<?php
function pfsense_www_class_autoloader($classname) {
	// Convert classname to match filename conventions
	$filename = str_replace('_', '/', $classname);

	// Build the full path, load it if it exists
	$filepath = "classes/$filename.class.php";
	if (file_exists($filepath)) {
		require_once($filepath);
	}
}
spl_autoload_register('pfsense_www_class_autoloader');

<?php
function pfsense_www_class_autoloader($classname) {
	// Convert classname to match filename conventions
	$filename = str_replace('_', '/', $classname);

	// Build the full path, load it if it exists
	$filepath = "/usr/local/www/classes/$filename.class.php";
	if (file_exists($filepath)) {
		require_once($filepath);
	}
}
spl_autoload_register('pfsense_www_class_autoloader');

Add full classpath to autoloader so that packages can run from their own directories.


<?php

class ApiFastTest extends TestCase
{
	protected $baseUrl = '';

	/**
	 * ApiFastTest constructor.
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * A basic functional test example.
	 *
	 * @return void
	 */
	public function testEmotes()
	{
		// WoTlk
		$this->json('GET', '/api/v1/dbc/emotes/')->seeJson(
			["id" => 0, "emote" => "ONESHOT_NONE"]
		);

		$this->json('GET', '/api/v1/dbc/emotes/3')->seeJson(
			["id" => 3, "emote" => "ONESHOT_WAVE(DNR)"]
		);

		// Wod
		$this->json('GET', '/api/v1/dbc/emotes/?version=wod')->seeJson(
			["id" => 577, "emote" => "ONESHOT_ATTACK1H"]
		);

		$this->json('GET', '/api/v1/dbc/emotes//?version=wod')->seeJson(
			["id" => 619, "emote" => "STATE_PARRY_UNARMED"]
		);
	}
}

Add tests for Emotes route.

Add tests for Emotes route.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add candidacy step 6 form type

Add candidacy step 6 form type


<?php
// Service
require_once('./json.php');

class ItemJson {

  /*
    This will retrieve a list of items stored in the item json resource.

    parameters - none
    return
      array - successfully retrieved list of items
      1 - resource list not found, internal server error.
  */
  public static function list () {
    // Retrieve item resources.
    $items = Json::get('item', null);

    // If item resource is not avaiable, internal server error.
    if ($items == 1)
      return 1;

    // Return items.
    return $items;
  }

  /*
    This will retrieve an item from the item json resource using an id.

    parameters
      $id - the id of the item. *required
    return
      array - successfully retrieved list of items
      1 - resource list not found, internal server error.
      2 - item not found, client error.
  */
  public static function get ($id) {
    // Retrieve item resources.
    $item = Json::get('item', $id);

    // If item resource is not avaiable, internal server error.
    if ($item == 1)
      return 1;
    if ($item == 2)
      return 2;

    // Item found.
    return $item;
  }

  /*
    This will save an item to the json storage file.
    The item email must be unique, if not, it will return an error.

    parameters
      $item (Item) - must be complete

    return
      0 - successful save.
      1 - resource not available, internal error.
      2 - item with email already exists, client error.
      3 - item with id already exists, internal error.

  */
  public static function save ($newItem) {
    // Retrieve item resources.
    $items = Json::get('item', null);

    // If item resource is not avaiable, internal server error.
    if ($items == 1)
      return 1;

    // Iterate through items to check if it already exists
    foreach ($items as $item) {
      // If item name already exists, return error 2.
      if ($item['name'] == $newItem['name'])
        return 2;
    }

    // If unique, save it.
    $save = Json::save('item', $newItem);

    // If id already exists, internal error.
    if ($save == 2)
      return 3;

    return 0;
  }

  /*
    This will update an item to the json storage file.
    The item must exist, if not, it will return an error.

    parameters
      $item (Item) - must be complete

    return
      0 - successful save.
      1 - resource not available, internal error.
      2 - item with id does not exist, client error.
  */
  public static function update ($item) {
    // Retrieve item resources.
    $list = Json::update('item', $item);

    // If resource not found.
    if ($list == 1)
      return 1;
    // If object not found.
    if ($list == 2)
      return 2;

    // If save was successful.
    return 0;
  }
}
?>

Fix ItemJson to accomodate Json class changes


<?php

$verb = strtolower($_SERVER['REQUEST_METHOD']);

function output($data) {
	echo json_encode([
			"result" => $data
		]);
}

header('Content-Type: application/json');

$users = [
			[
				"id" => 0,
				"name" => "Will McKenzie",
				"email" => "will@komododigital.co.uk"
			],
			[
				"id" => 1,
				"name" => "Alan Mitchell",
				"email" => "alan@komododigital.co.uk"
			]
	];

if (preg_match('/^\/users$/', $_SERVER["REQUEST_URI"])) {

	switch ($verb) {
		case 'get':
			output($users);
			break;
	}

} else {
    echo "
Siesta Test API
";
}

Add basic api server for test purposes

Add basic api server for test purposes


<?php

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

class AddVariantsColumnToMediaTable extends Migration
{
	public function up()
	{
		Schema::table('media', function (Blueprint $table) {
			$table->text('variants')->nullable()->after('height');
		});
	}

	public function down()
	{
		Schema::table('media', function (Blueprint $table) {
			$table->dropColumn('variants');
		});
	}
}

Add variants to media table (for storing different variations of images).


<?php

/**
 * SQLayerExampleTable
 * Example of SQLayerTable implemented as singleton
 *
 * This class will reference a table called 'example' within a database called 'example'.
 * Reference the singleton by calling: SQLayerExampleTable::tbl();
 *
 * @category   Frameworks
 * @package    SQLayer
 * @author     Roderic Linguri <rlinguri@mac.com>
 * @copyright  2016 Digices, Inc.
 * @license    https://opensource.org/licenses/MIT
 * @version    0.0.5
 * @link       http://www.sqlayer.com
 */

class SQLayerExampleTable extends SQLayerTable
{

    /** *obj* table singleton **/
    protected static $tbl;

    /** @method tbl getter
      * @param  void
      * @return *obj* of this class **/
    public static function tbl()
    {
        if (!isset(self::$tbl)) {
            self::$tbl = new self();
        }
        return self::$tbl;
    }

    /** @method constructor
      * @param  void
      * @return void **/
    public function __construct()
    {
        $this->dbo =  SQLayerExampleDbo::dbo();
        $this->tableName = 'example';
        $this->columns = array(
            new SQLayerColumn('k','key','Key','INTEGER PRIMARY KEY',5),
            new SQLayerColumn('s','symbol','Symbol','TEXT',8),
            new SQLayerColumn('n','name','Name','TEXT',80)
        );
    }

}

Create example of extended Table class.

Create example of extended Table class.


<?php

declare(strict_types=1);

namespace Tests\Regis\BitbucketContext\Application\CommandHandler\Inspection;

use PHPUnit\Framework\TestCase;
use Regis\BitbucketContext\Application\Command;
use Regis\BitbucketContext\Application\CommandHandler;
use Regis\BitbucketContext\Application\Reporter;
use Regis\BitbucketContext\Domain\Entity\PullRequestInspection;
use Regis\BitbucketContext\Domain\Entity\Report;
use Regis\BitbucketContext\Domain\Entity\Violation;
use Regis\BitbucketContext\Domain\Entity\Repository;
use Regis\BitbucketContext\Domain\Model\PullRequest;
use Regis\BitbucketContext\Domain\Model\ReviewComment;

class SendViolationsAsCommentsTest extends TestCase
{
    private $reporter;
    /** @var CommandHandler\Inspection\SendViolationsAsComments */
    private $handler;

    public function setUp()
    {
        $this->reporter = $this->createMock(Reporter::class);

        $this->handler = new CommandHandler\Inspection\SendViolationsAsComments($this->reporter);
    }

    public function testViolationsAreTransferedToTheReporter()
    {
        $repository = $this->createMock(Repository::class);
        $pullRequest = $this->createMock(PullRequest::class);
        $inspection = $this->createMock(PullRequestInspection::class);
        $report = $this->createMock(Report::class);

        $violation1 = $this->createMock(Violation::class);
        $violation2 = $this->createMock(Violation::class);

        $inspection->method('getReport')->willReturn($report);
        $inspection->method('hasReport')->willReturn(true);
        $inspection->method('getRepository')->willReturn($repository);
        $inspection->method('getPullRequest')->willReturn($pullRequest);
        $report->method('violations')->willReturn(new \ArrayIterator([$violation1, $violation2]));

        $this->reporter->expects($this->exactly(2))
            ->method('report')
            ->withConsecutive(
                [$repository, $this->isInstanceOf(ReviewComment::class), $pullRequest],
                [$repository, $this->isInstanceOf(ReviewComment::class), $pullRequest]
            );

        $command = new Command\Inspection\SendViolationsAsComments($inspection);

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

    public function testAnInspectionWithNoReportTriggersNothing()
    {
        $inspection = $this->createMock(PullRequestInspection::class);

        $inspection->method('hasReport')->willReturn(false);

        $inspection->expects($this->never())->method('getReport');
        $this->reporter->expects($this->never())->method('report');

        $command = new Command\Inspection\SendViolationsAsComments($inspection);

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

Test the bitbucket send violations command handler


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core;

/**
 * Loads and keeps track of Jivoo modules.
 * @property-read \Jivoo\AccessControl\AccessControl $AccessControl
 * @property-read \Jivoo\ActiveModels\ActiveModels $ActiveModels
 * @property-read \Jivoo\Assets\Assets $Assets
 * @property-read \Jivoo\Console\Console $Console
 * @property-read \Jivoo\Content\Content $Content
 * @property-read \Jivoo\Controllers\Controllers $Controllers
 * @property-read \Jivoo\Databases\Databases $Databases
 * @property-read \Jivoo\Extensions\Extensions $Extensions
 * @property-read \Jivoo\Helpers\Helpers $Helpers
 * @property-read \Jivoo\Jtk\Jtk $Jtk
 * @property-read \Jivoo\Migrations\Migrations $Migrations
 * @property-read \Jivoo\Models\Models $Models
 * @property-read \Jivoo\Routing\Routing $Routing
 * @property-read \Jivoo\Setup\Setup $Setup
 * @property-read \Jivoo\Snippets\Snippets $Snippets
 * @property-read \Jivoo\Themes\Themes $Themes
 * @property-read \Jivoo\View\View $View
 */
class ModuleLoader implements \ArrayAccess {

  public function load($module) {
    if (!isset($this->m->$module)) {
      $this->triggerEvent('beforeLoadModule', new LoadModuleEvent($this, $module));
      if (!isset($this->imports[$module]))
        $this->import($module);
      $class = $this->imports[$module];
      if (isset($this->optionalDependencies[$module])) {
        foreach ($this->optionalDependencies[$module] as $dependency) {
          if (isset($this->imports[$dependency]))
            $this->load($dependency);
        }
      }
      Lib::assumeSubclassOf($class, 'Jivoo\Core\LoadableModule');
      $this->m->$module = new $class($this);
      $this->triggerEvent('afterLoadModule', new LoadModuleEvent($this, $module, $this->m->$module));
      $this->m->$module->afterLoad();
      if (isset($this->waitingCalls[$module])) {
        foreach ($this->waitingCalls[$module] as $tuple) {
          list($method, $args) = $tuple;
          call_user_func_array(array($this->m->$module, $method), $args);
        }
      }
    }
    return $this->m->$module;
  }
}

Add new module loader class.

Add new module loader class.


<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Zed\Transfer;

use Spryker\Shared\Application\ApplicationConstants;
use Spryker\Shared\Config\Config;
use Spryker\Zed\Transfer\TransferConfig as SprykerTransferConfig;

class TransferConfig extends SprykerTransferConfig
{

    /**
     * @return array
     */
    public function getSourceDirectories()
    {
        $directories = parent::getSourceDirectories();
        $directories[] = Config::get(ApplicationConstants::APPLICATION_SPRYKER_ROOT) . '/../../code-generator/src/*/Shared/*/Transfer/';

        return $directories;
    }

}

Add path to new bundle transfer definitions. Project only.


<?php
namespace pyd\testkit;

use yii\base\InvalidParamException;
use pyd\testkit\Testkit;
use pyd\testkit\interfaces\InterfaceTestEventObserver;

/**
 * Listen to the test events and inform registered observers when they occur.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class TestEventMediator extends \yii\base\Object
{
    /**
     * Test event observers.
     * @see attach()
     * @var array each key should be an event name and its value an array of
     * observers {@see \pyd\testkit\interfaces\InterfaceTestEventObserver}
     */
    protected $observers;

    /**
     * Attach an observer to a test event.
     * @param string $eventName
     * @param \pyd\testkit\interfaces\InterfaceTestEventObserver $observer
     */
    public function attach($eventName, InterfaceTestEventObserver $observer)
    {
        $this->observers[$eventName][spl_object_hash($observer)] = $observer;
    }

    /**
     * Detach an observer from a test event.
     * @param string $eventName
     * @param pyd\testkit\interfaces\InterfaceTestEventObserver $observer
     * @throws InvalidParamException observer is not attached to this test event
     */
    public function detach($eventName, InterfaceTestEventObserver $observer)
    {
        unset($this->observers[$eventName][spl_object_hash($observer)]);
    }

    /**
     * Inform observers attached to a test event.
     * @param string $eventName
     * @param mixed $data data to be passed to the event handler of the observer
     */
    public function trigger($eventName, $data = null)
    {
        if (isset($this->observers[$eventName])) {
            foreach ($this->observers[$eventName] as $observer) {
                $observer->handleEvent($eventName, $data);
            }
        }
    }

    /**
     * Set observers.
     * This methods is meant to initialize the {@see $observers} property at
     * configuration time without observer instances but with their component IDs.
     * @param array $observers each key should be an event name and its value an
     * array of observers i.e. an instance implementing
     * {@see \pyd\testkit\interfaces\InterfaceTestEventObserver} or its
     * component ID
     */
    public function setObservers(array $observers)
    {
        $testkitApp = Testkit::$app;

        foreach ($observers as $eventName => $observers) {

            foreach ($observers as $observer) {

                if (is_string($observer)) {
                    if ($testkitApp->has($observer)) {
                        $observer = $testkitApp->get($observer);
                    } else {
                        throw new InvalidParamException("Unknown component ID  '$observer'.");
                    }
                }
                $this->attach($eventName, $observer);
            }
        }
    }
}

Create a test event mediator class Its responsability is to inform observers when a test event occurs.


<?php

namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class PolygonType extends Type
{
    const FIELD = 'polygon';

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'POLYGON';
    }

    public function canRequireSQLConversion()
    {
        return true;
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        preg_match('/POLYGON\(\((.*)\)\)/', $value, $matches);
        if ( !isset($matches[1]) )
            throw new Exception('No Polygon Points');
        return $matches[1];
    }

    public function convertToPHPValueSQL($sqlExpr, $platform)
    {
        return sprintf('AsText(%s)', $sqlExpr);
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return sprintf('POLYGON((%s))', $value);
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return sprintf('ST_PolygonFromText(%s)', $sqlExpr);
    }

    public function getName()
    {
        return self::FIELD;
    }
}

Add polygon type to Berberlei MySQL Types


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

/**
 * Poll model
 *
 * @author Victor Michnowicz
 * @category Modules
 */
class Poll_m extends MY_Model {}

Add new model cuz admin page fails without it


<?php

use yii\db\Schema;
use yii\db\Migration;

class m141218_102439_create_instructor_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%instructor}}', [
            'id' => Schema::TYPE_PK,
            'first_name' => Schema::TYPE_STRING . ' NOT NULL',
            'last_name' => Schema::TYPE_STRING . ' NOT NULL',
            'middle_name' => Schema::TYPE_STRING . ' NOT NULL',
        ], $tableOptions);

        $this->createIndex('NAME', '{{%instructor}}', ['first_name', 'last_name', 'middle_name'], true);
    }

    public function down()
    {
        $this->dropIndex('NAME', '{{%instructor}}');

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

Add migration for Instructor entity

Add migration for Instructor entity


<?php

/*
 * This file is part of the composer-changelogs project.
 *
 * (c) Loïck Piera <pyrech@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pyrech\ComposerChangelogs\tests;

use Pyrech\ComposerChangelogs\Version;

class VersionTest extends \PHPUnit_Framework_TestCase
{
    /** @var Version */
    private $SUT;

    public function test_it_keep_version_formats()
    {
        $this->SUT = new Version('v1.0.0.0', 'v1.0.0', 'v1.0.0');

        $this->assertSame('v1.0.0.0', $this->SUT->getName());
        $this->assertSame('v1.0.0', $this->SUT->getPretty());
        $this->assertSame('v1.0.0', $this->SUT->getFullPretty());

        $this->SUT = new Version('v.1.0.9999999.9999999-dev', 'dev-master', 'dev-master 1234abc');

        $this->assertSame('v.1.0.9999999.9999999-dev', $this->SUT->getName());
        $this->assertSame('dev-master', $this->SUT->getPretty());
        $this->assertSame('dev-master 1234abc', $this->SUT->getFullPretty());
    }

    public function test_it_detects_dev_version()
    {
        $this->SUT = new Version('v1.0.0.0', 'v1.0.0', 'v1.0.0');

        $this->assertFalse($this->SUT->isDev());

        $this->SUT = new Version('v.1.0.9999999.9999999-dev', 'dev-master', 'dev-master 1234abc');

        $this->assertTrue($this->SUT->isDev());

        $this->SUT = new Version('dev-fix/issue', 'dev-fix/issue', 'dev-fix/issue 1234abc');

        $this->assertTrue($this->SUT->isDev());
    }
}

Add tests for Version class

Add tests for Version class


<?php

namespace Kunstmaan\FormBundle\Entity\PageParts;

use Kunstmaan\AdminBundle\Helper\ClassLookup;
use Kunstmaan\FormBundle\Entity\FormAdaptorInterface;
use Kunstmaan\PagePartBundle\Entity\AbstractPagePart;

use Doctrine\ORM\Mapping as ORM;

/**
 * Abstract version of a form page part
 */
abstract class AbstractFormPagePart extends AbstractPagePart implements FormAdaptorInterface
{

    const ERROR_REQUIRED_FIELD = "field.required";

    /**
     * The label
     *
     * @ORM\Column(type="string", nullable=true)
     */
    protected $label;

    /**
     * Returns a unique id for the current page part
     *
     * @return string
     */
    public function getUniqueId()
    {
        return  str_replace('\\', ':', ClassLookup::getClass($this)) . $this->id; //TODO
    }

    /**
     * Set the label used for this page part
     *
     * @param int $label
     */
    public function setLabel($label)
    {
        $this->label = $label;
    }

    /**
     * Get the label used for this page part
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Returns the view used in the backend
     *
     * @return string
     */
    public function getAdminView()
    {
        return "KunstmaanFormBundle:AbstractFormPagePart:admin-view.html.twig";
    }

}

<?php

namespace Kunstmaan\FormBundle\Entity\PageParts;

use Kunstmaan\UtilitiesBundle\Helper\ClassLookup;
use Kunstmaan\FormBundle\Entity\FormAdaptorInterface;
use Kunstmaan\PagePartBundle\Entity\AbstractPagePart;

use Doctrine\ORM\Mapping as ORM;

/**
 * Abstract version of a form page part
 */
abstract class AbstractFormPagePart extends AbstractPagePart implements FormAdaptorInterface
{

    const ERROR_REQUIRED_FIELD = "field.required";

    /**
     * The label
     *
     * @ORM\Column(type="string", nullable=true)
     */
    protected $label;

    /**
     * Returns a unique id for the current page part
     *
     * @return string
     */
    public function getUniqueId()
    {
        return  str_replace('\\', ':', ClassLookup::getClass($this)) . $this->id; //TODO
    }

    /**
     * Set the label used for this page part
     *
     * @param int $label
     */
    public function setLabel($label)
    {
        $this->label = $label;
    }

    /**
     * Get the label used for this page part
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Returns the view used in the backend
     *
     * @return string
     */
    public function getAdminView()
    {
        return "KunstmaanFormBundle:AbstractFormPagePart:admin-view.html.twig";
    }

}

Use new namespace for ClassLookup

Use new namespace for ClassLookup


<?php

use Phinx\Migration\AbstractMigration;

class Format 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()
    {
        $this->table("format")
            ->addColumn("name", "string", ["limit" => 100])
            ->addColumn("collection", "string", ["limit" => 255])
            ->addColumn("template_id", "integer")
            ->create();

        $this->table("template")
            ->addColumn("name", "string", ["limit" => 100])
            ->create();

        $this->table("field")
            ->addColumn("name", "string", ["limit" => 255])
            ->addColumn("field_name", "string", ["limit" => 255])
            ->addColumn("type", "string", ["limit" => 50])
            ->addColumn("format_id", "integer", ["null" => true])
            ->addColumn("template_id", "integer", ["null" => true])
            ->create();
    }
}

Create migration for format related tables


<?php

namespace Jivoo\Core;

class AppConfigTest extends \Codeception\TestCase\Test {

  /**
   *
   * @var \UnitTester
   */
  protected $tester;

  protected function _before() {}

  protected function _after() {}

  public function testConstruction() {
  }

}

Add app config unit test.

Add app config unit test.


<?php namespace Pingpong\Modules\Commands;

use Illuminate\Console\Command;
use Pingpong\Modules\Generators\ModuleGenerator;
use Symfony\Component\Console\Input\InputArgument;

class MakeCommand extends Command {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate new module.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        with(new ModuleGenerator($this->argument('name')))
            ->setFilesystem($this->laravel['files'])
            ->setModule($this->laravel['modules'])
            ->setConfig($this->laravel['config'])
            ->setConsole($this)
            ->generate();
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The name of module will be created.'),
        );
    }

}

<?php namespace Pingpong\Modules\Commands;

use Illuminate\Console\Command;
use Pingpong\Modules\Generators\ModuleGenerator;
use Symfony\Component\Console\Input\InputArgument;

class MakeCommand extends Command {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate new module.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $names = $this->argument('name');

        foreach ($names as $name)
        {
            with(new ModuleGenerator($name))
                ->setFilesystem($this->laravel['files'])
                ->setModule($this->laravel['modules'])
                ->setConfig($this->laravel['config'])
                ->setConsole($this)
                ->generate();
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::IS_ARRAY, 'The names of modules will be created.'),
        );
    }

}

Allow to create multiple modules using module:make command


<?php
namespace OC\Migrations;

use OCP\Migration\ISimpleMigration;
use OCP\Migration\IOutput;

/**
 * Split shareapi_enforce_links_password config key into 3 different keys for read-only,
 * read & write and write-only links
 */
class Version20180123131835 implements ISimpleMigration {

	/**
	 * @param IOutput $out
	 */
	public function run(IOutput $out) {
		$config = \OC::$server->getConfig();
		$enforceLinks = $config->getAppValue('core', 'shareapi_enforce_links_password', null);
		if ($enforceLinks !== null) {
			$config->setAppValue('core', 'shareapi_enforce_links_password_read_only', $enforceLinks);
			$config->setAppValue('core', 'shareapi_enforce_links_password_read_write', $enforceLinks);
			$config->setAppValue('core', 'shareapi_enforce_links_password_write_only', $enforceLinks);
		}
		$config->deleteAppValue('core', 'shareapi_enforce_links_password');
	}
}

Add migration for the configuration key

Add migration for the configuration key


<?php

namespace App\Models\Items\Attributes;

use Illuminate\Database\Eloquent\Model;

/**
 * This is the item's category model class.
 *
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property int $code
 */
class VehicleCategory extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'item_categories';

    /**
     * The primary key column.
     *
     * @var string
     */
    protected $primaryKey = 'id';
}

Add the item category model

Add the item category model


<?php
namespace Bitrix24\Presets;

class Events
{
	/**
	 * event code when bitrix24 application has uninstall
	 */
	const ON_APP_UNINSTALL = 'ONAPPUNINSTALL';
	/**
	 * event code when bitrix24 application update
	 */
	const ON_APP_UPDATE = 'ONAPPUPDATE';
	/**
	 * event code when bitrix24 application payment
	 */
	const ON_APP_PAYMENT = 'ONAPPPAYMENT';
	/**
	 * event code when task add in bitrix24
	 */
	const ON_TASK_ADD = 'ONTASKADD';
	/**
	 * event code when task in bitrix24 has update
	 */
	const ON_TASK_UPDATE = 'ONTASKUPDATE';
	/**
	 * event code when task in bitrix24 has delete
	 */
	const ON_TASK_DELETE = 'ONTASKDELETE';
	/**
	 * event code when new user in bitrix24 has added
	 */
	const ON_USER_ADD = 'ONUSERADD';
}

Add class Bitrix24\Presets\Events for Bitrix24 event codes


<?php

namespace Orbt\StyleMirror\Css;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Orbt\ResourceMirror\ResourceMirror;
use Orbt\ResourceMirror\Event\ResourceMaterializeEvent;
use Orbt\ResourceMirror\Event\ResourceEvents;
use Orbt\ResourceMirror\Resource\MaterializedResource;

/**
 * A resource event listener that fetches all linked resources in CSS.
 */
class LinkedResourceFetcher implements EventSubscriberInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            ResourceEvents::MATERIALIZE => 'onResourceMaterialize',
        );
    }

    /**
     * @var ResourceScanner
     */
    protected $scanner;

    /**
     * @var ResourceMirror
     */
    protected $mirror;

    /**
     * Creates a linked fetcher.
     */
    public function __construct(ResourceScanner $scanner, ResourceMirror $mirror)
    {
        $this->scanner = $scanner;
        $this->mirror = $mirror;
    }

    /**
     * Scans all linked resources.
     */
    public function onResourceMaterialize(ResourceMaterializeEvent $e)
    {
        /** @var $resource MaterializedResource */
        $resource = $e->getResource();

        // Only scan resources with .css extension.
        if (preg_match('/\.css$/i', $resource->getPath())) {
            $this->scanner->scan($resource, $resource->getContent());
            $collection = $this->scanner->getQueue()->flush();
            // Materialize non-existing resources.
            foreach ($collection as $linkedResource) {
                if (!$this->mirror->exists($linkedResource)) {
                    $this->mirror->materialize($linkedResource);
                }
            }
        }
    }
}

Add linked resource fetcher to subscribe to the resource mirror.


    <?php
    /* translators: %s: Name of current post */
    echo apply_filters('the_excerpt', get_the_excerpt());
//                    the_content(sprintf(
//                                    __('Continue reading "%s"', 'twentyseventeen'), get_the_title()
//                    ));

    wp_link_pages(array(
        'before' => '
' . sprintf('
%s
', __('Page', 'twentyseventeen')),
        'after' => '
',
        'link_before' => '',
        'link_after' => '',
    ));
    ?>

Add separate snippet for excerpt content


<?php

    if (!function_exists('loadClass'))
    {
        function loadClass($className, $package='library', $vendors=[APP_PATH, SYSTEM_PATH])
        {
            static $instance = array();

            if (!is_array($vendors))
            {
                $vendors = array($vendors);
            }

            $className = strtolower($className);
            $class = false;

            if (isset($instance[$package]) && isset($instance[$package][$className]))
            {
                return $instance[$package][$className];
            }

            foreach ($vendors as $vendor)
            {
                $vendor = rtrim(strtolower($vendor), '/') . '/';

                if (file_exists($vendor . $package . '/' . $className . '.php'))
                {
                    include ($vendor . $package . '/' . $className . '.php');
                    $class = $className;
                    break;
                }
            }

            if ($class === false)
            {
                exit('Class "'.$className.'" is not found on "'.$package.'" package.');
            }

            $class = new $class();
            $instance[$package][$className] = $class;
            return $class;
        }
    }

    if (!function_exists('isLoaded'))
    {
        function isLoaded($package='', $name='')
        {
            static $loaded = array();

            if ($package === '' && $name === '')
            {
                return $loaded;
            }

            $loaded[$package][$name] = strtolower($name);
        }
    }

?>

Add common function to load class and it's necessary file...


<?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 duxet\RethinkDB\Schema;

use Illuminate\Database\Schema\Grammars\Grammar as BaseGrammar;

/**
 * Class Grammar
 *
 * @package Moloquent\Schema
 */
class Grammar extends BaseGrammar {
}

Fix issue supportsSchemaTransactions() on null

got this issue while fixing existing issue fix this issue
Call to a member function supportsSchemaTransactions() on null
by adding Grammar.php and editing Connection.php


<?php
/**
 * Serialized - PHP Library for Serialized Data
 *
 * Copyright (C) 2010  Tom Klingenberg
 *
 * 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 in a file called COPYING. If not, see
 * <http://www.gnu.org/licenses/> and please report back to the original
 * author.
 *
 * @author Tom Klingenberg <http://lastflood.com/>
 * @version 0.0.2
 * @package Tests
 */
Namespace Serialized;

require_once(__DIR__.'/TestCase.php');

class TestCaseTest extends TestCase
{
	/**
	 * TestCase::hexDump() is currently dead code (0.0.2)
	 * but kept as it is of use for debugging.
	 */
	public function testHexDump()
	{
		$string = 'Self Test';
		$expected = '53 65 6c 66 20 54 65 73 74';
		$actual = $this->hexDump($string);
		$this->assertSame($expected, $actual);
	}
}

ADD: Test for TestCase::hexDump() helper function.


<?php
function cmp($a, $b)
{
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

Sort an array by keys using a user-defined comparison function


<?php get_header(); ?>

	<?php if ( have_posts() ) : ?>

			<?php paginate_alphabetic_links( get_post_type() ); ?>

		<?php /* Start the Loop */ ?>
		<?php while ( have_posts() ) : the_post(); ?>

			<?php if ( DABC_Beer_Post_Type::POST_TYPE === get_post_type() ) : ?>

				<?php get_template_part( 'parts/beer-info' ); ?>

			<?php else : ?>

				<?php get_template_part( 'content', get_post_format() ); ?>

			<?php endif; ?>

		<?php endwhile; ?>

		<?php else : ?>
			<?php get_template_part( 'content', 'none' ); ?>

	<?php endif; // end have_posts() check ?>

	<?php /* Display navigation to next/previous pages when applicable */ ?>
	<?php if ( function_exists('brewtah_pagination') ) { brewtah_pagination(); } else if ( is_paged() ) { ?>

<?php next_posts_link( __( '← Older posts', 'brewtah' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'brewtah' ) ); ?>

	<?php } ?>

	<?php get_sidebar(); ?>

<?php get_footer(); ?>

Add beer specific archive, with alphabetic paging controls.


<?php

$staq_path = substr( __DIR__, 0, strrpos( __DIR__, '/Staq/' ) + 5 );
require_once( $staq_path . '/util/tests.php' );
include_once( $staq_path . '/include.php' );

// CONTEXT
$path = \Staq\util\string_basename( __DIR__, 4 );
$app = new \Staq\Application( $path );
$app->start( );
new \Stack\Coco;

// TEST COLLECTION
$case = new \Staq\util\Test_Case( 'With the starter disabled', [
	'Extensions' => function( ) use ( $app, $path ) {
		return ( $app->get_extensions( ) == [ $path, 'Staq/view', 'Staq/ground' ] );
	}
] );

// RESULT
echo $case->to_html( );
return $case;

Add usecase to test an application with the starter disabled


<?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Base class for sections showing lists of notices
 *
 * 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);
}

define('NOTICES_PER_SECTION', 6);

/**
 * Base class for sections showing lists of notices
 *
 * These are the widgets that show interesting data about a person
 * group, or site.
 *
 * @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 PopularNoticeSection extends NoticeSection
{
    function getNotices()
    {
        $qry = 'SELECT notice.*, '.
          'sum(exp(-(now() - fave.modified) / %s)) as weight ' .
          'FROM notice JOIN fave ON notice.id = fave.notice_id ' .
          'GROUP BY fave.notice_id ' .
          'ORDER BY weight DESC';

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

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

        $notice = Memcached_DataObject::cachedQuery('Notice',
                                                    sprintf($qry, common_config('popular', 'dropoff')),
                                                    1200);
        return $notice;
    }

    function title()
    {
        return _('Popular notices');
    }

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

Add a section for popular notices sitewide


<?php
namespace Artesaos\Zenvia\Tests;

use Artesaos\Zenvia\Http\ResponseHandler;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use Psr\Http\Message\ResponseInterface;

class ResponseHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $response;

    public function setUp()
    {
        $body = '{"response": "example"}';
        $this->response = new Response(200,[],$body);
    }

    public function test_if_a_response_from_api_is_psr7()
    {
        $this->assertInstanceOf(ResponseInterface::class, $this->response);
    }

    public function test_if_a_response_can_be_converted_to_Array()
    {
        $convertedResponse = ResponseHandler::convert($this->response,'array');
        $this->assertTrue(is_array($convertedResponse));
    }

    public function test_if_a_response_can_be_converted_to_Obj()
    {
        $convertedResponse = ResponseHandler::convert($this->response,'obj');

        $this->assertInternalType('object', $this->response);
        $this->assertInstanceOf(\StdClass::class, $convertedResponse);
    }

    public function test_if_a_response_can_be_converted_to_Stream()
    {
        $convertedResponse = ResponseHandler::convert($this->response,'stream');
        $this->assertInstanceOf(Stream::class, $convertedResponse);
    }

    public function test_if_a_response_can_be_converted_to_SimpleXml()
    {
        $convertedResponse = ResponseHandler::convert($this->response,'simple_xml');

        $this->assertInstanceOf(\SimpleXmlElement::class,simplexml_load_string($convertedResponse));
        $this->assertEquals('example',simplexml_load_string($convertedResponse)->response);
    }

    public function test_if_a_exception_is_throw_on_convert_to_invalid_format()
    {
        $this->setExpectedException(\InvalidArgumentException::class,'Format invalid_format is not supported');

        $convertedResponse = ResponseHandler::convert($this->response,'invalid_format');
    }
}

Add tests for validate response types

Add tests for validate response types


<?php

namespace Flarum\Core\Settings;

class CachedSettingsRepository implements SettingsRepository
{
    protected $inner;

    protected $isCached;

    protected $cache = [];

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

    public function all()
    {
        if (!$this->isCached) {
            $this->cache = $this->inner->all();
            $this->isCached = true;
        }

        return $this->cache;
    }

    public function get($key, $default = null)
    {
        if (array_key_exists($key, $this->cache)) {
            return $this->cache[$key];
        } else if (!$this->isCached) {
            return array_get($this->all(), $key, $default);
        }

        return $default;
    }

    public function set($key, $value)
    {
        $this->cache[$key] = $value;

        $this->inner->set($key, $value);
    }
}

Build a caching repository decorator for settings


<?php
function usage()
{
    die("\nUsage - clear admin user data: php clearAdminUserData.php <PartnerId> <partnerAdminEmail> <Are you sure : yes/no>\n\n".
        "FYI - Following this api the user and its login-data will be deleted without any trace.\n\n");
}
if($argc != 4 || $argv[3] !== "yes")
{
    return usage();
}

require("/opt/kaltura/app/alpha/scripts/bootstrap.php");

$partnerId = $argv[1];
$partnerAdminEmail = $argv[2];

//find userLoginData by login email and validate partner ID
$partner = PartnerPeer::retrieveByPK($partnerId);
if(!$partner || $partner->getAdminEmail()!==$partnerAdminEmail)
{
    die("\nWrong admin email supplied, expected {$partner->getAdminEmail()} found {$partnerAdminEmail}\n\n");
}

//get all admin users for the account
$adminUsers = Partner::getAdminLoginUsersList($partnerId);
foreach($adminUsers as $adminUser)
{
    $loginData = $adminUser->getLoginData();

    //Delete the kuser
    KalturaLog::log("{$argv[0]} Deleting kuser, puserId: {$adminUser->getPuserId()} id: {$adminUser->getId()}");
    $adminUser->delete();

    //Delete the login data
    KalturaLog::log("{$argv[0]} Deleting login data, id: {$loginData->getId()} login email: {$loginData->getLoginEmail()} ");
    $loginData->delete();
}

KalturaLog::log("{$argv[0]} Done removing all admin users from account: {$partnerId}");

PLAT-23626: Add script to clean admin users by partnerId


<?php

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

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

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

Add index on profile_id to races table

Add index on profile_id to races table


<?php

namespace React\Chatroulette;

use React\Socket\ConnectionInterface;

class TextAppTest extends \PHPUnit_Framework_TestCase
{
    private $appMock;
    private $app;

    public function setUp()
    {
        $this->appMock = $this->getMock('React\Chatroulette\AppInterface');
        $this->app = new TextApp($this->appMock);
    }

    /** @test */
    public function connectShouldDelegateToDecoratedApp()
    {
        $alice = new ConnectionStub();
        $alice->id = 'Alice';

        $this->appMock
            ->expects($this->once())
            ->method('connect')
            ->with($alice);

        $this->app->connect($alice);
    }

    /** @test */
    public function connectShouldGreetUser()
    {
        $alice = new ConnectionStub();
        $alice->id = 'Alice';

        $this->app->connect($alice);

        $this->assertConnectionData($alice, [
            'Hello Alice!',
        ]);
    }

    /** @test */
    public function connectionWaitEventShouldTriggerWaitMessage()
    {
        $alice = new ConnectionStub();
        $alice->id = 'Alice';

        $this->app->connect($alice);

        $alice->emit('wait');

        $this->assertConnectionData($alice, [
            'Hello Alice!',
            'Please wait until a partner connects.',
        ]);
    }

    /** @test */
    public function connectionPipeShouldTriggerTalkingToMessage()
    {
        $alice = new ConnectionStub();
        $alice->id = 'Alice';

        $bob = new ConnectionStub();
        $bob->id = 'Bob';

        $this->app->connect($alice);
        $this->app->connect($bob);

        $alice->pipe($bob)->pipe($alice);

        $this->assertConnectionData($alice, [
            'Hello Alice!',
            'You are now talking to Bob.',
        ]);

        $this->assertConnectionData($bob, [
            'Hello Bob!',
            'You are now talking to Alice.',
        ]);
    }

    private function assertConnectionData(ConnectionInterface $conn, $expected)
    {
        $data = implode("\n", $expected)."\n";
        $this->assertSame($data, $conn->data);
    }
}

Add unit tests for TextApp

Add unit tests for TextApp


<?php

// Feed it UUIDs from STDIN like this:
// % docker compose exec neo4j cypher-shell -u neo4j -p secret --format plain 'MATCH (n) RETURN n.uuid;'

namespace StrehleDe\TopicCards\Search;

use StrehleDe\TopicCards\Configuration\Configuration;

class SimpleReindexScript
{
    protected Configuration $configuration;

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

    public function reindex($stream): void
    {
        $cnt = 0;

        while (($line = fgets($stream, 4096)) !== false) {
            $uuid = trim($line, " \n\r\t\v\x00\"");

            if (empty($uuid)) {
                continue;
            }

            $cnt++;
            printf("%d: Indexing node <%s>\n", $cnt, $uuid);

            IndexUpdate::updateNode($uuid, $this->configuration);
        }
    }
}

Add simple Elasticsearch reindex script

Add simple Elasticsearch reindex script


<?php
namespace Grav;

// Ensure vendor libraries exist
$autoload = __DIR__ . '/vendor/autoload.php';
if (!is_file($autoload)) {
    throw new \RuntimeException("Please run: bin/grav install");
}

use Grav\Common\Grav;

// Register the auto-loader.
$loader = require_once $autoload;

if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
    throw new \RuntimeException(sprintf('You are running PHP %s, but Grav needs at least PHP %s to run.', $ver, $req));
}

// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());

// Set internal encoding if mbstring loaded
if (!extension_loaded('mbstring')) {
    throw new \RuntimeException("'mbstring' extension is not loaded.  This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');

// Get the Grav instance
$grav = Grav::instance(
    array(
        'loader' => $loader
    )
);

// Process the page
try {
    $grav->process();
} catch (\Exception $e) {
    $grav->fireEvent('onFatalException');
    throw $e;
}

<?php
namespace Grav;

// Ensure vendor libraries exist
$autoload = __DIR__ . '/vendor/autoload.php';
if (!is_file($autoload)) {
    throw new \RuntimeException("Please run: bin/grav install");
}

use Grav\Common\Grav;

// Register the auto-loader.
$loader = require_once $autoload;

if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
    die(sprintf('You are running PHP %s, but Grav needs at least PHP %s to run.', $ver, $req));
}

// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());

// Set internal encoding if mbstring loaded
if (extension_loaded('mbstring')) {
    die("'mbstring' extension is not loaded.  This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');

// Get the Grav instance
$grav = Grav::instance(
    array(
        'loader' => $loader
    )
);

// Process the page
try {
    $grav->process();
} catch (\Exception $e) {
    $grav->fireEvent('onFatalException');
    throw $e;
}

Change exception to die() in order to always show a message when these fatal errors are found

As proposed by @mahagr


<?php
// An image above a title and paragraph, with optional link.

$src = '';
if (is_object($f) && $f->getFileID()) {
    if ($f->getTypeObject()->isSVG()) {
        $src = $f->getRelativePath();
    } else {
        $thumbnailType = \Concrete\Core\File\Image\Thumbnail\Type\Type::getByHandle('medium');
        if (is_object($thumbnailType)) {
            $src = $f->getThumbnailURL($thumbnailType->getBaseVersion());
        } else {
            $src = $f->getRelativePath();
            if (!$src) {
                $src = $f->getURL();
            }
        }
    }
}
?>

    <?php if ($linkURL) { ?>
        <a href="<?=$linkURL?>">
    <?php } ?>
        <img class="ws-imglink-img" src="<?php echo h($src); ?>" alt="" role="presentation">

<?=$title?>

    <?php if ($linkURL) { ?>

    <?php }

    if ($altText) {
    ?>

<?=$altText?>

    <?php
    }
    ?>

Add image link block template

Add image link block template


<?php
class Kwc_Basic_Textfield_Admin extends Kwc_Abstract_Composite_Admin
{
    public function gridColumns()
    {
        $ret = array();
        $c = new Kwf_Grid_Column('string', trlKwf('Content'));
        $c->setData(new Kwf_Component_Abstract_ToStringData($this->_class));
        $ret['string'] = $c;
        return $ret;
    }
}

Add gridColumns for Textfield component

Add gridColumns for Textfield component

usually this is a one-liner so it makes sense to use as gridColumn


<?php

namespace Risan\OAuth1;

interface NonceGeneratorInterface
{
    /**
     * Generate a random string for nonce.
     *
     * @param  integer $length
     * @return string
     */
    public function generate($length = 32);
}

Add new interface for NonceGenerator.

:sparkles: Add new interface for NonceGenerator.


<?php

namespace KawaiiGherkin\Formatter;

final class FeatureDescription
{
    public function format($shortDescription, array $descriptionLines, $indentation = 4)
    {
        $indentation = str_repeat(' ', $indentation);
        $shortDesc   = 'Feature: ' . $shortDescription . PHP_EOL;
        $longDesc    =  implode(
            array_map(
                function ($descriptionLine) use ($indentation) {
                    return $indentation . trim($descriptionLine) . PHP_EOL;
                },
                $descriptionLines
            )
        );

        return $shortDesc . rtrim($longDesc);
    }
}

Add feature description formatter class

Add feature description formatter class


<?php
function cacheAudio($url, $file_type) {
    $cacheFile = $_SERVER['DOCUMENT_ROOT'] . '/cache/audio/' . md5($url). '.' . $file_type;
    $file_directory = 'http://' . $_SERVER['SERVER_NAME'] . '/cache/audio/' . md5($url). '.' . $file_type;

    if (file_exists($cacheFile)) {
        return $file_directory;
    }

    $audio = file_get_contents($url);

    $fh = fopen($cacheFile, 'w');
    fwrite($fh, $audio);
    fclose($fh);

    return $file_directory;
}

Add service for audio caching

Add service for audio caching


<?php
function getimg($url) {
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
    $headers[] = 'Connection: Keep-Alive';
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
    $user_agent = 'php';
    $process = curl_init($url);
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($process, CURLOPT_HEADER, 0);
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
    $return = curl_exec($process);
    curl_close($process);
    return $return;
}

function cacheImage($image_url, $data_source){
	$stripped_image_url = strtok($image_url, '?');
	$imagename= basename($stripped_image_url);
    $image_directory = $_SERVER['DOCUMENT_ROOT'] . '/src/images/' . $data_source . '/';
	if(!file_exists($image_directory . $imagename)){
	   $image = getimg($image_url);
	   file_put_contents($image_directory . $imagename,$image);
    }
}

Add service for image caching

Add service for image caching


<?php

declare(strict_types=1);

namespace BinSoul\Common\I18n;

/**
 * Represents an address which is mutable.
 */
interface MutableAddress extends Address
{
    /**
     * Sets the organization.
     */
    public function setOrganization(?string $value): void;

    /**
     * Sets the name prefix / salutation.
     */
    public function setNamePrefix(?string $value): void;

    /**
     * Sets the first name.
     */
    public function setFirstName(?string $value): void;

    /**
     * Sets the last name.
     */
    public function setLastName(?string $value): void;

    /**
     * Sets the address line 1.
     */
    public function setAddressLine1(?string $value): void;

    /**
     * Sets the address line 2.
     */
    public function setAddressLine2(?string $value): void;

    /**
     * Sets the address line 3.
     */
    public function setAddressLine3(?string $value): void;

    /**
     * Sets the sorting code.
     */
    public function setSortingCode(?string $value): void;

    /**
     * Sets the postal code.
     */
    public function setPostalCode(?string $value): void;

    /**
     * Sets the locality / city.
     */
    public function setLocality(?string $value): void;

    /**
     * Sets the sub locality.
     */
    public function setSubLocality(?string $value): void;

    /**
     * Sets the state.
     */
    public function setState(?string $value): void;

    /**
     * Sets the iso2 code of the country.
     */
    public function setCountryCode(?string $value): void;
}

Add an interface for mutable addresses

Add an interface for mutable addresses


<?php
namespace Sil\SilAuth\tests\unit\http;

use Sil\SilAuth\http\Request;

class DummyRequest extends Request
{
    protected $dummyIpAddress;

    /**
     * Get the DUMMY IP address (as the single entry in an array).
     *
     * @return string[] A list containing the dummy IP address.
     */
    protected function getIpAddresses()
    {
        return [$this->dummyIpAddress];
    }

    public function setDummyIpAddress($dummyIpAddress)
    {
        if ( ! self::isValidIpAddress($dummyIpAddress)) {
            throw new \InvalidArgumentException(sprintf(
                '%s is not a valid IP address.',
                var_export($dummyIpAddress, true)
            ));
        }

        $this->dummyIpAddress = $dummyIpAddress;
    }
}

Add dummy-request class for tests.

Add dummy-request class for tests.


<?php

namespace Zf2for1\Application;

use Zend_Application_Bootstrap_Bootstrap;
use Zend_Application_Bootstrap_Exception;
use Zf2for1\Resource\Zf2;

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    /**
     * Class cannot have resources.
     * Resources are now handled by ZF2 Service Manager
     * @see http://framework.zend.com/manual/2.2/en/modules/zend.service-manager.intro.html
     *
     * @return array
     */
    final public function getClassResources()
    {
        return array();
    }

    /**
     * Class cannot have resources.
     * Resources are now handled by ZF2 Service Manager
     * @see http://framework.zend.com/manual/2.2/en/modules/zend.service-manager.intro.html
     *
     * @return array
     */
    final public function getClassResourceNames()
    {
        return array();
    }

    /**
     * zf1 bootstrap only needed to bootstrap zf2 resource.
     * That resource will bootstrap Zend\Mvc\Application with compatibility code
     * required to setup zf1 application
     *
     * @param mixed $resource
     * @return void
     */
    final protected function _bootstrap($resource = null)
    {
        //zf2 resource must be bootstrapped first.
        $this->_executeResource('zf2');
        if (null === $resource || 'zf2' == $resource) {
            return; //Noop. This case will be handled during zf2 resource bootstrap
        }
        if (is_string($resource)) {
            // allow forced execution of resource due to legacy static state approach?
            // proper way is to list
            $this->getResource($resource);
        } else if (is_array($resource)) {
            foreach ($resource as $r) {
                $this->getResource($r);
            }
        } else {
            throw new Zend_Application_Bootstrap_Exception('Invalid argument passed to ' . __METHOD__);
        }
    }

    public function hasResource($name)
    {
        if (strtolower($name) == 'zf2') {
            return parent::hasResource('zf2');
        }
        $name = $this->resolveResourceToServiceName($name);
        return $this->getResource('zf2')->getServiceManager()->has($name);
    }

    public function getResource($name)
    {
        if (strtolower($name) == 'zf2') {
            return parent::getResource('zf2');
        }
        $name = $this->resolveResourceToServiceName($name);
        try {
            return parent::getResource('zf2')->getServiceManager()->get($name);
        } catch (\Exception $e) {
            throw new Zend_Application_Bootstrap_Exception($e->getMessage(), 0, $e);
        }
    }

    public function resolveResourceToServiceName($resource)
    {
        return 'zf1_resource_' . $resource;
    }
}

Add bootstrap override to allow zf2 style bootstrapping


<?php

namespace Emarref\Jwt\Encoding;

class Base64Test extends \PHPUnit_Framework_TestCase
{
    private static $value = 'føøbarbaz';

    /**
     * @var Base64
     */
    private $defaultEncoding;

    /**
     * @var Base64
     */
    private $nonDefaultEncoding;

    public function setUp()
    {
        $this->defaultEncoding    = new Base64();
        $this->nonDefaultEncoding = new Base64(false, false);
    }

    public function testEncode()
    {
        $this->assertSame('ZsO4w7hiYXJiYXo', $this->defaultEncoding->encode(self::$value));
        $this->assertSame('ZsO4w7hiYXJiYXo=', $this->nonDefaultEncoding->encode(self::$value));
    }

    public function testDecode()
    {
        $this->assertSame(self::$value, $this->defaultEncoding->decode('ZsO4w7hiYXJiYXo'));
        $this->assertSame(self::$value, $this->nonDefaultEncoding->decode('ZsO4w7hiYXJiYXo='));
    }
}

Add test for base64 encoding

Add test for base64 encoding


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

use litle\sdk\LitleOnlineRequest;
use litle\sdk\XmlParser;

class Utf8FunctionalTest extends \PHPUnit_Framework_TestCase
{
    public function test_simple_auth_with_card()
    {
        $hash_in = array(
            'card' => array('type' => 'VI',
                'number' => '4100000000000000',
                'expDate' => '1213',
                'cardValidationNum' => '1213'),
            'id' => '1211',
            'orderId' => '2111',
            'reportGroup' => 'PlanetsРусский中文',
            'orderSource' => 'ecommerce',
            'amount' => '0');

        $initialize = new LitleOnlineRequest();
        $authorizationResponse = $initialize->authorizationRequest($hash_in);
        $response = XmlParser::getNode($authorizationResponse, 'response');
        $this->assertEquals('000', $response);
        $this->assertEquals('PlanetsРусский中文', XmlParser::getAttribute($authorizationResponse, 'authorizationResponse','reportGroup'));
        $this->assertEquals('63225578415568556365452427825', XmlParser::getNode($authorizationResponse, 'networkTransactionId'));
    }
}

Add functional test for unicode.

Add functional test for unicode.


<?php

/**
 *  Text-related Drupal 7 snippets
 */

//  String placeholders :
//  format_string($string, array $args = array())
//      @variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
//      %variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
//      !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).
//  Examples with t() :
$i10n_dynamic_string = t("There is @check_plain.", array('@check_plain' => "no HTML here"));
$i10n_dynamic_string = t("There is %wrapped_in_em_tags.", array('%wrapped_in_em_tags' => "no HTML here either"));
$i10n_dynamic_string = t("There is !unfiltered.", array(
  // Security consideration example.
  '!unfiltered' => filter_xss("a raw, unfiltered string with HTML.")
));

//  I10n string formatter : singular / plural
//  format_plural($count, $singular, $plural, array $args = array(), array $options = array())
//  @see https://api.drupal.org/api/drupal/includes%21common.inc/function/format_plural/7
$count = 3;
$output = format_plural($count, '1 item', '@count items');

//  Example with additional arguments :
$output = format_plural(
  $count,
  'Changed the content type of 1 post from %old-type to %new-type.',
  'Changed the content type of @count posts from %old-type to %new-type.',
  array(
    '%old-type' => $info->old_type,
    '%new-type' => $info->new_type,
  )
);

Add Text-related Drupal 7 snippets

Add Text-related Drupal 7 snippets


<?php

/**
 * @copyright Copyright (C) 2015-2022 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@fetus.jp>
 */

declare(strict_types=1);

use app\components\db\AutoKey;
use app\components\db\Migration;

final class m220910_105227_point_sensor_alias extends Migration
{
    use AutoKey;

    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->insert('{{%subweapon3_alias}}', [
            'subweapon_id' => $this->key2id('{{%subweapon3}}', 'pointsensor'),
            'key' => self::name2key3('Point Sensor'),
        ]);

        return true;
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        $this->delete('{{%subweapon3_alias}}', [
            'key' => self::name2key3('Point Sensor'),
        ]);

        return true;
    }
}

Add missing alias for Point Sensor

Add missing alias for Point Sensor


<?php

/** @var Denkmal_Model_Link $link */
foreach (new Denkmal_Paging_Link_Broken() as $link) {
    $link->setFailedCount(0);
}

Add update script to let broken links again be tested


<?php
/**
 * Parser Reflection API
 *
 * @copyright Copyright 2015, Lisachenko Alexander <lisachenko.it@gmail.com>
 *
 * This source file is subject to the license that is bundled
 * with this source code in the file LICENSE.
 */

namespace ParserReflection\ValueResolver;

use PhpParser\Node;
use PhpParser\Node\Scalar\MagicConst;

/**
 * Tries to resolve expression into value
 */
class NodeExpressionResolver
{

    /**
     * Current reflection context for parsing
     *
     * @var mixed
     */
    private $context;

    /**
     * @var mixed Value of expression/constant
     */
    private $value;

    /**
     * Flag if expression is constant
     *
     * @var bool
     */
    private $isConstant = false;

    /**
     * Name of the constant (if present)
     *
     * @var null|string
     */
    private $constantName = null;

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

    /**
     * {@inheritDoc}
     */
    public function process(Node $node)
    {
        $this->value = null;

        // Most of simple scalars have raw value
        if ($node instanceof Node\Scalar && isset($node->value)) {
            $this->value = $node->value;
        }

        if ($node instanceof MagicConst) {
            $this->value = $this->resolveMagicConst($node);
        }
    }

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

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

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

    private function resolveMagicConst(MagicConst $node)
    {
        if ($node instanceof MagicConst\Method) {
            if ($this->context instanceof \ReflectionMethod) {
                $fullName = $this->context->getDeclaringClass()->getName() . '::' . $this->context->getShortName();

                return $fullName;
            }
        }

        if ($node instanceof MagicConst\Function_) {
            if ($this->context instanceof \ReflectionFunctionAbstract) {
                return $this->context->getName();
            }
        }

        if ($node instanceof MagicConst\Namespace_) {
            if (method_exists($this->context, 'getNamespaceName')) {
                return $this->context->getNamespaceName();
            }
        }

        if ($node instanceof MagicConst\Class_) {
            if ($this->context instanceof \ReflectionClass) {
                return $this->context->getName();
            }
        }

        if ($node instanceof MagicConst\Dir) {
            if (method_exists($this->context, 'getFileName')) {
                return dirname($this->context->getFileName());
            }
        }

        if ($node instanceof MagicConst\File) {
            if (method_exists($this->context, 'getFileName')) {
                return $this->context->getFileName();
            }
        }

        if ($node instanceof MagicConst\Line) {
            return $node->hasAttribute('startLine') ? $node->getAttribute('startLine') : 0;
        }

        if ($node instanceof MagicConst\Trait_) {
            if ($this->context instanceof \ReflectionClass && $this->context->isTrait()) {
                return $this->context->getName();
            }
        }

        return '';
    }
}

Add simple value resolver component for extracting values from constants


<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatFormField.php';
require_once 'Swat/SwatReplicableContainer.php';

/**
 * A form field container that replicates its children
 *
 * The form field can dynamically create widgets based on an array of
 * replicators identifiers.
 *
 * @package   Swat
 * @copyright 2005-2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatReplicableFormField extends SwatReplicableContainer
{
	// {{{ protected function getContainer()

	/**
	 * Gets a container to contain replicated widgets for this replicable
	 * container
	 *
	 * @param string $id the replicator id for the container.
	 * @param stirng $title the title of the container. The container may or
	 *                       may not use this title.
	 *
	 * @return SwatContainer the container object to which replciated widgets
	 *                        are added. The container is added to the widget
	 *                        tree after adding the replicated widgets to the
	 *                        container. If null is returned, the widgets are
	 *                        replicated directly in the widget tree.
	 */
	protected function getContainer($id, $title)
	{
		$form_field = new SwatFormField();
		$form_field->title = $title;
		return $form_field;
	}

	// }}}
}

?>

Rename ReplicatorFormField to ReplicableFormField and extend ReplicableContainer. This also has the side-effect of removing the fieldset around form fields. This can/should be added manually.

svn commit r13628


<?php
$globals = ["LOCAL_URL" => "https://localhost/podtube/src", "SUBDIR" => "podtube/src/", "GOOGLE_API_KEY" => "****",
				"DOWNLOAD_PATH" => "temp", "SessionCookieSecure" => true, "EMAIL_FROM" => "\"AudioDidact Administrator\"<michael@mikedombrowski.com>",
				"ChosenDAL" => "\\AudioDidact\\MySQLDAL", "DB_USER" => "root", "DB_PASSWORD" => "root",
				"PDO_STR" =>  "mysql:host=mysql;dbname=podtube;charset=utf8", "CHECK_REQUIRED" => true ];

$configFile = "config.php";
if(file_exists($configFile)){
	require($configFile);
	foreach($globals as $k=>$v){
		if(!defined($k)){
			file_put_contents($configFile, "\r\ndefine(\"$k\", \"$v\");\r\n", FILE_APPEND);
		}
	}
	if(defined("CHECK_REQUIRED") && !CHECK_REQUIRED){
		$currentConfig = file_get_contents($configFile);
		$newConfig = preg_replace("/define\(\"CHECK_REQUIRED\",\s+.*\)/", "define(\"CHECK_REQUIRED\", true)", $currentConfig);
		file_put_contents($configFile, $newConfig);
	}
}
else{
	die("config.php does not exist, cannot update what does not exist!");
}

Add file to help updates to AudioDidact by transfering configurations


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Add mail form (is not used).

Add mail form (is not used).


<?php

namespace Concrete\Tests\Block;

use Concrete\Core\Block\Block;
use Concrete\Core\Block\View\BlockView;
use Concrete\Core\Entity\Block\BlockType\BlockType;
use Concrete\Core\Support\Facade\Facade;
use PHPUnit_Framework_TestCase;

class BlockViewTest extends PHPUnit_Framework_TestCase
{
    /** @var \Concrete\Core\Application\Application */
    protected $app;

    public function setUp()
    {
        $this->app = Facade::getFacadeApplication();
    }

    public function testPreventRendering()
    {
        /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $director */
        $director = $this->app->make('director');
        $block = $this->getMockBlock('autonav');

        $listener = function ($event) {
            /** @var \Concrete\Core\Block\Events\BlockBeforeRender $event */
            $event->preventRendering();

            return $event;
        };

        $director->addListener('on_block_before_render', $listener);

        $view = new BlockView($block);

        ob_start();
        $view->renderViewContents([]);
        $this->assertEquals('', ob_get_flush());

        $director->removeListener('on_block_before_render', $listener);
    }

    protected function getMockBlock($handle, $bFilename = null)
    {
        $blockType = $this->getMockBuilder(BlockType::class)
            ->disableOriginalConstructor()
            ->getMock();
        $blockType->expects($this->any())
            ->method('getBlockTypeHandle')
            ->will($this->returnValue($handle));

        $controller = 'Concrete\\Block\\' . camelcase($handle) . '\\Controller';
        $controller = $this->getMockBuilder($controller)
            ->disableOriginalConstructor()
            ->getMock();

        $block = $this->getMockBuilder(Block::class)
            ->disableOriginalConstructor()
            ->getMock();
        $block->expects($this->any())
            ->method('getBlockTypeHandle')
            ->will($this->returnValue($handle));
        $block->expects($this->any())
            ->method('getInstance')
            ->will($this->returnValue($controller));
        $block->expects($this->any())
            ->method('getBlockTypeObject')
            ->will($this->returnValue($blockType));
        $block->expects($this->any())
            ->method('getBlockFilename')
            ->will($this->returnValue($bFilename));

        return $block;
    }
}

Add test for preventRendering a block

Add test for preventRendering a block


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\KeyDataBuilders;

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

final class SortedSetSubKeyDataBuilder implements BuildsKeyData
{
	/** @var ServerManager */
	private $manager;

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

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

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

	/**
	 * @param ProvidesKeyInfo $keyInfo
	 * @param ProvidesKeyName $keyName
	 *
	 * @throws RuntimeException
	 * @return ProvidesKeyData
	 */
	public function buildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : ProvidesKeyData
	{
		$i = 0;
		foreach ( $keyInfo->getSubItems() as $member => $score )
		{
			if ( (int)$keyName->getSubKey() !== $i++ )
			{
				continue;
			}

			$rawKeyData = $member;
			$keyData    = $this->prettifier->prettify( $member );

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

		throw new RuntimeException( 'Could not find key in sorted set anymore.' );
	}
}

Add sorted set sub key data builder

Add sorted set sub key data builder