<?php  namespace Mbbender\Doctrine\DBAL\Types;

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

class OrderedGuidType extends GuidType
{
    const ORDEREDGUID = 'ordered_guid';

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $field['length'] = 36;
        $field['fixed']  = true;

        $fieldDeclaration = array_merge($field, $fieldDeclaration);

        return $platform->getBinaryTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
            //TODO: Throw exception? Never should have a null value here I don't think
        }

        // TODO: Throw exception if $value is not a resource. Not sure how you can not have a resource.
        $value = (is_resource($value)) ? stream_get_contents($value) : $value;

        return bin2hex($value);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::ORDEREDGUID;
    }
}

<?php  namespace Mbbender\Doctrine\DBAL\Types;

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

class OrderedGuidType extends GuidType
{
    const ORDEREDGUID = 'ordered_guid';

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $field['length'] = 36;
        $field['fixed']  = true;

        $fieldDeclaration = array_merge($field, $fieldDeclaration);

        return $platform->getBinaryTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
            //TODO: Throw exception? Never should have a null value here I don't think
        }

        // TODO: Throw exception if $value is not a resource. Not sure how you can not have a resource.
        $value = (is_resource($value)) ? stream_get_contents($value) : $value;

        return bin2hex($value);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        try{
            $value = hex2bin($value);
        }
        catch(\ErrorException $e)
        {

        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::ORDEREDGUID;
    }
}

Add convert to database value function

Add convert to database value function


<?php namespace Ordercloud;

use Illuminate\Container\Container;
use Ordercloud\Entities\Auth\AccessToken;
use Ordercloud\Entities\Organisations\OrganisationAccessToken;
use Ordercloud\Support\CommandBus\Command;
use Ordercloud\Support\CommandBus\CommandBus;
use Ordercloud\Support\Http\Client;
use Ordercloud\Support\Http\Response;

class Ordercloud
{
    const VERSION = '0.1';

    /** @var CommandBus */
    private $commandBus;
    /** @var Container */
    private $container;

    public function __construct(CommandBus $commandBus, Container $container)
    {
        $this->commandBus = $commandBus;
        $this->container = $container;
    }

    /**
     * @param Command $command
     *
     * @return Response
     */
    public function exec(Command $command)
    {
        return $this->commandBus->execute($command);
    }

    /**
     * @param AccessToken $token
     */
    public function setAccessToken(AccessToken $token)
    {
        $this->getHttpClient()->setAccessToken($token->getAccessToken());
    }

    /**
     * @param OrganisationAccessToken $token
     */
    public function setOrganisationToken(OrganisationAccessToken $token)
    {
        $this->getHttpClient()->setOrganisationToken($token->getToken());
    }

    /**
     * @return Client
     */
    protected function getHttpClient()
    {
        return $this->container->make('Ordercloud\Support\Http\Client');
    }
}

<?php namespace Ordercloud;

use Illuminate\Container\Container;
use Ordercloud\Entities\Auth\AccessToken;
use Ordercloud\Entities\Organisations\OrganisationAccessToken;
use Ordercloud\Support\CommandBus\Command;
use Ordercloud\Support\CommandBus\CommandBus;
use Ordercloud\Support\Http\Client;
use Ordercloud\Support\Http\Response;

class Ordercloud
{
    const VERSION = '0.1';

    /** @var CommandBus */
    private $commandBus;
    /** @var Container */
    private $container;

    public function __construct(CommandBus $commandBus, Container $container)
    {
        $this->commandBus = $commandBus;
        $this->container = $container;
    }

    /**
     * @param Command $command
     *
     * @return Response
     */
    public function exec(Command $command)
    {
        return $this->commandBus->execute($command);
    }

    /**
     * @param string $token
     */
    public function setAccessToken($token)
    {
        $this->getHttpClient()->setAccessToken($token);
    }

    /**
     * @param string $token
     */
    public function setOrganisationToken($token)
    {
        $this->getHttpClient()->setOrganisationToken($token);
    }

    /**
     * @return Client
     */
    protected function getHttpClient()
    {
        return $this->container->make('Ordercloud\Support\Http\Client');
    }
}

Change access token requirement on Ordercloud facade


<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/yii.php';

$basePath = sys_get_temp_dir() . '/yii-sass';
if (!is_dir($basePath)) {
    if (!mkdir($basePath)) {
        throw new Exception('Can not create directory: ' . $basePath);
    }
}
Yii::createConsoleApplication(array('basePath' => $basePath));

<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/yii.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/console/CConsoleApplication.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/console/CConsoleCommandRunner.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/base/CApplicationComponent.php';
require __DIR__ . '/../vendor/yiisoft/yii/framework/utils/CFileHelper.php';

spl_autoload_unregister(array('YiiBase','autoload'));

$basePath = sys_get_temp_dir() . '/yii-sass';
if (!is_dir($basePath)) {
    if (!mkdir($basePath)) {
        throw new Exception('Can not create directory: ' . $basePath);
    }
}
Yii::createConsoleApplication(array('basePath' => $basePath));

Fix Yii autoloader issues in unit tests

Fix Yii autoloader issues in unit tests


<?php
/**
 * DronePHP (http://www.dronephp.com)
 *
 * @link      http://github.com/Pleets/DronePHP
 * @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
 * @license   http://www.dronephp.com/license
 */

namespace Drone\Db;

abstract class Entity
{
    /**
     * @var string
     */
    private $tableName;

    /**
     * Returns the tableName property
     *
     * @return string
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * Sets the tableName property
     *
     * @param string $tableName
     *
     * @param null
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }

    /**
     * Sets all entity properties passed in the array
     *
     * @param array $data
     *
     * @return null
     */
    public function exchangeArray($data)
    {
        foreach ($data as $prop => $value)
        {
            if (property_exists($this, $prop))
                $this->$prop = $value;
            else
                throw new Exception("The property '$prop' does not exists in the class!");
        }
    }
}

<?php
/**
 * DronePHP (http://www.dronephp.com)
 *
 * @link      http://github.com/Pleets/DronePHP
 * @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
 * @license   http://www.dronephp.com/license
 */

namespace Drone\Db;

abstract class Entity
{
    /**
     * @var string
     */
    private $tableName;

    /**
     * Returns the tableName property
     *
     * @return string
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * Sets the tableName property
     *
     * @param string $tableName
     *
     * @param null
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }

    /**
     * Sets all entity properties passed in the array
     *
     * @param array $data
     *
     * @return null
     */
    public function exchangeArray($data)
    {
        $class = get_class($this);

        foreach ($data as $prop => $value)
        {
            if (property_exists($this, $prop))
                $this->$prop = $value;
            else
                throw new Exception("The property '$prop' does not exists in the class '$class'");
        }
    }
}

Improve error description showing class name


<?php
/**
* Authentication Library
*
* @package Authentication
* @category Libraries
* @author Adam Griffiths
* @link http://programmersvoice.com
* @version 1.0.4
* @copyright Adam Griffiths 2009
*
* Auth provides a powerful, lightweight and simple interface for user authentication
*/

/**
* The array which holds your user groups and their ID.
* If you have a database table for groups, these ID's must be the same as in the database.
*/
$config['auth_groups'] = array(
							'admin' => '1',
							'editor' => '2',
							'user' => '100'
							);

/**
* The default URI string to redirect to after a successful login.
*/
$config['auth_login'] = 'admin/';

/**
* bool TRUE / FALSE
* Determines whether or not users will be remembered by the auth library
*/
$config['auth_remember'] = TRUE;

?>

<?php
/**
* Authentication Library
*
* @package Authentication
* @category Libraries
* @author Adam Griffiths
* @link http://programmersvoice.com
* @version 1.0.4
* @copyright Adam Griffiths 2009
*
* Auth provides a powerful, lightweight and simple interface for user authentication
*/

/**
* The array which holds your user groups and their ID.
* If you have a database table for groups, these ID's must be the same as in the database.
*/
$config['auth_groups'] = array(
							'admin' => '1',
							'editor' => '2',
							'user' => '100'
							);

/**
* The default URI string to redirect to after a successful login.
*/
$config['auth_login'] = 'admin/dashboard/';

/**
* bool TRUE / FALSE
* Determines whether or not users will be remembered by the auth library
*/
$config['auth_remember'] = TRUE;

?>

Update config file for correct admin path


<?php

require_once 'MemeBot/Memeable.php';
require_once 'MemeBot/MemeClass.php';
require_once 'MemeBot/Meme.php';

$meme = new MemeBot\MemeClass;

// Get Request
$trigger = trim($_POST['trigger_word']);
$text    = trim(substr($_POST['text'], strlen($trigger) + 1));

if($text == '') {
	sendResponse("One does not simply <text> - Lord of the Rings Boromir\nY U NO <text> - Y U NO Guy\nI don't always <text> but when i do <text> - The Most Interesting man in the World\nNot sure if <text> or <text> - Futurama Fry\nBrace yourselves <text> - Brace Yourselves X is Coming (Imminent Ned, Game of Thrones)\nYo dawg <text> so <text> - Yo Dawg Heard You (Xzibit)\n<text> that would be great - Bill Lumbergh from Office Space\nWhat if I told you <text> - Matrix Morpheus");
}

$returned_meme = $meme->generateMeme($text);

sendResponse($returned_meme);

exit;

/**
 * Send JSON Response
 *
 * @param $response
 */
function sendResponse($response)
{
    header('Content-Type: application/json');
    die(json_encode(array(
        'text' => $response
    )));
}

<?php

require_once 'MemeBot/Memeable.php';
require_once 'MemeBot/MemeClass.php';
require_once 'MemeBot/Meme.php';

$meme = new MemeBot\MemeClass;

// Get Request
$trigger = trim($_POST['trigger_word']);
$text    = trim(substr($_POST['text'], strlen($trigger) + 1));

if($text == '') {
	sendResponse("One does not simply <text> - Lord of the Rings Boromir\nY U NO <text> - Y U NO Guy\nI don't always <text> but when i do <text> - The Most Interesting man in the World\nNot sure if <text> or <text> - Futurama Fry\nBrace yourselves <text> - Brace Yourselves X is Coming (Imminent Ned, Game of Thrones)\nYo dawg <text> so <text> - Yo Dawg Heard You (Xzibit)\n<text> that would be great - Bill Lumbergh from Office Space\nWhat if I told you <text> - Matrix Morpheus");
}

$returned_meme = $meme->generateMeme($text);

sendResponse($returned_meme);

exit;

/**
 * Send JSON Response
 *
 * @param $response
 */
function sendResponse($response)
{
    header('Content-Type: application/json');
    die(json_encode(array(
        'text' => "<".$response.">",
        'unfurl_links' => true
    )));
}

Set unfurl link option in returned response


<?php
Object::add_extension('SiteTree', 'AccessKeyExtension');
Object::add_extension("Page_Controller","AccessKeyExtension");
 ?>

<?php
Object::add_extension('SiteTree', 'AccessKeyExtension');
Object::add_extension("Page_Controller","AccessKeyControllerExtension");
DataObject::add_extension('SiteConfig', 'AccessKeysSiteConfig');
 ?>

FIX: Fix error in config for controller extension


<?php
$app_path = realpath(
    dirname(__FILE__) . '/../../../../../../app'
);
if (!$app_path) {
    $app_path = '/mnt/hgfs/Sites/magento.development.local/public/app';
}

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', $app_path);

defined('LOG_PATH')
    || define('LOG_PATH', '/mnt/hgfs/Sites/magento.development.local/public/app/code/local/Ibuildings/Gearman/tests/');

require_once APPLICATION_PATH.'/Mage.php';
require_once 'Net/Gearman/Client.php';

<?php
$app_path = realpath(
    dirname(__FILE__) . '/../../../../../../app'
);
if (!$app_path) {
    $app_path = '/mnt/hgfs/Sites/magento.development.local/public/app';
}

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', $app_path);

defined('LOG_PATH')
    || define('LOG_PATH', '/mnt/hgfs/Sites/magento.development.local/public/app/code/local/Ibuildings/Gearman/tests/');

defined('TEST')
    || define('TEST', true);

require_once APPLICATION_PATH.'/Mage.php';

Remove Net_Gearman require, see last commit message


<?php

// Don't allow direct access to the boostrap
if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php'){
	exit('bootstrap.php does nothing on its own. Please see the examples provided');
}

// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');

// Register a simple autoload function
spl_autoload_register(function($class){
	require_once('../' . $class . '.php');
});

// Set your consumer key, secret and callback URL
$key      = 'XXXXXXXXXXXXXXX';
$secret   = 'XXXXXXXXXXXXXXX';
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Instantiate the required Dropbox objects
$storage = new \Dropbox\OAuth\Storage\Session;
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);

<?php

// Don't allow direct access to the boostrap
//if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php'){
///	exit('bootstrap.php does nothing on its own. Please see the examples provided');
//}

// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');

// Register a simple autoload function
spl_autoload_register(function($class){
	$class = str_replace('\\', '/', $class);
	require_once('../' . $class . '.php');
});

// Set your consumer key, secret and callback URL
$key      = 'XXXXXXXXXXXXXXX';
$secret   = 'XXXXXXXXXXXXXXX';
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Instantiate the required Dropbox objects
$storage = new \Dropbox\OAuth\Storage\Session;
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);

Convert backslashes to forward slashes in spl_autoload_register


<?php

namespace Speicher210\Fastbill\Api\Serializer\Handler;

use JMS\Serializer\Context;
use JMS\Serializer\Handler\DateHandler as JMSDateHandler;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\VisitorInterface;

class DateHandler extends JMSDateHandler
{
    /**
     * {@inheritdoc}
     */
    public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context)
    {
        // All dates send to Fastbill should be in Europe/Berlin timezone.
        $date->setTimezone(new \DateTimeZone('Europe/Berlin'));

        return parent::serializeDateTime($visitor, $date, $type, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type)
    {
        if ('' === $data || null === $data || '0000-00-00 00:00:00' === $data) {
            return null;
        }

        // We want to always show the response in the UTC timezone.
        $dateTime = parent::deserializeDateTimeFromJson($visitor, $data, $type);

        if ($dateTime instanceof \DateTime) {
            $dateTime->setTimezone(new \DateTimeZone('UTC'));
        }

        return $dateTime;
    }
}

<?php

namespace Speicher210\Fastbill\Api\Serializer\Handler;

use JMS\Serializer\Context;
use JMS\Serializer\Handler\DateHandler as JMSDateHandler;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\VisitorInterface;

class DateHandler extends JMSDateHandler
{
    /**
     * {@inheritdoc}
     */
    public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context)
    {
        // All dates send to Fastbill should be in Europe/Berlin timezone.
        $date->setTimezone(new \DateTimeZone('Europe/Berlin'));

        return parent::serializeDateTime($visitor, $date, $type, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type)
    {
        // Handle empty or invalid date / datetime values.
        if ('' === $data || null === $data || strpos($data, '0000-00-00') !== false) {
            return null;
        }

        // We want to always show the response in the UTC timezone.
        $dateTime = parent::deserializeDateTimeFromJson($visitor, $data, $type);

        if ($dateTime instanceof \DateTime) {
            $dateTime->setTimezone(new \DateTimeZone('UTC'));
        }

        return $dateTime;
    }
}

Handle invalid dates only as well

Handle invalid dates only as well


<?php

use OCA\Mail\HordeTranslationHandler;

$autoload = __DIR__ .  '/../vendor/autoload.php';
if (!is_readable($autoload)) {
	print 'Cannot read "autoload.php". Did you run composer ?'.
	      "
cd path/to/owncloud/apps/mail\n".
	      "curl -sS https://getcomposer.org/installer | php\n".
	      'php composer.phar install
';
	exit;
}
require_once $autoload;
$l = OC_L10N::get('mail');

// bypass Horde Translation system
Horde_Translation::setHandler('Horde_Imap_Client', new HordeTranslationHandler());
Horde_Translation::setHandler('Horde_Mime', new HordeTranslationHandler());

OCP\App::addNavigationEntry(array(
  'id' => 'mail',
  'order' => 1,
  'href' => OCP\Util::linkToRoute( 'mail.page.index' ),
  'icon' => OCP\Util::imagePath( 'mail', 'mail.svg' ),
  'name' => $l->t('Mail'),
));

//OCP\App::registerPersonal('mail','settings');

<?php

use OCA\Mail\HordeTranslationHandler;

if ((@include_once __DIR__ . '/../vendor/autoload.php')===false) {
	throw new Exception('Cannot include autoload. Did you run install dependencies using composer?');
}
$l = OC_L10N::get('mail');

// bypass Horde Translation system
Horde_Translation::setHandler('Horde_Imap_Client', new HordeTranslationHandler());
Horde_Translation::setHandler('Horde_Mime', new HordeTranslationHandler());

OCP\App::addNavigationEntry(array(
  'id' => 'mail',
  'order' => 1,
  'href' => OCP\Util::linkToRoute( 'mail.page.index' ),
  'icon' => OCP\Util::imagePath( 'mail', 'mail.svg' ),
  'name' => $l->t('Mail'),
));

//OCP\App::registerPersonal('mail','settings');

Throw an exception instead of exiting when autload.php cannot be included


<?php
namespace wcf\system\user\authentication\password\algorithm;
use wcf\system\user\authentication\password\IPasswordAlgorithm;

/**
 * Implementation of BCrypt.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2020 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Authentication\Password\Algorithm
 * @since	5.4
 */
final class Bcrypt implements IPasswordAlgorithm {
	private const OPTIONS = [
		'cost' => 10,
	];

	/**
	 * @inheritDoc
	 */
	public function verify(string $password, string $hash): bool {
		return \password_verify($password, $hash);
	}

	/**
	 * @inheritDoc
	 */
	public function hash(string $password): string {
		return \password_hash($password, \PASSWORD_BCRYPT, self::OPTIONS);
	}

	/**
	 * @inheritDoc
	 */
	public function needsRehash(string $hash): bool {
		return \password_needs_rehash($hash, \PASSWORD_BCRYPT, self::OPTIONS);
	}
}

<?php
namespace wcf\system\user\authentication\password\algorithm;
use wcf\system\user\authentication\password\IPasswordAlgorithm;

/**
 * Implementation of BCrypt.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2020 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Authentication\Password\Algorithm
 * @since	5.4
 */
final class Bcrypt implements IPasswordAlgorithm {
	private const OPTIONS = [
		'cost' => 12,
	];

	/**
	 * @inheritDoc
	 */
	public function verify(string $password, string $hash): bool {
		return \password_verify($password, $hash);
	}

	/**
	 * @inheritDoc
	 */
	public function hash(string $password): string {
		return \password_hash($password, \PASSWORD_BCRYPT, self::OPTIONS);
	}

	/**
	 * @inheritDoc
	 */
	public function needsRehash(string $hash): bool {
		return \password_needs_rehash($hash, \PASSWORD_BCRYPT, self::OPTIONS);
	}
}

Increase `Bcrypt` cost to 12

Increase `Bcrypt` cost to 12

This results in ~333ms per hash on an oldish Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz
 any other CPU I tested was faster than that.


@extends('layouts.master')

@section('main_content')

    @include('layouts.header', ['header' => 'Upload a CSV for import'])

For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack

                <form action={{url('/import')}} method="post" enctype="multipart/form-data">
                    {{ csrf_field()}}

                        Upload
                        <input type="file" name="upload-file" class="form-control">

                    Type of Import

                            <input checked type="checkbox" id="importType" value="turbovote" name="importType">

                            Turbovote Import

                        <input type="submit" class="button" value="Submit CSV">

                </form>

@stop

@extends('layouts.master')

@section('main_content')

    @include('layouts.header', ['header' => 'Upload a CSV for import'])

                        Attention:

For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack

                <form action={{url('/import')}} method="post" enctype="multipart/form-data">
                    {{ csrf_field()}}

                        Upload
                        <input type="file" name="upload-file" class="form-control">

                    Type of Import

                            <input checked type="checkbox" id="importType" value="turbovote" name="importType">

                            Turbovote Import

                        <input type="submit" class="button" value="Submit CSV">

                </form>

@stop

Make the message nicer with a picture of jen


<?php

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

class CreateContactNotesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('contact_notes', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('note');
            $table->integer('contact_id')->unsigned();
            $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateContactNotesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('contact_notes', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('note');
            $table->integer('contact_id')->unsigned();
            $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

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

Fix typo in contact notes migration down function


<?php

require 'core.php';

// No unauthenticated deploys!
protectPage();

// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
    if ($target->getIdentifier() == $hash)
    {
        $result = exec($target->getDeployCommand() . ' 2>&1'); // Execute script.
        if ($result == null)
        {
            echo json_encode([
                'status' => 'warning',
                'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.',
                'result' => $result,
            ]); // Null output from script.
        }
        else if ($result == '0')
        {
            echo json_encode([
                'status' => 'success',
                'message' => 'Your website should be online and ready! Your script ran without a problem.',
                'result' => $result,
            ]); // If script returns 0, that means success.
        }
        else if ($result == '1') {
            echo json_encode([
                'status' => 'danger',
                'message' => 'There was a problem deploying your site. Your script returned a failure.',
                'result' => $result,
            ]); // If script returns 1, that means failure.
        }
        else
        {
            echo json_encode([
                'status' => 'info',
                'message' => 'Your script returned something weird. You should look into this further.',
                'result' => $result,
            ]); // If script returns something else, we dunno.
        }
    }
}

<?php

require 'core.php';

// No unauthenticated deploys!
protectPage();

// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
    if ($target->getIdentifier() == $hash)
    {
        $result = shell_exec('/usr/bin/git pull 2>&1'); // Execute script.
        if ($result == null)
        {
            echo json_encode([
                'status' => 'warning',
                'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.',
                'result' => $result,
            ]); // Null output from script.
        }
        else if ($result == '0')
        {
            echo json_encode([
                'status' => 'success',
                'message' => 'Your website should be online and ready! Your script ran without a problem.',
                'result' => $result,
            ]); // If script returns 0, that means success.
        }
        else if ($result == '1') {
            echo json_encode([
                'status' => 'danger',
                'message' => 'There was a problem deploying your site. Your script returned a failure.',
                'result' => $result,
            ]); // If script returns 1, that means failure.
        }
        else
        {
            echo json_encode([
                'status' => 'info',
                'message' => 'Your script returned something weird. You should look into this further.',
                'result' => $result,
            ]); // If script returns something else, we dunno.
        }
    }
}

Remove scripting for now, just git pull

Remove scripting for now, just git pull


<?php

namespace Drupal\happy_alexandrie\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

class AlexandrieAccess {

  /**
   * Limit access to the Library between 9:00 and 18:30 except for admins.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface The access result.
   *   The access result.
   */
  public function accessLibrary(AccountInterface $account) {
    $time = time();
    if ($time >= strtotime('today 9:00') && $time <= strtotime('today 18:30')) {
      return AccessResult::allowed();
    }
    return AccessResult::allowedIfHasPermission($account, 'administer alexandrie library');
  }

}

<?php

namespace Drupal\happy_alexandrie\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Session\AccountInterface;
use Drupal\happy_alexandrie\Form\AlexandrieConfigForm;

class AlexandrieAccess {

  const DATE_FORMAT = 'G:i';

  /**
   * Limit access to the Library between 9:00 and 18:30 except for admins.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface The access result.
   *   The access result.
   */
  public function accessLibrary(AccountInterface $account) {
    $config = \Drupal::config('happy_alexandrie.library_config');
    $hour_opening = DrupalDateTime::createFromFormat(AlexandrieConfigForm::DATE_FORMAT, $config->get('opening'))->format(self::DATE_FORMAT);
    $hour_closing = DrupalDateTime::createFromFormat(AlexandrieConfigForm::DATE_FORMAT, $config->get('closing'))->format(self::DATE_FORMAT);

    $time = time();
    if ($time >= strtotime('today ' . $hour_opening) && $time <= strtotime('today ' . $hour_closing)) {
      return AccessResult::allowed();
    }
    return AccessResult::allowedIfHasPermission($account, 'administer alexandrie library');
  }

}

2.4.3: Use schedule settings in the access method.


<?php

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

namespace Symfony\Component\Serializer\Tests\Fixtures;

class JsonSerializableDummy implements \JsonSerializable
{
    public function jsonSerialize()
    {
        return [
            'foo' => 'a',
            'bar' => 'b',
            'baz' => 'c',
            'qux' => $this,
        ];
    }
}

<?php

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

namespace Symfony\Component\Serializer\Tests\Fixtures;

class JsonSerializableDummy implements \JsonSerializable
{
    public function jsonSerialize(): array
    {
        return [
            'foo' => 'a',
            'bar' => 'b',
            'baz' => 'c',
            'qux' => $this,
        ];
    }
}

Add return types to JsonSerializable implementations


<?php

namespace App\Export\DailySaleRecord;

use App\Utility\Chinghwa\ExportExcel;
use Carbon\Carbon;

class OnlyEcExport extends Export
{
    protected $to = [
        'darren@chinghwa.com.tw' => '6804張碩'
    ];

    protected $cc = [
        'jeremy@chinghwa.com.tw'    => '6232游加恩',
        'jocoonopa@chinghwa.com.tw' => '6231小閎'
    ];

    public function getFilename()
    {
        $this->date = Carbon::now()->modify('-1 Days');

        return ExportExcel::DSR_FILENAME . "{$this->date->format('Ymd')}_ec";
    }
}

<?php

namespace App\Export\DailySaleRecord;

use App\Utility\Chinghwa\ExportExcel;
use Carbon\Carbon;

class OnlyEcExport extends Export
{
    protected $to = [
        'darren@chinghwa.com.tw'   => '6804張碩',
        'Merc0918@chinghwa.com.tw' => '羅偉銘',
        'Tina.lin@chinghwa.com.tw' => '林玉樺'
    ];

    protected $cc = [
        'jeremy@chinghwa.com.tw'    => '6232游加恩',
        'jocoonopa@chinghwa.com.tw' => '6231小閎'
    ];

    public function getFilename()
    {
        $this->date = Carbon::now()->modify('-1 Days');

        return ExportExcel::DSR_FILENAME . "{$this->date->format('Ymd')}_ec";
    }
}

Add two members to recieve ec_dsr_report, next will fix PM8:00 problem


<?php
/**
 * AllTests file
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Test.Case
 * @since         CakePHP(tm) v 2.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('CakeTestLoader', 'TestSuite');

/**
 * AllTests class
 *
 * This test group will run all tests.
 *
 * @package       Cake.Test.Case
 */
class AllTests extends PHPUnit_Framework_TestSuite {

/**
 * Suite define the tests for this suite
 *
 * @return void
 */
     public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('All Tests');
        $path = TESTS . 'Case' . DS;
        $config['app'] = 1;
        $tests = CakeTestLoader::generateTestList($config);
        foreach ($tests as $test) {
            if ($test != 'AllTests') {
                $suite->addTestFile($path . $test . 'Test.php');
            }
        }
        return $suite;
    }
}

<?php
/**
 * AllTests file
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Test.Case
 * @since         CakePHP(tm) v 2.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('CakeTestLoader', 'TestSuite');

/**
 * AllTests class
 *
 * This test group will run all tests.
 *
 * @package       Cake.Test.Case
 */
class AllTests extends PHPUnit_Framework_TestSuite
{

    /**
    * Suite define the tests for this suite
    */
    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite('All Tests');
        $path = TESTS . 'Case' . DS;
        $config['app'] = 1;
        $tests = CakeTestLoader::generateTestList($config);
        foreach ($tests as $test) {
            if ($test != 'AllTests') {
                $suite->addTestFile($path . $test . 'Test.php');
            }
        }
        return $suite;
    }

}

Make AllTests.php without any checkstyle error


<?php

namespace Unicodeveloper\Ngsc\Test;

use PHPUnit_Framework_TestCase;

class NgscTest extends PHPUnit_Framework_TestCase
{
    /**
     * Test that true does in fact equal true
     */
    public function testTrueIsTrue()
    {
        $this->assertTrue(true);
    }
}

feat(tests): Add simple placeholder tests, give first timers opportunities to contribute to open source


<?php

namespace FluxBB\Web\Controllers;

use FluxBB\Server\Exception\Exception;
use FluxBB\Server\Exception\ValidationFailed;
use FluxBB\Web\Controller;

class AuthController extends Controller
{
    public function registerForm()
    {
        return $this->view('register');
    }

    public function register()
    {
        try {
            $this->execute('handle_registration', [
                'ip' => $this->request->getClientIp(),
            ]);

            return $this->redirectTo('index')
                        ->withMessage(trans('fluxbb::register.reg_complete'));
        } catch (ValidationFailed $e) {
            return $this->redirectTo('register')
                        ->withInput()
                        ->withErrors($e);
        }
    }

    public function loginForm()
    {
        return $this->view('login');
    }

    public function login()
    {
        try {
            $this->execute('handle_login');

            return $this->redirectTo('index')
                        ->withMessage(trans('fluxbb::login.message_login'));
        } catch (Exception $e) {
            return $this->redirectTo('login')
                        ->withInput();
            // TODO: With errors!
        }
    }

    public function logout()
    {
        $this->execute('logout');

        return $this->redirectTo('index');
    }

    public function resetForm()
    {
        //
    }

    public function reset()
    {
        //
    }
}

<?php

namespace FluxBB\Web\Controllers;

use FluxBB\Server\Exception\Exception;
use FluxBB\Server\Exception\ValidationFailed;
use FluxBB\Web\Controller;

class AuthController extends Controller
{
    public function registerForm()
    {
        return $this->view('register');
    }

    public function register()
    {
        try {
            $this->execute('handle_registration', [
                'ip' => $this->request->getClientIp(),
            ]);

            return $this->redirectTo('index')
                        ->withMessage(trans('fluxbb::register.reg_complete'));
        } catch (ValidationFailed $e) {
            return $this->redirectTo('register')
                        ->withInput()
                        ->withErrors($e);
        }
    }

    public function loginForm()
    {
        return $this->view('login');
    }

    public function login()
    {
        try {
            $this->execute('handle_login');

            return $this->redirectTo('index')
                        ->withMessage(trans('fluxbb::login.message_login'));
        } catch (Exception $e) {
            return $this->redirectTo('login')
                        ->withInput();
            // TODO: With errors!
        }
    }

    public function logout()
    {
        $this->execute('logout');

        return $this->redirectTo('index')
                    ->withMessage('Successfully logged out.');
    }

    public function resetForm()
    {
        //
    }

    public function reset()
    {
        //
    }
}

Add a redirect message when logging out.


OIDC RP Test

<?php
foreach ($_SERVER as $key => $value) if (substr($key,0,4) == "OIDC") echo "
" . substr($key,5) . ": $value
\n";

OIDC RP Test

<a href="redirect_uri?logout=https://<?=$_SERVER['HTTP_HOST']?>/">Logout
<?php
foreach ($_SERVER as $key => $value) if (substr($key,0,4) == "OIDC") echo "
" . substr($key,5) . ": $value
\n";

Add logout link for OIDC Test RP

Add logout link for OIDC Test RP


<?php
/**
 * Created by PhpStorm.
 * User: Giansalex
 * Date: 15/07/2017
 * Time: 22:54.
 */

namespace Greenter\Ws\Header;

use SoapHeader;
use SoapVar;

/**
 * Class WSSESecurityHeader.
 */
class WSSESecurityHeader extends SoapHeader
{
    const WSS_NAMESPACE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';

    public function __construct($username, $password)
    {
        $security = new SoapVar(
            [new SoapVar(
                [
                    new SoapVar($username, XSD_STRING, null, null, 'Username', self::WSS_NAMESPACE),
                    new SoapVar($password, XSD_STRING, null, null, 'Password', self::WSS_NAMESPACE),
                ],
                SOAP_ENC_OBJECT,
                null,
                null,
                'UsernameToken',
                self::WSS_NAMESPACE
            )],
            SOAP_ENC_OBJECT
        );
        $this->SoapHeader(self::WSS_NAMESPACE, 'Security', $security, false);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Giansalex
 * Date: 15/07/2017
 * Time: 22:54.
 */

namespace Greenter\Ws\Header;

use SoapHeader;
use SoapVar;

/**
 * Class WSSESecurityHeader.
 */
class WSSESecurityHeader extends SoapHeader
{
    const WSS_NAMESPACE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
    const PASSWORD_TYPE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText';
    const PASSWORD_FORMAT = '<o:Password xmlns:o="%s" Type="%s">%s</o:Password>';

    public function __construct($username, $password)
    {
        $passwordXml = sprintf(self::PASSWORD_FORMAT, self::WSS_NAMESPACE, self::PASSWORD_TYPE, $password);
        $security = new SoapVar(
            [new SoapVar(
                [
                    new SoapVar($username, XSD_STRING, null, null, 'Username', self::WSS_NAMESPACE),
                    new SoapVar($passwordXml, XSD_ANYXML),
                ],
                SOAP_ENC_OBJECT,
                null,
                null,
                'UsernameToken',
                self::WSS_NAMESPACE
            )],
            SOAP_ENC_OBJECT
        );
        $this->SoapHeader(self::WSS_NAMESPACE, 'Security', $security, false);
    }
}

Add Type attribute to password (security header)


<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function signIn($user = null)
    {
        $this->clearRedisCache();

        $user = $user ?: create('App\User');

        $this->actingAs($user);

        return $this;
    }

    protected function clearRedisCache()
    {
        \Illuminate\Support\Facades\Cache::flush();
    }
}

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\Passport\Passport;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function signIn($user = null)
    {
        $this->clearRedisCache();

        $user = $user ?: create('App\User');

        $this->actingAs($user);

        return $this;
    }

    protected function signInViaPassport($user = null)
    {
        $this->clearRedisCache();

        $user = $user ?: create('App\User');

        Passport::actingAs($user);

        return $this;
    }

    protected function clearRedisCache()
    {
        \Illuminate\Support\Facades\Cache::flush();
    }
}

Add signInViaPassport() for api tests

Add signInViaPassport() for api tests


<?php

namespace RocketCode\Shopify;

/**
 * This trait should be used to implement the interface ShopifyApiUser
 */
trait UsesShopifyApi {
    /**
     * Get the Shopify API object to query Shopify
     *
     * @return \RocketCode\Shopify\API
     */
    public function getShopifyApi() {
        static $api;
        if (!($api instanceof API)) {
            $api = new API([
                'API_KEY' => env('SHOPIFY_APP_ID'),
                'API_SECRET' => env('SHOPIFY_APP_SECRET'),
                'SHOP_DOMAIN' => $this->getDomain(),
                'ACCESS_TOKEN' => $this->getAccessToken(),
            ]);
        }
        return $api;
    }

    /**
     * Returns the domain for the shop queried by the API
     *
     * @return string
     */
    abstract protected function getDomain();

    /**
     * Returns the access token for the shop queried by the API
     *
     * @return string
     */
    abstract protected function getAccessToken();
}

<?php

namespace RocketCode\Shopify;

/**
 * This trait should be used to implement the interface ShopifyApiUser
 */
trait UsesShopifyApi {
    protected $api;

    /**
     * Get the Shopify API object to query Shopify
     *
     * @return \RocketCode\Shopify\API
     */
    public function getShopifyApi() {
        if (!($this->api instanceof API)) {
            $this->api = new API([
                'API_KEY' => env('SHOPIFY_APP_ID'),
                'API_SECRET' => env('SHOPIFY_APP_SECRET'),
                'SHOP_DOMAIN' => $this->getDomain(),
                'ACCESS_TOKEN' => $this->getAccessToken(),
            ]);
        }
        return $this->api;
    }

    /**
     * Returns the domain for the shop queried by the API
     *
     * @return string
     */
    abstract protected function getDomain();

    /**
     * Returns the access token for the shop queried by the API
     *
     * @return string
     */
    abstract protected function getAccessToken();
}

Fix to getShopifyApi() so it correctly returns different instances when dealing with different shops


<?php

declare(strict_types=1);

namespace SimpleSAML\SAML2\XML\md;

use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;

use function filter_var;

/**
 * Abstract class implementing LocalizedURIType.
 *
 * @package simplesamlphp/saml2
 */
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
    /**
     * Validate the content of the element.
     *
     * @param string $content  The value to go in the XML textContent
     * @throws \Exception on failure
     * @return void
     */
    protected function validateContent(string $content): void
    {
        parent::validateContent($content);

        Assert::false(
            !empty($content) && !filter_var($content, FILTER_VALIDATE_URL),
            static::getQualifiedName() . ' is not a valid URL.',
            ProtocolViolationException::class,
        );
    }
}

<?php

declare(strict_types=1);

namespace SimpleSAML\SAML2\XML\md;

use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;

use function filter_var;

/**
 * Abstract class implementing LocalizedURIType.
 *
 * @package simplesamlphp/saml2
 */
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
    /**
     * Validate the content of the element.
     *
     * @param string $content  The value to go in the XML textContent
     * @throws \Exception on failure
     * @return void
     */
    protected function validateContent(string $content): void
    {
        parent::validateContent($content);

        Assert::false(
            !empty($content) && !filter_var($content, FILTER_VALIDATE_URL),
            $this->getQualifiedName() . ' is not a valid URL.',
            ProtocolViolationException::class,
        );
    }
}

Fix static call to non-static method

Fix static call to non-static method


<?php namespace App\Data;

use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Discussion extends Eloquent
{
	use SoftDeletes, PresentableTrait;

	protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = DiscussionPresenter::class;

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function author()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function replies()
	{
		return $this->hasMany(Reply::class);
	}

	public function topic()
	{
		return $this->belongsTo(Topic::class);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function addReply(array $data)
	{
		$this->replies()->create($data);
	}

	public function scopeFilter($query, $filters)
	{
		return $filters->apply($query);
	}
}

<?php namespace App\Data;

use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Discussion extends Eloquent
{
	use SoftDeletes, PresentableTrait;

	protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = DiscussionPresenter::class;

	protected static function boot()
	{
		parent::boot();

		static::addGlobalScope('replyCount', function ($builder) {
			$builder->withCount('replies');
		});
	}

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function author()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function replies()
	{
		return $this->hasMany(Reply::class);
	}

	public function topic()
	{
		return $this->belongsTo(Topic::class);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function addReply(array $data)
	{
		$this->replies()->create($data);
	}

	public function scopeFilter($query, $filters)
	{
		return $filters->apply($query);
	}
}

Add a global scope for the reply count

Add a global scope for the reply count


<?php

namespace Dmatthew\Brand\Block\Brand;

class View extends \Magento\Framework\View\Element\Template
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

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

        $this->pageConfig->getTitle()->set('Brands!!!');

        return $this;
    }

    /**
     * Retrieve current brand model object
     *
     * @return \Dmatthew\Brand\Model\Brand
     */
    public function getBrand()
    {
        if (!$this->hasData('current_brand')) {
            $this->setData('current_brand', $this->_coreRegistry->registry('current_brand'));
        }
        return $this->getData('current_brand');
    }
}

<?php

namespace Dmatthew\Brand\Block\Brand;

class View extends \Magento\Framework\View\Element\Template
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

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

        $brand = $this->getBrand();
        if ($brand) {
            $title = $brand->getName();
            if ($title) {
                $this->pageConfig->getTitle()->set($title);
            }
        }

        return $this;
    }

    /**
     * Retrieve current brand model object
     *
     * @return \Dmatthew\Brand\Model\Brand
     */
    public function getBrand()
    {
        if (!$this->hasData('current_brand')) {
            $this->setData('current_brand', $this->_coreRegistry->registry('current_brand'));
        }
        return $this->getData('current_brand');
    }
}

Set Brand name as page meta title.

Set Brand name as page meta title.


<?php
/**
 *
 * (c) Marco Bunge <marco_bunge@web.de>
 *
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
 *
 * Date: 12.02.2016
 * Time: 10:36
 *
 */

namespace Blast\Db\Data;

trait ImmutableDataObjectTrait
{
    /**
     * Receive data
     * @return array
     */
    public function getData()
    {
        return Helper::receiveDataFromObject($this);
    }
}

<?php
/**
 *
 * (c) Marco Bunge <marco_bunge@web.de>
 *
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
 *
 * Date: 12.02.2016
 * Time: 10:36
 *
 */

namespace Blast\Db\Data;

trait ImmutableDataObjectTrait
{
    /**
     * Receive data
     * @return array
     */
    public function getData()
    {
        return isset($this->data) ? $this->data : [];
    }
}

Fix recursion call on Hook of getData / setData on data objects


<?php

declare(strict_types=1);

namespace Dflydev\FigCookies;

use function array_filter;
use function assert;
use function explode;
use function is_array;
use function preg_split;
use function urldecode;

class StringUtil
{
    /** @return string[] */
    public static function splitOnAttributeDelimiter(string $string) : array
    {
        $splitAttributes = preg_split('@\s*[;]\s*@', $string);

        assert(is_array($splitAttributes));

        return array_filter($splitAttributes);
    }

    /** @return string[] */
    public static function splitCookiePair(string $string) : array
    {
        $pairParts    = explode('=', $string, 2);
        $pairParts[1] = urldecode($pairParts[1]) ?? '';

        return $pairParts;
    }
}

<?php

declare(strict_types=1);

namespace Dflydev\FigCookies;

use function array_filter;
use function assert;
use function explode;
use function is_array;
use function preg_split;
use function urldecode;

class StringUtil
{
    /** @return string[] */
    public static function splitOnAttributeDelimiter(string $string) : array
    {
        $splitAttributes = preg_split('@\s*[;]\s*@', $string);

        assert(is_array($splitAttributes));

        return array_filter($splitAttributes);
    }

    /** @return string[] */
    public static function splitCookiePair(string $string) : array
    {
        $pairParts    = explode('=', $string, 2);
        $pairParts[1] = urldecode($pairParts[1] ?? '');

        return $pairParts;
    }
}

Fix potential TypeError with malformed cookie


<?php

namespace Twig\Extension;

class GeshiExtension extends \Twig_Extension
{

    /**
     * @return array
     */
    public function getFilters()
    {
        return array(
            'geshi' => new \Twig_Filter_Method(
                    $this, 'parseGeshi', array('is_safe' => array('html'))
            )
        );
    }

    /**
     * @param string $sContent
     * @param string $sLanguage
     * @return string
     */
    public function parseGeshi($sContent, $sLanguage, $bUseClasses = false)
    {
        $oGeshi = new \GeSHi($sContent, $sLanguage);
        if ($bUseClasses) {
            $oGeshi->enable_classes();
        }
        return $oGeshi->parse_code();
    }

    /**
     * @return array
     */
    public function getTokenParsers()
    {
        return array(new \Twig\TokenParser\GeshiTokenParser());
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'geshi';
    }

}

<?php

namespace Twig\Extension;

class GeshiExtension extends \Twig_Extension
{

    /**
     * @return array
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('geshi', array($this, 'parseGeshi'), array('is_safe' => array('html'))),
        );
    }

    /**
     * @param string $sContent
     * @param string $sLanguage
     * @return string
     */
    public function parseGeshi($sContent, $sLanguage, $bUseClasses = false)
    {
        $oGeshi = new \GeSHi($sContent, $sLanguage);
        if ($bUseClasses) {
            $oGeshi->enable_classes();
        }
        return $oGeshi->parse_code();
    }

    /**
     * @return array
     */
    public function getTokenParsers()
    {
        return array(new \Twig\TokenParser\GeshiTokenParser());
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'geshi';
    }

}

Replace use of deprecated class "Twig_Filter_Method"


<?php

namespace JWX\JWT;

use JWX\JWT\Claim\Claim;

class Claims
{
	/**
	 * Claims
	 *
	 * @var Claim[] $_claims
	 */
	protected $_claims;

	/**
	 * Constructor
	 *
	 * @param Claim ...$claims
	 */
	public function __construct(Claim ...$claims) {
		$this->_claims = $claims;
	}

	/**
	 * Initialize from JSON
	 *
	 * @param string $json
	 * @throws \UnexpectedValueException
	 * @return self
	 */
	public static function fromJSON($json) {
		$claims = array();
		$fields = json_decode($json, true, 32, JSON_BIGINT_AS_STRING);
		if (!is_array($fields)) {
			throw new \UnexpectedValueException("Invalid JSON");
		}
		foreach ($fields as $name => $value) {
			$claims[] = Claim::fromNameAndValue($name, $value);
		}
		return new self(...$claims);
	}

	/**
	 * Convert to JSON
	 *
	 * @return string
	 */
	public function toJSON() {
		$data = array();
		foreach ($this->_claims as $claim) {
			$data[$claim->name()] = $claim->value();
		}
		return json_encode($data, JSON_FORCE_OBJECT);
	}
}

<?php

namespace JWX\JWT;

use JWX\JWT\Claim\Claim;

class Claims
{
	/**
	 * Claims
	 *
	 * @var Claim[] $_claims
	 */
	protected $_claims;

	/**
	 * Constructor
	 *
	 * @param Claim ...$claims
	 */
	public function __construct(Claim ...$claims) {
		$this->_claims = $claims;
	}

	/**
	 * Initialize from JSON
	 *
	 * @param string $json
	 * @throws \UnexpectedValueException
	 * @return self
	 */
	public static function fromJSON($json) {
		$claims = array();
		$fields = json_decode($json, true, 32, JSON_BIGINT_AS_STRING);
		if (!is_array($fields)) {
			throw new \UnexpectedValueException("Invalid JSON");
		}
		foreach ($fields as $name => $value) {
			$claims[] = Claim::fromNameAndValue($name, $value);
		}
		return new self(...$claims);
	}

	/**
	 * Convert to JSON
	 *
	 * @return string
	 */
	public function toJSON() {
		$data = array();
		foreach ($this->_claims as $claim) {
			$data[$claim->name()] = $claim->value();
		}
		return json_encode($data, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES);
	}
}

Add flag to not escape slashes in json encoding


<?php
	namespace Site\Page;

	class MetadataList {
		public $error;
		public $count = 0;

		public function find($parameters = array()) {
			$bind_params = array();
			$get_object_query = "
				SELECT	id
				FROM	page_metadata
				WHERE	id = id
			";

			if (!empty($parameters['page_id'])) {
				$get_object_query .= "
				AND		page_id = ?";
				array_push($bind_params,$parameters['page_id']);
			}

			$rs = $GLOBALS['_database']->Execute($get_object_query,$bind_params);
			if (! $rs) {
				$this->error = "SQL Error in Site::Page::MetadataList::find(): ".$GLOBALS['_database']->ErrorMsg();
				return null;
			}
			$metadatas = array();
			while(list($id) = $rs->FetchRow()) {
				$metadata = new \Site\Page\Metadata($id);
				array_push($metadatas,$metadata);
				$this->count ++;
			}
			return $metadatas;
		}

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

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

<?php
	namespace Site\Page;

	class MetadataList {
		public $error;
		public $count = 0;

		public function find($parameters = array()) {
			$bind_params = array();
			$get_object_query = "
				SELECT	id
				FROM	page_metadata
				WHERE	id = id
			";

			if (!empty($parameters['page_id'])) {
				$get_object_query .= "
				AND		page_id = ?";
				array_push($bind_params,$parameters['page_id']);
			}

			$rs = $GLOBALS['_database']->Execute($get_object_query,$bind_params);
			if (! $rs) {
				$this->error = "SQL Error in Site::Page::MetadataList::find(): ".$GLOBALS['_database']->ErrorMsg();
				return null;
			}
			$metadatas = array();
			while(list($id) = $rs->FetchRow()) {
				$metadata = new \Site\Page\Metadata($id);
				if (preg_match('/^[\w\_][\w\-\_\.]*$/',$metadata->key)) {
					array_push($metadatas,$metadata);
					$this->count ++;
				}
			}
			return $metadatas;
		}

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

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

Clean up page metadata keys

Clean up page metadata keys


<?php

/**
 * @group cache
 */
class CacheTest extends DatabaseTestCase {
	public function setUp() {
		DatabaseTestCase::setUp();
		BasicObject::invalidate_cache();
	}

	public function assertPreConditions() {
		global $cache;
		if($cache == false) {
			echo "Trying to run cached tests with cache disabled\n";
			exit(-1);
		}
	}

	public function testFromField() {
	}
}

<?php

/**
 * @group cache
 */
class CacheTest extends DatabaseTestCase {
	public function setUp() {
		DatabaseTestCase::setUp();
		BasicObject::invalidate_cache();
	}

	public function assertPreConditions() {
		global $cache;
		if($cache == false) {
			echo "Trying to run cached tests with cache disabled\n";
			exit(-1);
		}
	}

	public function testEditAndLoad() {
		$m1 = Blueprint::make('Model1');
		$m1 = Model1::from_id($m1->id);
		$val = $m1->int1 + 10;
		$m1->int1 = $val;
		$m1->commit();

		$m1 = Model1::from_id($m1->id);
		$this->assertEquals($val, $m1->int1);

	}
}

Add test for commit invalidating cache

Add test for commit invalidating cache


<?php

    define("SECONDS_BETWEEN_ALERTS", rand(10, 60));

    $alerts = array(
        "Coldest Air of the Season Sweeping Through Central and Southern States",
        "Belgium on 'high alert'",
        "Multiple raids in Brussels as police seek ISIS terrorists",
        "Syria fighters may be fueled by amphetamines",
        "Alien invasion? Strange sightings in Hong Kong",
        "Experts criticise WHO delay in sounding alarm over Ebola outbreak"
    );

    date_default_timezone_set("Europe/Madrid");
    header("Content-Type: text/event-stream\n\n");

    while (true) {
        sendAlert($alerts[rand(0, 5)]);

        ob_end_flush();
        flush();
        sleep(SECONDS_BETWEEN_ALERTS);
    }

    function sendAlert($message) {
        $date = date_create();
        $timestamp = date_timestamp_get($date);

        echo "data: { \"message\": \"$message\", \"timestamp\": $timestamp }\n\n";
    }

?>

<?php

    define("SECONDS_BETWEEN_ALERTS", rand(10, 60));

    $alerts = array(
        "Coldest Air of the Season Sweeping Through Central and Southern States",
        "Belgium on 'high alert'",
        "Multiple raids in Brussels as police seek ISIS terrorists",
        "Syria fighters may be fueled by amphetamines",
        "Alien invasion? Strange sightings in Hong Kong",
        "Experts criticise WHO delay in sounding alarm over Ebola outbreak"
    );

    date_default_timezone_set("Europe/Madrid");
    header("Content-Type: text/event-stream\n\n");

    while (true) {
        sleep(SECONDS_BETWEEN_ALERTS);

        sendAlert($alerts[rand(0, 5)]);

        ob_end_flush();
        flush();
    }

    function sendAlert($message) {
        $date = date_create();
        $timestamp = date_timestamp_get($date);

        echo "data: { \"message\": \"$message\", \"timestamp\": $timestamp }\n\n";
    }

?>

Move sleep call to begining of loop

Move sleep call to begining of loop


<?php
/**
 * A few common settings for all unit tests.
 *
 * Also remember do define the @package attribute for your test class to make it appear under
 * the right package in unit test and code coverage reports.
 */

define('PRADO_TEST_RUN', true);
define('PRADO_FRAMEWORK_DIR', dirname(__FILE__).'/../../framework');
define('VENDOR_DIR', dirname(__FILE__).'/../../vendor');
set_include_path(PRADO_FRAMEWORK_DIR.PATH_SEPARATOR.get_include_path());

if (!@include_once VENDOR_DIR.'/autoload.php') {
    die('You must set up the project dependencies, run the following commands:
        wget http://getcomposer.org/composer.phar
        php composer.phar install');
}

require_once(PRADO_FRAMEWORK_DIR.'/prado.php');

// for FunctionalTests
require_once(__DIR__.'/PradoGenericSeleniumTest.php');

<?php
/**
 * A few common settings for all unit tests.
 *
 * Also remember do define the @package attribute for your test class to make it appear under
 * the right package in unit test and code coverage reports.
 */

define('PRADO_TEST_RUN', true);
define('PRADO_FRAMEWORK_DIR', dirname(__FILE__).'/../../framework');
define('VENDOR_DIR', dirname(__FILE__).'/../../vendor');
set_include_path(PRADO_FRAMEWORK_DIR.PATH_SEPARATOR.get_include_path());
// coverage tests waste a lot of memory!
ini_set('memory_limit', '1G');

if (!@include_once VENDOR_DIR.'/autoload.php') {
    die('You must set up the project dependencies, run the following commands:
        wget http://getcomposer.org/composer.phar
        php composer.phar install');
}

require_once(PRADO_FRAMEWORK_DIR.'/prado.php');

// for FunctionalTests
require_once(__DIR__.'/PradoGenericSeleniumTest.php');

Raise memory limit for coverage tests

Raise memory limit for coverage tests


<?php
namespace Czim\CmsModels\Test;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{

    /**
     * {@inheritdoc}
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('translatable.locales', [ 'en', 'nl' ]);
        $app['config']->set('translatable.use_fallback', true);
        $app['config']->set('translatable.fallback_locale', 'en');

        $app['config']->set('cms-models.analyzer.traits.listify', [
            \Czim\Listify\Listify::class,
        ]);

        $app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views'));
    }

}

<?php
namespace Czim\CmsModels\Test;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{

    /**
     * {@inheritdoc}
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('translatable.locales', [ 'en', 'nl' ]);
        $app['config']->set('translatable.use_fallback', true);
        $app['config']->set('translatable.fallback_locale', 'en');

        $app['config']->set('cms-models', include(realpath(dirname(__DIR__) . '/config/cms-models.php')));
        $app['config']->set('cms-models.analyzer.database.class', null);

        $app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views'));
    }

}

Test fix: always use full cms-models config state as default


<?php
$code = file_get_contents($file);
$obj = null;

if (defined('tempns'))
  if (!function_exists('uopz_undefine'))
    die('You need uopz pecl extension for complex class cross includes');
  else
    uopz_undefine('tempns');

define('tempns', 'tempns_'.md5(microtime()));
//$new_source = preg_replace("/class(\s+)({$module})/", "class /".tempns."/$module", $code);
$code = str_replace('<?php', 'namespace '.tempns.';', $code);
$code = str_replace(' api', '\\api', $code);

eval($code);

$classname = "\\".tempns."\\$module";
$obj = new $classname;

<?php
$code = file_get_contents($file);
$obj = null;

if (defined('tempns'))
  if (!function_exists('uopz_undefine'))
    die('You need uopz pecl extension for complex class cross includes');
  else
    uopz_undefine('tempns');

define('tempns', 'tempns_'.md5(microtime()));
//$new_source = preg_replace("/class(\s+)({$module})/", "class /".tempns."/$module", $code);
$code = str_replace('<?php', 'namespace '.tempns.';', $code);
$code = preg_replace('/ api\s*\n/', '\\api', $code);

eval($code);

$classname = "\\".tempns."\\$module";
$obj = new $classname;

Fix first crappy bug in this crappy hack


<?php

namespace AbleCore\Modules;

class ImageStyleManager {

	protected $styles = array();

	/**
	 * Init
	 *
	 * @return ImageStyleManager A new instance of the ImageStyleManager.
	 */
	public static function init()
	{
		return new self();
	}

	/**
	 * Define
	 *
	 * @param string $name    The machine name of the image style.
	 * @param string $label   The human-readable label of the image style.
	 * @param array  $effects An array of effects to attach to the style.
	 *
	 * @return ImageStyle The generated image style.
	 */
	public function define($name, $label, $effects = array())
	{
		$style = new ImageStyle($name, $label, $effects);
		$this->styles[] = $name;
		return $style;
	}

	/**
	 * Finish
	 *
	 * @return array The final result, ready to pass to hook_image_default_styles()
	 */
	public function fin()
	{
		$generated = array();
		foreach ($this->styles as $style) {
			/** @var ImageStyle $style */
			$generated[$style->getName()] = $style->getDefinition();
		}

		return $generated;
	}

}

<?php

namespace AbleCore\Modules;

class ImageStyleManager {

	protected $styles = array();

	/**
	 * Init
	 *
	 * @return ImageStyleManager A new instance of the ImageStyleManager.
	 */
	public static function init()
	{
		return new self();
	}

	/**
	 * Define
	 *
	 * @param string $name    The machine name of the image style.
	 * @param string $label   The human-readable label of the image style.
	 * @param array  $effects An array of effects to attach to the style.
	 *
	 * @return ImageStyle The generated image style.
	 */
	public function define($name, $label, $effects = array())
	{
		$style = new ImageStyle($name, $label, $effects);
		$this->styles[] = $style;
		return $style;
	}

	/**
	 * Finish
	 *
	 * @return array The final result, ready to pass to hook_image_default_styles()
	 */
	public function fin()
	{
		$generated = array();
		foreach ($this->styles as $style) {
			/** @var ImageStyle $style */
			$generated[$style->getName()] = $style->getDefinition();
		}

		return $generated;
	}

}

Make sure we assign the right thing to the styles array.


<?php

namespace Oro\Bundle\ApiBundle\Config;

use Oro\Bundle\ApiBundle\Processor\Config\ConfigContext;

/**
 * An instance of this class can be added to the config extras of the Context
 * to request to add related entities to a result.
 */
class ExpandRelatedEntitiesConfigExtra implements ConfigExtraInterface
{
    const NAME = 'expand_related_entities';

    /** @var string[] */
    protected $expandedEntities;

    /**
     * @param string[] $expandedEntities The list of related entities.
     *                                   Each item can be an association name or a path to a nested association.
     *                                   Example: ["comments", "comments.author"]
     *                                   Where "comments" is an association under the "articles" entity,
     *                                   "author" is an association under the "comments" entity.
     */
    public function __construct(array $expandedEntities)
    {
        $this->expandedEntities = $expandedEntities;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function configureContext(ConfigContext $context)
    {
        $context->set(self::NAME, $this->expandedEntities);
    }

    /**
     * {@inheritdoc}
     */
    public function isInheritable()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheKeyPart()
    {
        return 'expand:' . implode(',', $this->expandedEntities);
    }
}

<?php

namespace Oro\Bundle\ApiBundle\Config;

use Oro\Bundle\ApiBundle\Processor\Config\ConfigContext;

/**
 * An instance of this class can be added to the config extras of the Context
 * to request to add related entities to a result.
 */
class ExpandRelatedEntitiesConfigExtra implements ConfigExtraInterface
{
    const NAME = 'expand_related_entities';

    /** @var string[] */
    protected $expandedEntities;

    /**
     * @param string[] $expandedEntities The list of related entities.
     *                                   Each item can be an association name or a path to a nested association.
     *                                   Example: ["comments", "comments.author"]
     *                                   Where "comments" is an association under a primary entity,
     *                                   "author" is an association under the "comments" entity.
     */
    public function __construct(array $expandedEntities)
    {
        $this->expandedEntities = $expandedEntities;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function configureContext(ConfigContext $context)
    {
        $context->set(self::NAME, $this->expandedEntities);
    }

    /**
     * {@inheritdoc}
     */
    public function isInheritable()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheKeyPart()
    {
        return 'expand:' . implode(',', $this->expandedEntities);
    }
}

BAP-9376: Create unit tests for ApiBundle. Fix ExpandRelatedEntities and FilterFieldsByExtra. Unit tests for ExpandRelatedEntities, FilterFieldsByExtra, CompleteDefinition, EnsureInitialized


<?php

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

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

<?php

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

if (class_exists('Tideways\Profiler')) {
    \Tideways\Profiler::start(array('api_key' => trim(file_get_contents(__DIR__.'/tideways.key'))));
}

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

Add tideways config to getcomposer.org

Add tideways config to getcomposer.org


<?php
namespace Mailgun\Connection\Exceptions;

class GenericHTTPError extends \Exception{}

?>

<?php
namespace Mailgun\Connection\Exceptions;

class GenericHTTPError extends \Exception
{
	protected $httpResponseCode;
	protected $httpResponseBody;

	public function __construct($message=null, $response_code=null, $response_body=null, $code=0, \Exception $previous=null) {
		parent::__construct($message, $code, $previous);

		$this->httpResponseCode = $response_code;
		$this->httpResponseBody = $response_body;
	}

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

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

?>

Add HTTP properties to generic error

Add HTTP properties to generic error

Allows generic HTTP error to accept more detailed information about the response from the server.


<?php

namespace Casinelli\CampaignMonitor;

class CampaignMonitor
{
    protected $app;

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

    public function campaigns($campaignId = null)
    {
        return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens());
    }

    public function clients($clientId = null)
    {
        return new \CS_REST_Clients($clientId, $this->getAuthTokens());
    }

    public function lists($listId = null)
    {
        return new \CS_REST_Lists($listId, $this->getAuthTokens());
    }

    public function segments($segmentId = null)
    {
        return new \CS_REST_Segments($segmentId, $this->getAuthTokens());
    }

    public function template($templateId = null)
    {
        return new \CS_REST_Templates($templateId, $this->getAuthTokens());
    }

    public function subscribers($listId = null)
    {
        return new \CS_REST_Subscribers($listId, $this->getAuthTokens());
    }

    public function classicSend($clientId = null)
    {
        return new \CS_REST_Transactional_ClassicEmail($this->getAuthTokens(), $clientId);
    }

    protected function getAuthTokens()
    {
        return [
            'api_key' => $this->app['config']['campaignmonitor.api_key'],
        ];
    }
}

<?php

namespace Casinelli\CampaignMonitor;

class CampaignMonitor
{
    protected $app;

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

    public function campaigns($campaignId = null)
    {
        return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens());
    }

    public function clients($clientId = null)
    {
        return new \CS_REST_Clients($clientId, $this->getAuthTokens());
    }

    public function lists($listId = null)
    {
        return new \CS_REST_Lists($listId, $this->getAuthTokens());
    }

    public function segments($segmentId = null)
    {
        return new \CS_REST_Segments($segmentId, $this->getAuthTokens());
    }

    public function template($templateId = null)
    {
        return new \CS_REST_Templates($templateId, $this->getAuthTokens());
    }

    public function subscribers($listId = null)
    {
        return new \CS_REST_Subscribers($listId, $this->getAuthTokens());
    }

    public function classicSend($clientId = null)
    {
        return new \CS_REST_Transactional_ClassicEmail($this->getAuthTokens(), $clientId);
    }

    public function smartSend($smartId = null, $clientId)
    {
        return new \CS_REST_Transactional_SmartEmail($smartId, $this->getAuthTokens(), $clientId);
    }

    protected function getAuthTokens()
    {
        return [
            'api_key' => $this->app['config']['campaignmonitor.api_key'],
        ];
    }
}

Add support for smart transactional emails


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Taxonomy\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;

interface TaxonRepositoryInterface extends RepositoryInterface
{
    /**
     * @return array|TaxonInterface[]
     */
    public function findChildren(string $parentCode, ?string $locale = null): array;

    /**
     * @return array|TaxonInterface[]
     */
    public function findRootNodes(): array;

    public function findOneBySlug(string $slug, string $locale): ?TaxonInterface;

    /**
     * @return array|TaxonInterface[]
     */
    public function findByName(string $name, string $locale): array;

    /**
     * @return array|TaxonInterface[]
     */
    public function findByNamePart(string $phrase, ?string $locale = null): array;

    public function createListQueryBuilder(): QueryBuilder;
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Taxonomy\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;

interface TaxonRepositoryInterface extends RepositoryInterface
{
    /**
     * @return array|TaxonInterface[]
     */
    public function findChildren(string $parentCode, ?string $locale = null): array;

    /**
     * @return array|TaxonInterface[]
     */
    public function findRootNodes(): array;

    public function findOneBySlug(string $slug, string $locale): ?TaxonInterface;

    /**
     * @return array|TaxonInterface[]
     */
    public function findByName(string $name, string $locale): array;

    /**
     * @return array|TaxonInterface[]
     */
    public function findByNamePart(string $phrase, ?string $locale = null, ?int $limit = null): array;

    public function createListQueryBuilder(): QueryBuilder;
}

Add ability to limit products and taxons when looking for name part


<?php

class testRuleAppliesToVariableNameWithEmptySubtractSuffixes
{
    private $permissionsRepository;
}

<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

class testRuleAppliesToVariableNameWithEmptySubtractSuffixes
{
    private $permissionsRepository;
}

Add forgotten file doc block

Add forgotten file doc block


<?php
/**
 * Created by PhpStorm.
 * User: seyfer
 * Date: 09.08.17
 * Time: 17:03
 */

namespace Sly\Sly\NotificationPusher\Adapter;

use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;

/**
 * Class ApnsAPI
 * @package Sly\Sly\NotificationPusher\Adapter
 *
 * todo: implement with edamov/pushok
 */
class ApnsAPI extends BaseAdapter
{

    /**
     * Push.
     *
     * @param \Sly\NotificationPusher\Model\PushInterface $push Push
     *
     * @return \Sly\NotificationPusher\Collection\DeviceCollection
     */
    public function push(PushInterface $push)
    {
        // TODO: Implement push() method.
    }

    /**
     * Supports.
     *
     * @param string $token Token
     *
     * @return boolean
     */
    public function supports($token)
    {
        // TODO: Implement supports() method.
    }

    /**
     * Get defined parameters.
     *
     * @return array
     */
    public function getDefinedParameters()
    {
        // TODO: Implement getDefinedParameters() method.
    }

    /**
     * Get default parameters.
     *
     * @return array
     */
    public function getDefaultParameters()
    {
        // TODO: Implement getDefaultParameters() method.
    }

    /**
     * Get required parameters.
     *
     * @return array
     */
    public function getRequiredParameters()
    {
        // TODO: Implement getRequiredParameters() method.
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: seyfer
 * Date: 09.08.17
 * Time: 17:03
 */

namespace Sly\NotificationPusher\Adapter;

use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;

/**
 * Class ApnsAPI
 * @package Sly\Sly\NotificationPusher\Adapter
 *
 * todo: implement with edamov/pushok
 */
class ApnsAPI extends BaseAdapter
{

    /**
     * Push.
     *
     * @param \Sly\NotificationPusher\Model\PushInterface $push Push
     *
     * @return \Sly\NotificationPusher\Collection\DeviceCollection
     */
    public function push(PushInterface $push)
    {
        // TODO: Implement push() method.
    }

    /**
     * Supports.
     *
     * @param string $token Token
     *
     * @return boolean
     */
    public function supports($token)
    {
        // TODO: Implement supports() method.
    }

    /**
     * Get defined parameters.
     *
     * @return array
     */
    public function getDefinedParameters()
    {
        // TODO: Implement getDefinedParameters() method.
    }

    /**
     * Get default parameters.
     *
     * @return array
     */
    public function getDefaultParameters()
    {
        // TODO: Implement getDefaultParameters() method.
    }

    /**
     * Get required parameters.
     *
     * @return array
     */
    public function getRequiredParameters()
    {
        // TODO: Implement getRequiredParameters() method.
    }
}

Fix PSR-4 fix for Composer deprecation

Fix PSR-4 fix for Composer deprecation

Composer:

Deprecation Notice: Class Sly\Sly\NotificationPusher\Adapter\ApnsAPI located in ./vendor/sly/notification-pusher/src/Sly/NotificationPusher/Adapter/ApnsAPI.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in /vendor/composer/composer/src/Composer/Autoload/ClassMapGenerator.php:185

The namespace just needs to be updated.


<?php

declare(strict_types=1);

namespace League\Tactician;

/**
 * Marker interface for all Tactician exceptions
 */
interface Exception
{
}

<?php

declare(strict_types=1);

namespace League\Tactician;

use Throwable;

/**
 * Marker interface for all Tactician exceptions
 */
interface Exception extends Throwable
{
}

Make marker interface extend throwable

Make marker interface extend throwable

This makes sure the interface can only be used by exceptions/errors, and
it makes more sense to be catched.


<?php

/**
 * This file contains an extension for the base controller
 * class, which implements additional features specifically
 * required by the CLI.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * CLI Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class CliController extends Controller
{

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "not implemented!\n";
    }

    /**
     * Default method as defined in conf.application.inc.php
     *
     * @return void
     */
    abstract public function index();

}

?>

<?php

/**
 * This file contains an extension for the base controller
 * class, which implements additional features specifically
 * required by the CLI.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * CLI Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class CliController extends Controller
{

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

    /**
     * Destructor.
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls.
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "not implemented!\n";
    }

    /**
     * Default method as defined in conf.application.inc.php.
     *
     * @return void
     */
    abstract public function index();

}

?>

system: Fix style issues for clicontroller class


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Resource\Model;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
interface ToggleableInterface
{
    /**
     * @return bool
     */
    public function isEnabled(): bool;

    /**
     * @param bool $enabled
     */
    public function setEnabled(?bool $enabled): void;

    public function enable(): void;

    public function disable(): void;
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Resource\Model;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
interface ToggleableInterface
{
    /**
     * Missing scalar typehint because it conflicts with AdvancedUserInterface.
     *
     * @return bool
     */
    public function isEnabled();

    /**
     * @param bool $enabled
     */
    public function setEnabled(?bool $enabled): void;

    public function enable(): void;

    public function disable(): void;
}

Adjust to scalar types introduced in Resource component & bundle


<?php

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

namespace Imagine\Imagick;

use Imagine\Image\AbstractImagineTest;
use Imagine\Image\Box;

class ImagineTest extends AbstractImagineTest
{
    protected function setUp()
    {
        parent::setUp();

        if (!class_exists('Imagick')) {
            $this->markTestSkipped('Imagick is not installed');
        }
    }

    protected function getEstimatedFontBox()
    {
        return new Box(116, 55);
    }

    protected function getImagine()
    {
        return new Imagine();
    }
}

<?php

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

namespace Imagine\Imagick;

use Imagine\Image\AbstractImagineTest;
use Imagine\Image\Box;

class ImagineTest extends AbstractImagineTest
{
    protected function setUp()
    {
        parent::setUp();

        if (!class_exists('Imagick')) {
            $this->markTestSkipped('Imagick is not installed');
        }
    }

    protected function getEstimatedFontBox()
    {
        return new Box(115, 55);
    }

    protected function getImagine()
    {
        return new Imagine();
    }
}

Fix unit tests box size

Fix unit tests box size


<?php
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
require_once CAKE . 'Test' . DS . 'CASE' . DS . 'Model' . DS . 'models.php';
class DeletedAtBehaviorTest extends CakeTestCase {

}

<?php
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
require_once CAKE . 'Test' . DS . 'CASE' . DS . 'Model' . DS . 'models.php';
class DeletedAtBehaviorTest extends CakeTestCase {

  public $fixtures = array(
    'plugin.deleted_at.deleted_user', 'core.user'
  );

  public function setUp() {
    parent::setUp();
    $this->DeletedUser = ClassRegistry::init('User');
    $this->DeletedUser->useTable = 'deleted_users';
    $this->DeletedUser->Behaviors->load('DeletedAt.DeletedAt');
  }

  public function tearDown() {
    unset($this->DeletedUser);
    parent::tearDown();
  }

}

Add initial code for setup/teardown of test cases


<?php echo __('Welcome'); ?>

    <?php foreach(get_recent_collections(2) as $collection): ?>

                <?php
                $title = metadata($collection, array('Dublin Core', 'Title'));

                $queryParams = array(
                    'collection' => $collection->id,
                    'sort_field' => 'Dublin Core,Title'
                );

                echo link_to('items', 'browse', $title, array(), $queryParams);
                ?>

            <?php if ($description = metadata($collection, array('Dublin Core', 'Description'))): ?>

<?php echo $description; ?>

            <?php endif; ?>

Browse Sub-Collections

                <?php foreach (metadata($collection, array('Dublin Core', 'Subject'), array('all' => true)) as $subject): ?>

                        <?php
                        $queryParams = array(
                            'tags' => $subject,
                            'collection' => $collection->id,
                            'sort_field' => 'Dublin Core,Title'
                        );

                        echo link_to('items', 'browse', $subject, array(), $queryParams);
                        ?>

                <?php endforeach; ?>

    <?php endforeach; ?>

<?php $collections = get_records('Collection'); ?>

<?php echo __('Welcome'); ?>

    <?php foreach($collections as $collection): ?>

                <?php
                $title = metadata($collection, array('Dublin Core', 'Title'));

                $queryParams = array(
                    'collection' => $collection->id,
                    'sort_field' => 'Dublin Core,Title'
                );

                echo link_to('items', 'browse', $title, array(), $queryParams);
                ?>

            <?php if ($description = metadata($collection, array('Dublin Core', 'Description'))): ?>

<?php echo $description; ?>

            <?php endif; ?>

Browse Sub-Collections

                <?php foreach (metadata($collection, array('Dublin Core', 'Subject'), array('all' => true)) as $subject): ?>

                        <?php
                        $queryParams = array(
                            'tags' => $subject,
                            'collection' => $collection->id,
                            'sort_field' => 'Dublin Core,Title'
                        );

                        echo link_to('items', 'browse', $subject, array(), $queryParams);
                        ?>

                <?php endforeach; ?>

    <?php endforeach; ?>

Change Finding Aids homepage to show more collections than two.


<?php
/**
 * WordPress_Sniffs_VIP_SessionVariableUsageSniff
 *
 * Discourages the use of the session variable
 *
 * @category PHP
 * @package  PHP_CodeSniffer
 * @author   Shady Sharaf <shady@x-team.com>
 * @link     https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75
 */
class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff
{

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

    }//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.
     *
     * @todo Allow T_CONSTANT_ENCAPSED_STRING?
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) {
        	$phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr);
        }

    }//end process()

}//end class

<?php
/**
 * WordPress_Sniffs_VIP_SessionVariableUsageSniff
 *
 * Discourages the use of the session variable.
 * Creating a session writes a file to the server and is unreliable in a multi-server environment.
 *
 * @category PHP
 * @package  PHP_CodeSniffer
 * @author   Shady Sharaf <shady@x-team.com>
 * @link     https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75
 */
class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff
{

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

    }//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.
     *
     * @todo Allow T_CONSTANT_ENCAPSED_STRING?
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) {
        	$phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr);
        }

    }//end process()

}//end class

Add explicit reasoning for session sniff

From https://vip.wordpress.com/documentation/code-review-what-we-look-for/#session_start-and-other-session-related-functions, linked in #75