<?php

namespace FD\PrivateMessageBundle\Validator;

use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator.
 */
class ConversationValidator
{
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        self::validateRecipients($conversation, $context);
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        // This could be NULL or array.
        $recipients = $conversation->getRecipients();

        if (is_array($recipients) && in_array($conversation->getAuthor(), $recipients)) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

<?php

namespace FD\PrivateMessageBundle\Validator;

use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator.
 */
class ConversationValidator
{
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        self::validateRecipients($conversation, $context);
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        // This could be NULL or array.
        $recipients = $conversation->getRecipients();

        if ($recipients->contains($conversation->getAuthor())) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

Fix Conversation validation on recipients


<?php

namespace Symfony\Component\Serializer\Tests\Normalizer\Features;

class ObjectDummy
{
    protected $foo;
    /**
     * @var array
     */
    public $bar;
    private $baz;
    protected $camelCase;
    protected $object;

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

    public function setFoo($foo)
    {
        $this->foo = $foo;
    }

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

    public function setBaz($baz)
    {
        $this->baz = $baz;
    }

    public function getFooBar()
    {
        return $this->foo.$this->bar;
    }

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

    public function setCamelCase($camelCase)
    {
        $this->camelCase = $camelCase;
    }

    public function otherMethod()
    {
        throw new \RuntimeException('Dummy::otherMethod() should not be called');
    }

    public function setObject($object)
    {
        $this->object = $object;
    }

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

<?php

namespace Symfony\Component\Serializer\Tests\Normalizer\Features;

#[\AllowDynamicProperties]
class ObjectDummy
{
    protected $foo;
    /**
     * @var array
     */
    public $bar;
    private $baz;
    protected $camelCase;
    protected $object;

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

    public function setFoo($foo)
    {
        $this->foo = $foo;
    }

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

    public function setBaz($baz)
    {
        $this->baz = $baz;
    }

    public function getFooBar()
    {
        return $this->foo.$this->bar;
    }

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

    public function setCamelCase($camelCase)
    {
        $this->camelCase = $camelCase;
    }

    public function otherMethod()
    {
        throw new \RuntimeException('Dummy::otherMethod() should not be called');
    }

    public function setObject($object)
    {
        $this->object = $object;
    }

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

Fix deprecations on PHP 8.2

Fix deprecations on PHP 8.2


<?php
require_once("database.php");
require_once("templating.php");

if(!$logged_in) {
	$smarty->display("login.tpl");
	die();
}

if(isset($_POST['invite'])) {

	$errors = "";
	$email = $_POST['email'];
	if(empty($email)) {
		$errors .= "You must enter an e-mail address.<br />";
	}

	if(empty($errors)) {
		$code = md5(md5($username) . time());
		$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
			. $mdb2->quote($username, "text") . ", "
			. $mdb2->quote($code, "text") . ")");

		$url = $base_url . "/register.php?authcode=" . $code;
		$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
		mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n Just visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
		$smarty->assign("sent", true);
	} else {
		$smarty->assign("errors", $errors);
	}

}

$smarty->display("invite.tpl");
?>

<?php
require_once("database.php");
require_once("templating.php");

if(!$logged_in) {
	$smarty->display("login.tpl");
	die();
}

if(isset($_POST['invite'])) {

	$errors = "";
	$email = $_POST['email'];
	if(empty($email)) {
		$errors .= "You must enter an e-mail address.<br />";
	}

	if(empty($errors)) {
		$code = md5(md5($username) . time());
		$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
			. $mdb2->quote($username, "text") . ", "
			. $mdb2->quote($code, "text") . ")");

		$url = $base_url . "/register.php?authcode=" . $code;
		$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
		mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n\nJust visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
		$smarty->assign("sent", true);
	} else {
		$smarty->assign("errors", $errors);
	}

}

$smarty->display("invite.tpl");
?>

Fix formatting of invitation e-mail slightly.


<?php

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

class RemoveEventIdFromPhotos extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('photos', function (Blueprint $table) {
            $table->dropForeign('photos_event_id_foreign');
            $table->dropIndex('photos_event_id_index');
            $table->dropColumn('event_id');

            $table->dropForeign('photos_signup_id_foreign');
            $table->dropIndex('photos_signup_id_index');
            $table->dropColumn('signup_id');

            $table->increments('id')->first();
        });
    }

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

            $table->integer('event_id')->unsigned()->index()->comment('The event this post corresponds to.');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');

            $table->integer('signup_id')->unsigned()->index()->comment('The signup this Post references.');
            $table->foreign('signup_id')->references('id')->on('signups')->onDelete('cascade');
        });
    }
}

<?php

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

class RemoveEventIdFromPhotos extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('photos', function (Blueprint $table) {
            $table->dropForeign('photos_event_id_foreign');
            $table->dropIndex('photos_event_id_index');
            $table->dropColumn('event_id');

            $table->dropForeign('photos_signup_id_foreign');
            $table->dropIndex('photos_signup_id_index');
            $table->dropColumn('signup_id');

            $table->increments('id')->first();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('photos', function (Blueprint $table) {
            $table->integer('event_id')->unsigned()->nullable()->index()->comment('The event this post corresponds to.');
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');

            $table->integer('signup_id')->unsigned()->nullable()->index()->comment('The signup this Post references.');
            $table->foreign('signup_id')->references('id')->on('signups')->onDelete('cascade');

            $table->dropColumn('id');

        });
    }
}

Allow foriegn keys on photo table to default to null so we can rollback migrations


<?php
namespace Se7enChat\src;

class Autoloader
{
    private $projectRoot;

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

    public function load()
    {
        // Load the libraries included by Composer.
        require __DIR__ . '/../vendor/autoload.php';

        spl_autoload_register(array($this, 'requireFile'));
    }

    private function requireFile($className)
    {
        $path = sprintf('%s%s.php',
            $this->projectRoot, str_replace('\\', '/', $className));
        if (preg_match('/^Se7enChat/', $className)) {
            require $path;
        }
    }
}

<?php
namespace Se7enChat\src;

class Autoloader
{
    private $projectRoot;

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

    public function load()
    {
        // Load the libraries included by Composer.
        require __DIR__ . '/../vendor/autoload.php';

        spl_autoload_register(array($this, 'requireFile'));
    }

    private function requireFile($className)
    {
        $path = sprintf('%s%s.php',
            $this->projectRoot, str_replace('\\', '/', $className));
        if (preg_match('/^Se7enChat/', $className) && !class_exists($className)) {
            require $path;
        }
    }
}

Update autoloader to only load a class if it has not already been loaded.

Hopefully this will help keep the memory usage down.

Signed-off-by: Se7enChat <e5dc7202134ade0d04c45466a5972470210b05f6@zoho.com>


<?php
/*
 * This file is part of Raven.
 *
 * (c) Sentry Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Raven Breadcrumbs
 *
 * @package raven
 */

class Raven_Breadcrumbs
{
    public function __construct($size = 100)
    {
        $this->count = 0;
        $this->pos = 0;
        $this->size = $size;
        $this->buffer = array();
    }

    public function record($crumb)
    {
        $this->buffer[$this->pos] = $crumb;
        $this->pos = ($this->pos + 1) % $this->size;
        $this->count++;
    }

    public function fetch()
    {
        $results = array();
        for ($i = 0; $i <= ($this->size - 1); $i++) {
            $node = @$this->buffer[($this->pos + $i) % $this->size];

            if (isset($node)) {
                $results[] = $node;
            }
        }
        return $results;
    }

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

    public function to_json()
    {
        return array(
            'values' => $this->fetch(),
        );
    }
}

<?php
/*
 * This file is part of Raven.
 *
 * (c) Sentry Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Raven Breadcrumbs
 *
 * @package raven
 */

class Raven_Breadcrumbs
{
    public function __construct($size = 100)
    {
        $this->count = 0;
        $this->pos = 0;
        $this->size = $size;
        $this->buffer = array();
    }

    public function record($crumb)
    {
        if (empty($crumb['timestamp'])) {
            $crumb['timestamp'] = microtime(true);
        }
        $this->buffer[$this->pos] = $crumb;
        $this->pos = ($this->pos + 1) % $this->size;
        $this->count++;
    }

    public function fetch()
    {
        $results = array();
        for ($i = 0; $i <= ($this->size - 1); $i++) {
            $node = @$this->buffer[($this->pos + $i) % $this->size];

            if (isset($node)) {
                $results[] = $node;
            }
        }
        return $results;
    }

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

    public function to_json()
    {
        return array(
            'values' => $this->fetch(),
        );
    }
}

Add timestamp when none present

Add timestamp when none present


<?php

/*
 * This file is part of StyleCI.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace StyleCI\Config;

/**
 * This is the array helper class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 * @author Joseph Cohen <joe@alt-three.com>
 */
class Arr
{
    /**
     * Get an item from an array.
     *
     * @param array  $array
     * @param string $key
     * @param mixed  $default
     *
     * @return mixed
     */
    public static function get(&$array, $key, $default = null)
    {
        return isset($array[$key]) ? $array[$key] : $default;
    }

    /**
     * Add an item to an array.
     *
     * @param array $array
     * @param mixed $item
     *
     * @return void
     */
    public static function add(&$array, $item)
    {
        if (!in_array($item, $array, true)) {
            $array[] = $item;
        }
    }

    /**
     * Remove an item from an array.
     *
     * @param array $array
     * @param mixed $item
     *
     * @return void
     */
    public static function remove(&$array, $item)
    {
        $index = array_search($item, $array, true);

        if ($index !== false) {
            unset($array[$index]);
        }
    }
}

<?php

/*
 * This file is part of StyleCI.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace StyleCI\Config;

/**
 * This is the array helper class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 * @author Joseph Cohen <joe@alt-three.com>
 */
class Arr
{
    /**
     * Get an item from an array.
     *
     * @param array  $array
     * @param string $key
     * @param mixed  $default
     *
     * @return mixed
     */
    public static function get(&$array, $key, $default = null)
    {
        return isset($array[$key]) ? $array[$key] : $default;
    }

    /**
     * Add an item to an array.
     *
     * @param array $array
     * @param mixed $item
     *
     * @return bool
     */
    public static function add(&$array, $item)
    {
        if (!in_array($item, $array, true)) {
            $array[] = $item;

            return true;
        }

        return false;
    }

    /**
     * Remove an item from an array.
     *
     * @param array $array
     * @param mixed $item
     *
     * @return bool
     */
    public static function remove(&$array, $item)
    {
        $index = array_search($item, $array, true);

        if ($index !== false) {
            unset($array[$index]);

            return true;
        }

        return false;
    }
}

Make the array functions indicate if anything happened


<?php
/**
 * @package Awoods/World
 */
namespace Awoods\World;

interface CountryInterface {

	/**
	 * @return string
	 */
	public function getName();

	/**
	 * @return string
	 */
	public function getFullName();

	/**
	 * @param string $postalCode
	 *
	 * @return bool
	 */
	public function isPostalCodeValid($postalCode);

	/**
	 * Determine if the provided phone number looks correct.
	 *
	 * @param string $phoneNumber
	 * @param bool $strict Optional. Default is false. Do you want interpret the value according to the country standard?
	 *
	 * @return bool
	 */
	public function isPhoneNumberValid($phoneNumber, $strict = false);
}

<?php
/**
 * @package Awoods/World
 */
namespace Awoods\World;

interface CountryInterface {

	/**
	 * @return string
	 */
	public function getName();

	/**
	 * @return string
	 */
	public function getFullName();

}

Remove validation methods from Country Interface

Not all countries use postal codes.


<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

namespace Flarum\Tags\Access;

use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;

class TagPolicy extends AbstractPolicy
{
    /**
     * @param User $actor
     * @param Tag $tag
     * @return bool|null
     */
    public function startDiscussion(User $actor, Tag $tag)
    {
        if ($tag->is_restricted) {
            return $actor->hasPermission('tag'.$tag->id.'.startDiscussion') ? $this->allow() : $this->deny();
        }
    }

    /**
     * @param User $actor
     * @param Tag $tag
     * @return bool|null
     */
    public function addToDiscussion(User $actor, Tag $tag)
    {
        return $this->startDiscussion($actor, $tag);
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

namespace Flarum\Tags\Access;

use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;

class TagPolicy extends AbstractPolicy
{
    /**
     * @param User $actor
     * @param Tag $tag
     * @return bool|null
     */
    public function startDiscussion(User $actor, Tag $tag)
    {
        if ($tag->is_restricted) {
            return $actor->hasPermission('tag'.$tag->id.'.startDiscussion') ? $this->allow() : $this->deny();
        }
    }

    /**
     * @param User $actor
     * @param Tag $tag
     * @return bool|null
     */
    public function addToDiscussion(User $actor, Tag $tag)
    {
        return $actor->can('startDiscussion', $tag);
    }
}

Fix logic for determining whether users can add tags to a discussion


<?php
namespace PhpBrew;

class AppStore
{
    public static function all()
    {
        $apps = array(
            'composer' => array('url' => 'https://getcomposer.org/composer.phar', 'as' => 'composer'),
            'phpunit' => array('url' => 'https://phar.phpunit.de/phpunit.phar', 'as' => 'phpunit'),
            'phpmd' => array('url' => 'http://static.phpmd.org/php/latest/phpmd.phar', 'as' => 'phpmd'),
            'behat' => array('url' => 'https://github.com/Behat/Behat/releases/download/v2.5.5/behat.phar', 'as' => 'behat'),
        );
        $phpunitapps = explode(' ','phpunit phpcov phpcpd phpdcd phptok phploc');
        foreach ($phpunitapps as $phpunitapp) {
            $apps[ $phpunitapp ] = array(
                'url' => sprintf('https://phar.phpunit.de/%s.phar', $phpunitapp),
                'as' => $phpunitapp,
            );
        }
        return $apps;
    }
}

<?php
namespace PhpBrew;

class AppStore
{
    public static function all()
    {
        $apps = array(
            'composer'  => array('url' => 'https://getcomposer.org/composer.phar', 'as'                              => 'composer'),
            'phpunit'   => array('url' => 'https://phar.phpunit.de/phpunit.phar', 'as'                               => 'phpunit'),
            'phpmd'     => array('url' => 'http://static.phpmd.org/php/latest/phpmd.phar', 'as'                      => 'phpmd'),
            'behat-2.5' => array('url' => 'https://github.com/Behat/Behat/releases/download/v2.5.5/behat.phar', 'as' => 'behat'),
            'behat-3.5' => array('url' => 'https://github.com/Behat/Behat/releases/download/v3.0.15/behat.phar', 'as' => 'behat'),
        );
        $phpunitapps = explode(' ','phpunit phpcov phpcpd phpdcd phptok phploc');
        foreach ($phpunitapps as $phpunitapp) {
            $apps[ $phpunitapp ] = array(
                'url' => sprintf('https://phar.phpunit.de/%s.phar', $phpunitapp),
                'as' => $phpunitapp,
            );
        }
        return $apps;
    }
}

Add behat 2.5 and 3.0

Add behat 2.5 and 3.0


<?php
namespace ET\Db;

use \ET\Config;

class PdoBackend
{
    /** @var Config */
    private $config;

    /** @var PDO */
    private $pdo;

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

    public function connect()
    {
        if (!isset($this->config->db->dsn)) {
            throw new DbException('DSN is not defined in config, this is required for PDO');
        }

        if (!isset($this->config->db->username) || !isset($this->config->db->password)) {
            throw new DbException(
                'Username or Password is not defined in config,'.
                'this is required to be at least empty.'
            );
        }

        try {
            $this->pdo = new \PDO(
                $this->config->db->dsn,
                $this->config->db->username,
                $this->config->db->password
            );
        } catch (\PDOException $e) {
            throw new DbException('PDO Exception: '.$e->getMessage());
        }

        return true;
    }
}

<?php
namespace ET\Db;

use \ET\Config;

class PdoBackend
{
    /** @var Config */
    private $config;

    /** @var PDO */
    private $pdo;

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

    public function connect()
    {
        if (!isset($this->config->db->dsn)) {
            throw new DbException('DSN is not defined in config, this is required for PDO');
        }

        if (!isset($this->config->db->username) || !isset($this->config->db->password)) {
            throw new DbException(
                'Username or Password is not defined in config,'.
                'this is required to be at least empty.'
            );
        }

        try {
            $this->pdo = new \PDO(
                $this->config->db->dsn,
                $this->config->db->username,
                $this->config->db->password
            );
        } catch (\PDOException $e) {
            throw new DbException('PDO Exception: '.$e->getMessage());
        }

        $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);

        return true;
    }
}

Set default fetch model to object

Set default fetch model to object


<?php

namespace Amelia\Rememberable\Eloquent;

use Illuminate\Database\Eloquent\Collection;

class Builder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * @var \Amelia\Rememberable\Query\Builder
     */
    protected $query;

    /**
     * Get the hydrated models without eager loading.
     *
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model[]
     */
    public function getModels($columns = ['*'])
    {
        $key = $this->query->getCacheKey($columns);

        $results = $this->query->get($columns)->all();

        $connection = $this->model->getConnectionName();

        $models = $this->model->hydrate($results, $connection);

        $this->tagModels($models, $key);

        return $models->all();
    }

    /**
     * Tag this cache key with the ID of every model in the collection.
     *
     * @param \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[] $models
     * @param string $key
     */
    protected function tagModels(Collection $models, $key)
    {
        $tags = $this->query->getCacheTags();

        $class = get_class($this->model);

        foreach ($models as $model) {
            $tags[] = $class.':'.$model->getKey();
        }

        $this->query->setTagsForKey($tags, $key);
    }
}

<?php

namespace Amelia\Rememberable\Eloquent;

use Illuminate\Database\Eloquent\Collection;

class Builder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * @var \Amelia\Rememberable\Query\Builder
     */
    protected $query;

    /**
     * Get the hydrated models without eager loading.
     *
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model[]
     */
    public function getModels($columns = ['*'])
    {
        $key = $this->query->getCacheKey($columns);

        $results = $this->query->get($columns);

        if ($results instanceof Collection) {
            $results = $results->all();
        }

        $connection = $this->model->getConnectionName();

        $models = $this->model->hydrate($results, $connection);

        $this->tagModels($models, $key);

        return $models->all();
    }

    /**
     * Tag this cache key with the ID of every model in the collection.
     *
     * @param \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[] $models
     * @param string $key
     */
    protected function tagModels(Collection $models, $key)
    {
        $tags = $this->query->getCacheTags();

        $class = get_class($this->model);

        foreach ($models as $model) {
            $tags[] = $class.':'.$model->getKey();
        }

        $this->query->setTagsForKey($tags, $key);
    }
}

Add laravel 5.2 compat by checking query builder return type


<?php

namespace Adldap\Laravel\Scopes;

use Adldap\Query\Builder;

class MailScope implements Scope
{
    /**
     * {@inheritdoc}
     */
    public function apply(Builder $builder)
    {
        $builder->whereHas('mail');
    }
}

<?php

namespace Adldap\Laravel\Scopes;

use Adldap\Query\Builder;

class MailScope implements Scope
{
    /**
     * {@inheritdoc}
     */
    public function apply(Builder $builder)
    {
        $builder->whereHas($builder->getSchema()->email());
    }
}

Use schema in email scope

Use schema in email scope


<?php

date_default_timezone_set('Europe/London');

require_once 'config.inc.php';
require_once 'MailManager.php';

try
{
  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name, false);

  $mm->setSubject('Test Email');
  $mm->addRecipient('paul.waring@manchester.ac.uk');
  $mm->setBody('Test Body');

  $mm->send();
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

<?php

date_default_timezone_set('Europe/London');

require_once 'config.inc.php';
require_once 'MailManager.php';

try
{
  $enable_mail = isset($_GET['enablemail']) ? boolval($_GET['enablemail']) : false;

  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name, $enable_mail);

  $mm->setSubject('Test Email');
  $mm->addRecipient('paul.waring@manchester.ac.uk');
  $mm->setBody('Test Body');

  $mm->send();
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

Make mail enabling a GET parameter

Make mail enabling a GET parameter

This makes it easier to test, without having to commit/deploy each time.


<?php

namespace Mama\Authlink;

class AuthlinkTest extends \PHPUnit_Framework_TestCase
{

  public function testGenerate()
  {
    $authlink = new Authlink();

    $link = $authlink->generate();

    $this->assertNotEmpty($link);
  }

  public function testGenerateValidate()
  {
    $authlink = new Authlink();

    $link = $authlink->generate();

    $this->assertTrue($authlink->validate($link));
  }

  public function testExpiredLink()
  {
    $authlink = new Authlink();

    $link = $authlink->generate(1);

    $this->assertTrue($authlink->validate($link));

    sleep(1); //wait to expire

    $this->assertFalse($authlink->validate($link));
  }

}

<?php

namespace Mama\Authlink;

class AuthlinkTest extends \PHPUnit_Framework_TestCase
{

  public function testGenerate()
  {
    $authlink = new Authlink();

    $link = $authlink->generate();

    $this->assertNotEmpty($link);
  }

  public function testGenerateValidate()
  {
    $authlink = new Authlink();

    $link = $authlink->generate();

    $this->assertTrue($authlink->validate($link));
  }

  public function testExpiredLink()
  {
    $authlink = new Authlink();

    $link = $authlink->generate(1);

    $this->assertTrue($authlink->validate($link));

    sleep(1); //wait to expire

    $this->assertFalse($authlink->validate($link));
  }

  public function testChecksum()
  {
    $authlink1 = new Authlink(array('secret' => 'someSecret'));
    $authlink2 = new Authlink(array('secret' => 'anotherSecret'));

    $link1 = $authlink1->generate();
    $link2 = $authlink2->generate();

    $this->assertTrue($authlink1->validate($link1));
    $this->assertFalse($authlink1->validate($link2));

    $this->assertTrue($authlink2->validate($link2));
    $this->assertFalse($authlink2->validate($link1));
  }

}

Test checksums with different secrets

Test checksums with different secrets


<?php
namespace Everyman\Neo4j;

class Exception extends \Exception
{
}

<?php
namespace Everyman\Neo4j;

class Exception extends \Exception
{
	protected $headers;
	protected $data;

	public function __construct($message, $code, $headers = array(), $data = array())
	{
		$this->headers = $headers;
		$this->data = $data;
		parent::__construct($message, $code);
	}

	/**
	 * Return response headers
	 * @return array Response headers
	 */
	public function getHeaders()
	{
		return $this->headers;
	}

	/**
	 * Return response data
	 * @return array Response data
	 */
	public function getData()
	{
		return $this->data;
	}
}

Set the response headers and data in constructor, accessible through getHeaders and getData methods


<?php

declare(strict_types=1);

namespace Cortex\Fort\Http\Controllers\Userarea;

use Illuminate\Http\Request;
use Rinvex\Fort\Models\Session;
use Cortex\Foundation\Http\Controllers\AuthenticatedController;

class AccountSessionsController extends AuthenticatedController
{
    /**
     * Show the account sessions.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('cortex/fort::userarea.account.sessions');
    }

    /**
     * Flush the given session.
     *
     * @param string|null $id
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function flush(Request $request, $id = null)
    {
        $status = '';

        if ($id) {
            Session::find($id)->delete();
            $status = trans('cortex/fort::messages.auth.session.flushed');
        } elseif ($request->get('confirm')) {
            Session::where('user_id', $request->user($this->getGuard())->id)->delete();
            $status = trans('cortex/fort::messages.auth.session.flushedall');
        }

        return intend([
            'back' => true,
            'with' => ['warning' => $status],
        ]);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Fort\Http\Controllers\Userarea;

use Illuminate\Http\Request;
use Cortex\Foundation\Http\Controllers\AuthenticatedController;

class AccountSessionsController extends AuthenticatedController
{
    /**
     * Show the account sessions.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('cortex/fort::userarea.account.sessions');
    }

    /**
     * Flush the given session.
     *
     * @param string|null $id
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function flush(Request $request, $id = null)
    {
        $status = '';

        if ($id) {
            app('rinvex.fort.session')->find($id)->delete();
            $status = trans('cortex/fort::messages.auth.session.flushed');
        } elseif ($request->get('confirm')) {
            app('rinvex.fort.session')->where('user_id', $request->user($this->getGuard())->id)->delete();
            $status = trans('cortex/fort::messages.auth.session.flushedall');
        }

        return intend([
            'back' => true,
            'with' => ['warning' => $status],
        ]);
    }
}

Use IoC bound model rather than hard coding


<?php
namespace wcf\system\user\notification\object\type;
use wcf\data\comment\Comment;
use wcf\data\comment\CommentList;
use wcf\system\user\notification\object\CommentUserNotificationObject;
use wcf\system\WCF;

/**
 * Represents a comment notification object type for comments on articles.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Notification\Object\Type
 * @since       3.2
 */
class ArticleCommentUserNotificationObjectType extends AbstractUserNotificationObjectType implements ICommentUserNotificationObjectType {
	/**
	 * @inheritDoc
	 */
	protected static $decoratorClassName = CommentUserNotificationObject::class;

	/**
	 * @inheritDoc
	 */
	protected static $objectClassName = Comment::class;

	/**
	 * @inheritDoc
	 */
	protected static $objectListClassName = CommentList::class;

	/**
	 * @inheritDoc
	 */
	public function getOwnerID($objectID) {
		$sql = "SELECT	objectID
			FROM	wcf".WCF_N."_comment
			WHERE	commentID = ?";
		$statement = WCF::getDB()->prepareStatement($sql);
		$statement->execute([$objectID]);
		$row = $statement->fetchArray();

		return ($row ? $row['objectID'] : 0);
	}
}

<?php
namespace wcf\system\user\notification\object\type;
use wcf\data\comment\Comment;
use wcf\data\comment\CommentList;
use wcf\system\user\notification\object\CommentUserNotificationObject;
use wcf\system\WCF;

/**
 * Represents a comment notification object type for comments on articles.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Notification\Object\Type
 * @since       3.2
 */
class ArticleCommentUserNotificationObjectType extends AbstractUserNotificationObjectType implements ICommentUserNotificationObjectType {
	/**
	 * @inheritDoc
	 */
	protected static $decoratorClassName = CommentUserNotificationObject::class;

	/**
	 * @inheritDoc
	 */
	protected static $objectClassName = Comment::class;

	/**
	 * @inheritDoc
	 */
	protected static $objectListClassName = CommentList::class;

	/**
	 * @inheritDoc
	 */
	public function getOwnerID($objectID) {
		$sql = "SELECT		article.userID
			FROM		wcf".WCF_N."_comment comment
			LEFT JOIN	wcf".WCF_N."_article article
			ON		(article.articleID = comment.objectID)
			WHERE		comment.commentID = ?";
		$statement = WCF::getDB()->prepareStatement($sql);
		$statement->execute([$objectID]);

		return $statement->fetchSingleColumn() ?: 0;
	}
}

Fix determination of article owner userID for article comment notifications

See #2649


<?php
declare(strict_types=1);
namespace Onion\Framework\Application;

use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\EmitterInterface;

class Application implements ServerMiddlewareInterface
{
    /**
     * @var DelegateInterface
     */
    protected $delegate;

    /**
     * @var EmitterInterface
     */
    protected $emitter;

    public function __construct(DelegateInterface $delegate, EmitterInterface $emitter)
    {
        $this->delegate = $delegate;
        $this->emitter = $emitter;
    }

    public function run(ServerRequestInterface $request)
    {
        $this->emitter->emit($this->process($request, null));
    }

    /**
     * @param ServerRequestInterface $request
     * @param DelegateInterface      $delegate
     *
     * @throws \Throwable Rethrows the exceptions if no $delegate is available
     *
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, DelegateInterface $delegate = null): ResponseInterface
    {
        try {
            return $this->delegate->process($request);
        } catch (\Throwable $ex) {
            if ($delegate === null) {
                throw $ex;
            }

            return $delegate->process($request->withAttribute('exception', $ex));
        }
    }
}

<?php
declare(strict_types=1);
namespace Onion\Framework\Application;

use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\EmitterInterface;

class Application implements ServerMiddlewareInterface
{
    /**
     * @var DelegateInterface
     */
    protected $delegate;

    /**
     * @var EmitterInterface
     */
    protected $emitter;

    public function __construct(DelegateInterface $delegate, EmitterInterface $emitter)
    {
        $this->delegate = $delegate;
        $this->emitter = $emitter;
    }

    public function run(ServerRequestInterface $request)
    {
        return $this->emitter->emit($this->process($request, null));
    }

    /**
     * @param ServerRequestInterface $request
     * @param DelegateInterface      $delegate
     *
     * @throws \Throwable Rethrows the exceptions if no $delegate is available
     *
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, DelegateInterface $delegate = null): ResponseInterface
    {
        try {
            return $this->delegate->process($request);
        } catch (\Throwable $ex) {
            if ($delegate === null) {
                throw $ex;
            }

            return $delegate->process($request->withAttribute('exception', $ex));
        }
    }
}

Add return statent to 'run' method

Add return statent to 'run' method


<?php
foreach($_['books'] as $id => $addressbook) {
	echo '
'.$addressbook['displayname'].'
';
	echo '
';
	foreach($addressbook['contacts'] as $contact) {
		echo '
'.$contact['displayname'].'
';
	}
	echo '
';
}
?>

Add thumbnail links so they are loaded when addressbook is expanded.


<?php

namespace BeanstalkSatisGen\File;

class Composer extends Json
{

    /**
     * Returns whether or not this composer file is a satis package based on the
     * contents.
     *
     * @return boolean
     */
    public function isComposerPackage()
    {
        return
            ! empty($this->content) &&
            $this->hasName() &&
            (
                $this->hasPackageType() ||
                $this->isSatisPackage()
            );
    }

    /**
     * Whether or not this composer file has a name
     */
    protected function hasName()
    {
        return ! empty($this->content->name);
    }

    /**
     * Whether or not this composer.json has a type that is a package
     *
     * @return bool
     */
    protected function hasPackageType()
    {
        $allowableTypes = array(
            'library',
            'wordpress-plugin',
            'wordpress-muplugin',
            'symfony-bundle',
            'drupal-module'
        );

        return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
    }

    /**
     * Whether or not this composer is a satis package
     *
     * @return bool
     */
    protected function isSatisPackage()
    {
        return
            isset($this->content->extra) &&
            isset($this->content->extra->{'satis-package'}) &&
            true === $this->content->extra->{'satis-package'};
    }
}

<?php

namespace BeanstalkSatisGen\File;

class Composer extends Json
{

    /**
     * Returns whether or not this composer file is a satis package based on the
     * contents.
     *
     * @return boolean
     */
    public function isComposerPackage()
    {
        return
            ! empty($this->content) &&
            $this->hasName() &&
            (
                $this->hasPackageType() ||
                $this->isSatisPackage()
            );
    }

    /**
     * Whether or not this composer file has a name
     */
    protected function hasName()
    {
        return ! empty($this->content->name);
    }

    /**
     * Whether or not this composer.json has a type that is a package
     *
     * @return bool
     */
    protected function hasPackageType()
    {
        $allowableTypes = array(
            'library',
            'wordpress-plugin',
            'wordpress-muplugin',
            'wordpress-theme',
            'symfony-bundle',
            'drupal-module'
        );

        return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
    }

    /**
     * Whether or not this composer is a satis package
     *
     * @return bool
     */
    protected function isSatisPackage()
    {
        return
            isset($this->content->extra) &&
            isset($this->content->extra->{'satis-package'}) &&
            true === $this->content->extra->{'satis-package'};
    }
}

Add WordPress thema as package type

Add WordPress thema as package type


<?php

namespace Reshadman\FileSecretary\Infrastructure;

use MimeTyper\Repository\MimeDbRepository as BaseMimeDbRepository;

class MimeDbRepository extends BaseMimeDbRepository
{
    public function findExtension($type)
    {
        $found = parent::findExtension($type);

        return FileSecretaryManager::normalizeExtension($found);
    }

    public function findType($extension)
    {
        // Get all matching extensions.
        $types = $this->findTypes($extension);

        if (count($types) > 0) {
            // Return first match.
            return $types[0];
        }

        return null;
    }
}

<?php

namespace Reshadman\FileSecretary\Infrastructure;

use MimeTyper\Repository\MimeDbRepository as BaseMimeDbRepository;

class MimeDbRepository extends BaseMimeDbRepository
{
    protected $extendedMimes = [
        'application/x-rar-compressed' => 'rar',
        'application/rar' => 'rar'
    ];

    public function findExtension($type)
    {
        $found = parent::findExtension($type);

        if ($found === null) {
            if (isset($this->extendedMimes[$type])) {
                $found = $this->extendedMimes[$type];
            }
        }

        return FileSecretaryManager::normalizeExtension($found);
    }

    public function findType($extension)
    {
        // Get all matching extensions.
        $types = $this->findTypes($extension);

        if (count($types) > 0) {
            // Return first match.
            return $types[0];
        }

        return null;
    }
}

Add rar mime type support

Add rar mime type support


<?php

namespace PhpSpec\Formatter;

use PhpSpec\Event\ExampleEvent;
use PhpSpec\Formatter\Presenter\PresenterInterface;

class HtmlFormatter extends BasicFormatter
{
    private $reportItemFactory;
    private $presenter;

    public function __construct(Html\ReportItemFactory $reportItemFactory = null)
    {
        $this->reportItemFactory = $reportItemFactory ?: new Html\ReportItemFactory();
    }

    public function setPresenter(PresenterInterface $presenter)
    {
        $this->presenter = $presenter;
    }

    public function afterExample(ExampleEvent $event)
    {
        $reportLine = $this->reportItemFactory->create($this->getIO(), $event, $this->presenter);
        $reportLine->write();
    }
}

<?php

namespace PhpSpec\Formatter;

use PhpSpec\Event\ExampleEvent;
use PhpSpec\Event\SuiteEvent;
use PhpSpec\Formatter\Presenter\PresenterInterface;

class HtmlFormatter extends BasicFormatter
{
    private $reportItemFactory;
    private $presenter;

    public function __construct(Html\ReportItemFactory $reportItemFactory = null)
    {
        $this->reportItemFactory = $reportItemFactory ?: new Html\ReportItemFactory();
    }

    public function setPresenter(PresenterInterface $presenter)
    {
        $this->presenter = $presenter;
    }

    public function beforeSuite(SuiteEvent $suite)
    {
        include __DIR__ . "/Html/ReportHeader.html";
    }

    public function afterExample(ExampleEvent $event)
    {
        $reportLine = $this->reportItemFactory->create($this->getIO(), $event, $this->presenter);
        $reportLine->write();
        $this->getIO()->write(PHP_EOL);
    }

    public function afterSuite(SuiteEvent $suite)
    {
        include __DIR__ . "/Html/ReportSummary.html";
        include __DIR__ . "/Html/ReportFooter.html";
    }
}

Add a header and a footer as suite events


<?php
namespace SslurpTest;

use PHPUnit_Framework_TestCase as TestCase;
use Sslurp\X509Certificate;

class X509CertificateTest extends TestCase
{
    public function testConsructorSupoprtsMultipleInputTypesAndCanGenerateProperKeyPin()
    {
        $certPath     = __DIR__ . '/_files/mxr.mozilla.org.pem';
        $certString   = file_get_contents($certPath);
        $certResource = openssl_x509_read($certString);
        $expectedPin  = '47cac6d8f2c2363675e6f433970f27523824d0ec';

        $cert = new X509Certificate($certPath);
        $this->assertSame($cert->getPin(), $expectedPin);

        $cert = new X509Certificate($certString);
        $this->assertSame($cert->getPin(), $expectedPin);

        $cert = new X509Certificate($certResource);
        $this->assertSame($cert->getPin(), $expectedPin);
    }
}

<?php
namespace SslurpTest;

use PHPUnit_Framework_TestCase as TestCase;
use Sslurp\X509Certificate;

class X509CertificateTest extends TestCase
{
    public function testConsructorSupoprtsMultipleInputTypesAndCanGenerateProperKeyPin()
    {
        $certPath     = __DIR__ . '/_files/mxr.mozilla.org.pem';
        $certString   = file_get_contents($certPath);
        $certResource = openssl_x509_read($certString);
        $expectedPin  = '47cac6d8f2c2363675e6f433970f27523824d0ec';

        $cert = new X509Certificate($certPath);
        $this->assertSame($cert->getPin(), $expectedPin);

        $cert = new X509Certificate($certString);
        $this->assertSame($cert->getPin(), $expectedPin);

        $cert = new X509Certificate($certResource);
        $this->assertSame($cert->getPin(), $expectedPin);
    }

    public function testInvalidConstructorArgumentThrowsException()
    {
        $this->setExpectedException('InvalidArgumentException');
        $cert = new X509Certificate(123);
    }
}

Test X509Certificate for invalid constructor argument


<?php
/**
 * Shoestrap initial setup and constants
 */
function shoestrap_setup() {
	// Make theme available for translation
	load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' );

	// Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus )
	register_nav_menus( array(
		'primary_navigation'   => __( 'Primary Navigation', 'shoestrap' ),
		'secondary_navigation' => __( 'Secondary Navigation', 'shoestrap' ),
	 ) );

	// Add post thumbnails ( http://codex.wordpress.org/Post_Thumbnails )
	add_theme_support( 'post-thumbnails' );

	// Add post formats ( http://codex.wordpress.org/Post_Formats )
	add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) );

	add_theme_support( 'automatic-feed-links' );

	// Tell the TinyMCE editor to use a custom stylesheet
	add_editor_style( '/assets/css/editor-style.css' );
}
add_action( 'after_setup_theme', 'shoestrap_setup' );

<?php
/**
 * Shoestrap initial setup and constants
 */
function shoestrap_setup() {
	// Make theme available for translation
	load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' );

	// Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus )
	register_nav_menus( array(
		'primary_navigation'   => __( 'Primary Navigation', 'shoestrap' ),
		'secondary_navigation' => __( 'Secondary Navigation', 'shoestrap' ),
	 ) );

	// Add post thumbnails ( http://codex.wordpress.org/Post_Thumbnails )
	add_theme_support( 'post-thumbnails' );

	// Add post formats ( http://codex.wordpress.org/Post_Formats )
	add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) );

	add_theme_support( 'automatic-feed-links' );

	add_theme_support( 'html5', array( 'gallery', 'caption' ) );

	// Tell the TinyMCE editor to use a custom stylesheet
	add_editor_style( '/assets/css/editor-style.css' );
}
add_action( 'after_setup_theme', 'shoestrap_setup' );

Add suport for HTML5 Galleries & Captions

See http://make.wordpress.org/core/2014/04/15/html5-galleries-captions-
in-wordpress-3-9/ for mor details


<?php
/**
 * Clean up the_excerpt()
 */
function roots_excerpt_more() {
  return ' … ' . __('Continued', 'roots') . '';
}
add_filter('excerpt_more', 'roots_excerpt_more');

/**
 * Disable page scroll when clicking the more link
 */
function disable_more_link_scroll($link) {
	return preg_replace('|#more-[0-9]+|', '', $link);
}
add_filter('the_content_more_link', 'disable_more_link_scroll');

/**
 * Disable moving checked items out of the hierarchy and to the top of the list
 */
function disable_checked_ontop($args, $post_id = 0) {
  $args['checked_ontop'] = false;
  return $args;
}
add_filter('wp_terms_checklist_args', 'disable_checked_ontop');

/**
 * Add the "img-responsive" class to classes of images in posts
 */
function add_image_responsive_class($classes) {
  return 'img-responsive ' . $classes;
}
add_filter('get_image_tag_class', 'add_image_responsive_class');


<?php namespace Laraplus\Form\DataStores;

trait RetrievesModelValues
{
    /**
     * @var ArrayAccess|array
     */
    protected $model = null;

    /**
     * @param ArrayAccess|array $model
     */
    public function bind($model)
    {
        $this->model = $model;
    }

    /**
     * @param string $name
     * @param null|ArrayAccess|array $offset
     * @return null|string
     */
    public function getModelValue($name, $offset = null)
    {
        $model = isset($offset) ? $offset : $this->model;

        if(($from = strpos($name, '[')) && ($to = strpos($name, ']'))) {
            $newName = substr($name, $from+1, $to-$from-1) . substr($name, $to+1);
            $offset = substr($name, 0, $from);

            if(!isset($model[$offset])) return null;

            return $this->getModelValue($newName, $model[$offset]);
        }

        if (is_array($model) && isset($model[$name])) {
            return $model[$name];
        }

        if(is_object($model) && $model->$name) {
            return $model->$name;
        }

        return null;
    }
}

<?php namespace Laraplus\Form\DataStores;

trait RetrievesModelValues
{
    /**
     * @var ArrayAccess|array
     */
    protected $model = null;

    /**
     * @param ArrayAccess|array $model
     */
    public function bind($model)
    {
        $this->model = $model;
    }

    /**
     * @param string $name
     * @param null|ArrayAccess|array $offset
     * @return null|string
     */
    public function getModelValue($name, $offset = null)
    {
        $model = isset($offset) ? $offset : $this->model;

        if(($from = strpos($name, '[')) && ($to = strpos($name, ']'))) {
            $newName = substr($name, $from+1, $to-$from-1) . substr($name, $to+1);
            $offset = substr($name, 0, $from);

            if(!isset($model[$offset])) return null;

            return $this->getModelValue($newName, $model[$offset]);
        }

        if (is_array($model) && isset($model[$name])) {
            return $model[$name];
        }

        if(is_object($model) && strlen($model->$name)) {
            return $model->$name;
        }

        return null;
    }
}

Fix retrieving model values for empty strings


<?php
namespace Concrete\Tests\Express\Form\Control\View;

use Concrete\Core\Entity\Express\Control\AttributeKeyControl;
use Concrete\Core\Entity\Express\Control\Control;
use Concrete\Core\Express\Form\Control\View\View;
use Concrete\Core\Express\Form\Context\ContextInterface;
use Concrete\Core\Filesystem\TemplateLocator;

class TestView extends View
{
    /**
     * AttributeKeyView constructor.
     *
     * @param ContextInterface $context
     * @param AttributeKeyControl $control
     */
    public function __construct(ContextInterface $context, Control $control)
    {
        parent::__construct($context, $control);
    }

    public function getControlID()
    {
        return 'tests';
    }

    public function createTemplateLocator()
    {
        $locator = new TemplateLocator('tests');

        return $locator;
    }
}

<?php
namespace Concrete\Tests\Express\Form\Control\View;

use Concrete\Core\Express\Form\Control\View\View;
use Concrete\Core\Filesystem\TemplateLocator;

class TestView extends View
{
    public function getControlID()
    {
        return 'tests';
    }

    public function createTemplateLocator()
    {
        $locator = new TemplateLocator('tests');

        return $locator;
    }
}

Remove unnecessary constructor from the test class


<?php

namespace GatherUp\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof JsonException) {
            return response()->json(json_decode($e->getMessage()), 403);
        }
        else if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }
}

<?php

namespace GatherUp\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof JsonException) {
            return response()->json(json_decode($e->getMessage()), $e->getStatusCode());
        }
        else if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }
}

Use the JsonException status code

Use the JsonException status code


<?php

// Remove the «Private» label from the beginning of private posts' titles
add_filter('private_title_format', function($title) {
    return '%s';
});

// Hide frontend admin bar from regular users
add_filter('show_admin_bar', function($show_admin_bar) {
    return current_user_can('manage_options');
});

// In development, send all outbound e-mails from and to the blog's e-mail address
add_filter('wp_mail', function(array $params) {
    if (defined('WP_ENV') && WP_ENV === 'development') {
        $params['from'] = $params['to'] = get_bloginfo('admin_email');
    }

    return $params;
});

<?php

// Remove the «Private» label from the beginning of private posts' titles
add_filter('private_title_format', function($title) {
    return '%s';
});

// Hide frontend admin bar from regular users
add_filter('show_admin_bar', function($show_admin_bar) {
    return current_user_can('manage_options');
});

// In development, send all outbound e-mails from and to the blog's e-mail address
if (defined('WP_ENV') && WP_ENV === 'development') {
    $new_addr = get_bloginfo('admin_email');

    add_filter('wp_mail', function(array $params) use ($new_addr) {
        $params['to'] = $new_addr;

        return $params;
    });
    add_filter('wp_mail_from', function($to_addr) use ($new_addr) {
        return $new_addr;
    });
}

Correct buggy behavior for development proxy e-mail address filter


<?php
/**
 * Part of ci-phpunit-test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

require __DIR__ . '/Installer.php';

$app = 'application';
if ($argv && $argv[1] && is_dir($argv[1])) {
    $app = $argv[1];
}
$installer = new Installer();
$installer->install($app);

<?php
/**
 * Part of ci-phpunit-test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

require __DIR__ . '/Installer.php';

$app = 'application';
if (isset($argv[1]) && is_dir($argv[1])) {
    $app = $argv[1];
}
$installer = new Installer();
$installer->install($app);

Fix "Notice: Undefined offset: 1"

Fix "Notice: Undefined offset: 1"


<?php
/*
 * This file is part of rg\broker.
 *
 * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace rg\broker\customizations;

class Locker extends \Composer\Package\Locker {

    public function __construct() {
    }

    public function lockPackages($packages) {
    }

    public function isLocked() {
        return false;
    }

    public function isFresh() {
        return false;
    }

    public function getLockedPackages() {
        return array();
    }

    public function setLockData(array $packages, $devPackages, array $aliases) {

    }
}

<?php
/*
 * This file is part of rg\broker.
 *
 * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace rg\broker\customizations;

class Locker extends \Composer\Package\Locker {

    public function __construct() {
    }

    public function lockPackages(array $packages) {
    }

    public function isLocked($dev = false) {
        return false;
    }

    public function isFresh() {
        return false;
    }

    public function getLockedPackages($dev = false) {
        return array();
    }

    public function setLockData(array $packages, $devPackages, array $aliases, $minimumStability, array $stabilityFlags) {

    }
}

Fix strict standards warnings with overridden methods that changed their signature


<?php

namespace Doctrine\Tests\Common\Persistence\Mapping;

use Doctrine\Tests\DoctrineTestCase;
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;

class StaticPHPDriverTest extends DoctrineTestCase
{
    public function testLoadMetadata()
    {
        $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
        $metadata->expects($this->once())->method('getFieldNames');

        $driver = new StaticPHPDriver(array(__DIR__));
        $driver->loadMetadataForClass(__NAMESPACE__ . '\\TestEntity', $metadata);
    }
}

class TestEntity
{
    static public function loadMetadata($metadata)
    {
        $metadata->getFieldNames();
    }
}

<?php

namespace Doctrine\Tests\Common\Persistence\Mapping;

use Doctrine\Tests\DoctrineTestCase;
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;

class StaticPHPDriverTest extends DoctrineTestCase
{
    public function testLoadMetadata()
    {
        $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
        $metadata->expects($this->once())->method('getFieldNames');

        $driver = new StaticPHPDriver(array(__DIR__));
        $driver->loadMetadataForClass(__NAMESPACE__ . '\\TestEntity', $metadata);
    }

    public function testGetAllClassNames()
    {
        $driver = new StaticPHPDriver(array(__DIR__));
        $classNames = $driver->getAllClassNames();

        $this->assertTrue(in_array(
            'Doctrine\Tests\Common\Persistence\Mapping\TestEntity', $classNames));
    }
}

class TestEntity
{
    static public function loadMetadata($metadata)
    {
        $metadata->getFieldNames();
    }
}

Add one more test for StaticPHPDriver

Add one more test for StaticPHPDriver


<?php
/*
 * Lightdatasys web site source code
 *
 * Copyright Matt Light <matt.light@lightdatasys.com>
 *
 * For copyright and licensing information, please view the LICENSE
 * that is distributed with this source code.
 */

namespace Lidsys\Application\Service;

use Lstr\Silex\Database\DatabaseService;
use Silex\Application;
use Silex\ServiceProviderInterface;

class Provider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['config'] = $app->share(function ($app) {
            return $app['lstr.config']->load(array(
                __DIR__ . '/../../../../config/autoload/*.global.php',
                __DIR__ . '/../../../../config/autoload/*.local.php',
            ));
        });

        $app['db'] = $app->share(function ($app) {
            return new DatabaseService($app, $app['config']['db.config']);
        });

        $app['mailer'] = $app->share(function ($app) {
            $config = $app['config']['mailer'];
            return new MailerService(
                $config['key'],
                $config['domain']
            );
        });
    }

    public function boot(Application $app)
    {
    }
}

<?php
/*
 * Lightdatasys web site source code
 *
 * Copyright Matt Light <matt.light@lightdatasys.com>
 *
 * For copyright and licensing information, please view the LICENSE
 * that is distributed with this source code.
 */

namespace Lidsys\Application\Service;

use Lstr\Silex\Database\DatabaseService;
use Silex\Application;
use Silex\ServiceProviderInterface;

class Provider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['config'] = $app->share(function ($app) {
            return $app['lstr.config']->load(array(
                __DIR__ . '/../../../../config/autoload/*.global.php',
                __DIR__ . '/../../../../config/autoload/*.local.php',
            ));
        });

        $app['db'] = $app->share(function ($app) {
            return new DatabaseService($app, $app['config']['db.config']);
        });

        $app['mailer'] = $app->share(function ($app) {
            $config = $app['config']['mailer'];
            return new MailerService(
                $config['key'],
                $config['domain'],
                array(
                    '{{BASE_URL}}' => $app['config']['app']['base_url'],
                )
            );
        });
    }

    public function boot(Application $app)
    {
    }
}

Add BASE_URL substitution to mailer service instance


<?php

namespace SLLH\IsoCodesValidatorBundle\Tests;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractContainerBuilderTestCase;
use SLLH\IsoCodesValidatorBundle\SLLHIsoCodesValidatorBundle;

class SLLHIsoCodesValidatorBundleTest extends AbstractContainerBuilderTestCase
{
    /**
     * @var SLLHIsoCodesValidatorBundle
     */
    protected $bundle;

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

        $this->bundle = new SLLHIsoCodesValidatorBundle();
    }

    public function testBuild()
    {
        $this->bundle->build($this->container);

        $this->assertCount(2, $this->container->getCompilerPassConfig()->getPasses(), 'Bundle must contains a TranslationPass instance.');
        $this->assertInstanceOf(
            'SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler\TranslationPass',
            $this->container->getCompilerPassConfig()->getPasses()[1],
            'Bundle must contains a TranslationPass instance.'
        );
    }
}

<?php

namespace SLLH\IsoCodesValidatorBundle\Tests;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractContainerBuilderTestCase;
use SLLH\IsoCodesValidatorBundle\SLLHIsoCodesValidatorBundle;

class SLLHIsoCodesValidatorBundleTest extends AbstractContainerBuilderTestCase
{
    /**
     * @var SLLHIsoCodesValidatorBundle
     */
    protected $bundle;

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

        $this->bundle = new SLLHIsoCodesValidatorBundle();
    }

    public function testBuild()
    {
        $this->bundle->build($this->container);

        $passes = $this->container->getCompilerPassConfig()->getPasses();
        $this->assertCount(2, $passes, 'Bundle must contains a TranslationPass instance.');
        $this->assertInstanceOf(
            'SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler\TranslationPass',
            $passes[1],
            'Bundle must contains a TranslationPass instance.'
        );
    }
}

Fix php 5.3 syntax error

Fix php 5.3 syntax error


<?php
/**
 * Override field methods
 *
 * @package     Kirki
 * @subpackage  Controls
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
 * @since       2.3.2
 */

/**
 * Field overrides.
 */
class Kirki_Field_Dimension extends Kirki_Field {

	/**
	 * Sets the control type.
	 *
	 * @access protected
	 */
	protected function set_type() {

		$this->type = 'kirki-dimension';

	}
}

<?php
/**
 * Override field methods
 *
 * @package     Kirki
 * @subpackage  Controls
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
 * @since       2.3.2
 */

/**
 * Field overrides.
 */
class Kirki_Field_Dimension extends Kirki_Field {

	/**
	 * Sets the control type.
	 *
	 * @access protected
	 */
	protected function set_type() {

		$this->type = 'kirki-dimension';

	}

	/**
	 * Sanitizes the value.
	 *
	 * @access public
	 * @param string $value The value.
	 * @return string
	 */
	public function sanitize( $value ) {
		return Kirki_Sanitize_Values::css_dimension( $value );
	}
}

Add sanitization for dimension control.

Add sanitization for dimension control.


<?php

/*
 * This file is part of php-cache\adapter-bundle package.
 *
 * (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cache\Adapter\DoctrineAdapterBundle\Tests\DependencyInjection;

use Cache\AdapterBundle\DependencyInjection\CacheAdapterExtension;
use Cache\AdapterBundle\DummyAdapter;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;

class DoctrineCacheExtensionTest extends AbstractExtensionTestCase
{
    protected function getContainerExtensions()
    {
        return [
            new CacheAdapterExtension(),
        ];
    }

    public function testThatProvidersExists()
    {
        $providers = ['foo' => ['factory' => 'cache.factory.redis']];
        $this->load(['providers' => $providers]);

        $this->assertContainerBuilderHasService('cache.provider.foo', DummyAdapter::class);
        $this->assertContainerBuilderHasAlias('cache', 'cache.provider.foo');
    }
}

<?php

/*
 * This file is part of php-cache\adapter-bundle package.
 *
 * (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cache\Adapter\DoctrineAdapterBundle\Tests\DependencyInjection;

use Cache\AdapterBundle\DependencyInjection\CacheAdapterExtension;
use Cache\AdapterBundle\DummyAdapter;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;

class DoctrineCacheExtensionTest extends AbstractExtensionTestCase
{
    protected function getContainerExtensions()
    {
        return [
            new CacheAdapterExtension(),
        ];
    }

    public function testThatProvidersExists()
    {
        $providers = ['foo' => ['factory' => 'cache.factory.array']];
        $this->load(['providers' => $providers]);

        $this->assertContainerBuilderHasService('cache.provider.foo', DummyAdapter::class);
        $this->assertContainerBuilderHasAlias('cache', 'cache.provider.foo');
    }
}

Use array factory in tests

Use array factory in tests


<?php
/*
* (c) Nimbles b.v. <wessel@nimbles.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nimbles\OnlineBetaalPlatform\Model;

use PHPUnit\Framework\TestCase;

/**
 * Class PaymentTest
 */
class PaymentTest extends TestCase
{
    public function testPayment()
    {
        $payment = new Payment('https://nimbles.com/return/url', 1050);

        $this->assertEquals(1050, $payment->getAmount());
        $this->assertEquals('https://nimbles.com/return/url', $payment->getReturnUrl());

        $payment->setUid('secret-uuid');
        $this->assertEquals('secret-uuid', $payment->getUid());

        $payment->setStatus('created');
        $this->assertEquals('created', $payment->getStatus());

        $payment->setBuyerLastName('jenkins');
        $this->assertEquals('jenkins', $payment->getBuyerLastName());

        $payment->setBuyerFirstName('peter');
        $this->assertEquals('peter', $payment->getBuyerFirstName());

        $payment->setBuyerLastName('jenkins@github.com');
        $this->assertEquals('jenkins@github.com', $payment->getBuyerEmail());

        $payment->setRedirectUrl('https://nimbles.com/redirect/url');
        $this->assertEquals('https://nimbles.com/redirect/url', $payment->getRedirectUrl());

        $payment->setShippingCosts(500);
        $this->assertEquals(500, $payment->getShippingCosts());
    }
}

<?php
/*
* (c) Nimbles b.v. <wessel@nimbles.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nimbles\OnlineBetaalPlatform\Model;

use PHPUnit\Framework\TestCase;

/**
 * Class PaymentTest
 */
class PaymentTest extends TestCase
{
    public function testPayment()
    {
        $payment = new Payment('https://nimbles.com/return/url', 1050);

        $this->assertEquals(1050, $payment->getAmount());
        $this->assertEquals('https://nimbles.com/return/url', $payment->getReturnUrl());

        $payment->setUid('secret-uuid');
        $this->assertEquals('secret-uuid', $payment->getUid());

        $payment->setStatus('created');
        $this->assertEquals('created', $payment->getStatus());

        $payment->setBuyerLastName('jenkins');
        $this->assertEquals('jenkins', $payment->getBuyerLastName());

        $payment->setBuyerFirstName('peter');
        $this->assertEquals('peter', $payment->getBuyerFirstName());

        $payment->setBuyerEmail('jenkins@github.com');
        $this->assertEquals('jenkins@github.com', $payment->getBuyerEmail());

        $payment->setRedirectUrl('https://nimbles.com/redirect/url');
        $this->assertEquals('https://nimbles.com/redirect/url', $payment->getRedirectUrl());

        $payment->setShippingCosts(500);
        $this->assertEquals(500, $payment->getShippingCosts());
    }
}

Correct test setter for email

Correct test setter for email


<?php

return array(

    'default' => 'default',

    'path' => base_path('themes'),

    'cache' => [
    	'enabled' => true,
    	'lifetime' => 86400,
    ]

);

<?php

return array(

    'default' => 'default',

    'path' => base_path('themes'),

    'cache' => [
    	'enabled' => true,
    	'key' => 'pingpong.themes',
    	'lifetime' => 86400,
    ]

);

Allow to update cache key

Allow to update cache key


<?php
namespace Craft;

use Cake\Utility\Hash as Hash;

class BaseFeedMeFieldType
{
    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feedme/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function getFieldType()
    {
        return str_replace(array('Craft\\', 'FeedMeFieldType'), array('', ''), get_class($this));
    }

    public function prepFieldData($element, $field, $fieldData, $handle, $options)
    {
        $data = Hash::get($fieldData, 'data');

        return $data;
    }

}

<?php
namespace Craft;

use Cake\Utility\Hash as Hash;

class BaseFeedMeFieldType
{
    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feedme/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function getFieldType()
    {
        return str_replace(array('Craft\\', 'FeedMeFieldType'), array('', ''), get_class($this));
    }

    public function prepFieldData($element, $field, $fieldData, $handle, $options)
    {
        $data = Hash::get($fieldData, 'data');

        return $data;
    }

    public function postFieldData($element, $field, &$fieldData, $handle)
    {
        // Parse all field content for Twig shorthand variables
        foreach ($fieldData as $attribute => $data) {
            // Only check for string content at this stage
            if (!is_array($data)) {
                // Don't process the data unless we detect a Twig tag - also performance
                if (strpos($data, '{') !== false) {
                    $fieldData[$attribute] = craft()->templates->renderObjectTemplate($data, $element);
                }
            }
        }
    }

}

Allow Twig shorthand variables to be used in default fields


<?php

namespace Bolt\Extension;

use Silex\Application;

/**
 * Management class for extensions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Manager
{
    /** @var \Bolt\Composer\ExtensionAutoloader */
    protected $autoloader;
    /** @var ResolvedExtension[] */
    protected $extensions;

    /** @var Application */
    private $app;

    /**
     * Constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
        $this->autoloader = $app['extensions.autoload'];
    }

    /**
     * Load and fetch the extension classes.
     */
    public function load()
    {
        $this->extensions = $this->autoloader->load();
    }

    /**
     * Get an installed extension class.
     *
     * @param $name
     *
     * @return ExtensionInterface
     */
    public function get($name)
    {
        if (isset($this->extensions[$name])) {
            return $this->extensions[$name]->getInnerExtension();
        }
    }
}

<?php

namespace Bolt\Extension;

use Silex\Application;

/**
 * Management class for extensions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Manager
{
    /** @var \Bolt\Composer\ExtensionLoader */
    protected $loader;

    /** @var Application */
    private $app;

    /**
     * Constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
        $this->loader = $app['extensions.loader'];
    }
}

Trim fat from the extension manager

Trim fat from the extension manager


<!DOCTYPE html>

        <title>Budget</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i" />
        <link rel="stylesheet" href="/style.css" />

        @if (Auth::check())

                        Dashboard

                        Search

                        Reports

                        Budgets

                        Earnings

                        Spendings

                        Tags

                        Settings

                        Log out

        @endif

            @yield('body')

<!DOCTYPE html>

        <title>Budget</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i" />
        <link rel="stylesheet" href="/style.css" />

        @if (Auth::check())

                        Dashboard

                        Search

                        Budgets

                        Earnings

                        Spendings

                        Tags

                        Settings

                        Log out

        @endif

            @yield('body')

Remove reports from navigation in layout view


<?php

namespace Begin;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';
}

<?php

namespace Begin;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];
}

Add the attributes on the users table that are mass assignable


<?php

namespace igorw\edn;

class LexerTest extends \PHPUnit_Framework_TestCase {
    /**
     * @test
     * @dataProvider provideInvalidEdn
     * @expectedException Phlexy\LexingException
     */
    function parseShouldRejectInvalidSyntax($edn) {
        $data = tokenize($edn);

        $this->fail(sprintf('Expected parser to fail on %s, but got: %s', json_encode($edn), print_r($data, true)));
    }

    function provideInvalidEdn() {
        return [
            ['##'],
            ['#:foo'],
            [':#foo'],
            [':{'],
            [':}'],
            [':{}'],
            [':^'],
            ['^'],
            ['_:^'],
            ['.9'],
            ['/foo'],
            ['foo/'],
            [':/foo'],
            [':foo/'],
            ['#/foo'],
            ['#foo/'],
            ['foo/bar/baz'],
            ['foo/bar/baz/qux'],
            ['foo/bar/baz/qux/'],
            ['foo/bar/baz/qux/quux'],
            ['//'],
            ['///'],
            ['/foo//'],
            ['///foo'],
            ['\newline0.1'],
            ['\newline.'],
            ['.\newline'],
        ];
    }
}

<?php

namespace igorw\edn;

class LexerTest extends \PHPUnit_Framework_TestCase {
    /**
     * @test
     * @dataProvider provideInvalidEdn
     * @expectedException Phlexy\LexingException
     */
    function parseShouldRejectInvalidSyntax($edn) {
        $data = tokenize($edn);

        $this->fail(sprintf('Expected lexer to fail on %s, but got: %s', json_encode($edn), print_r($data, true)));
    }

    function provideInvalidEdn() {
        return [
            ['##'],
            ['#:foo'],
            [':#foo'],
            [':{'],
            [':}'],
            [':{}'],
            [':^'],
            ['^'],
            ['_:^'],
            ['.9'],
            ['/foo'],
            ['foo/'],
            [':/foo'],
            [':foo/'],
            ['#/foo'],
            ['#foo/'],
            ['foo/bar/baz'],
            ['foo/bar/baz/qux'],
            ['foo/bar/baz/qux/'],
            ['foo/bar/baz/qux/quux'],
            ['//'],
            ['///'],
            ['/foo//'],
            ['///foo'],
            ['\newline0.1'],
            ['\newline.'],
            ['.\newline'],
        ];
    }
}

Fix lexer test error message

Fix lexer test error message


<!DOCTYPE html>

        <title>Be right back.</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

Be right back.

<!DOCTYPE html>

        <title>Be right back.</title>

The site is temporarily unavailable (503).

Remove webfont from 503 page

Remove webfont from 503 page


<?php
/**
 * ZucchiDoctrine (http://zucchi.co.uk)
 *
 * @link      http://github.com/zucchi/ZucchiDoctrine for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zucchi Limited. (http://zucchi.co.uk)
 * @license   http://zucchi.co.uk/legals/bsd-license New BSD License
 */
namespace ZucchiDoctrine\EntityManager;

use Doctrine\ORM\EntityManager;
use Zend\ServiceManager\ServiceManager;

trait EntityManagerAwareTrait
{
    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * set the entity manager
     * @param EntityManager $em
     * @return $this
     */
    public function setEntityManager(EntityManager $em)
    {
        $this->entityManager = $em;
        return $this;
    }

    /**
     * get the currently set Entity Manager
     * @return EntityManager
     */
    public function getEntityManager()
    {
        if (!$this->entityManager && method_exists($this, 'getServiceManager')) {
            $sm = $this->getServiceManager();
            if ($sm instanceof ServiceManager) {
               $this->entityManager = $sm->get('doctrine.entitymanager.orm_default');
            }
        }
        return $this->entityManager;
    }
}

<?php
/**
 * ZucchiDoctrine (http://zucchi.co.uk)
 *
 * @link      http://github.com/zucchi/ZucchiDoctrine for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zucchi Limited. (http://zucchi.co.uk)
 * @license   http://zucchi.co.uk/legals/bsd-license New BSD License
 */
namespace ZucchiDoctrine\EntityManager;

use Doctrine\ORM\EntityManager;
use Zend\ServiceManager\ServiceManager;

trait EntityManagerAwareTrait
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * set the entity manager
     * @param EntityManager $em
     * @return $this
     */
    public function setEntityManager(EntityManager $em)
    {
        $this->entityManager = $em;
        return $this;
    }

    /**
     * get the currently set Entity Manager
     * @return EntityManager
     */
    public function getEntityManager()
    {
        if (!$this->entityManager && method_exists($this, 'getServiceManager')) {
            $sm = $this->getServiceManager();
            if ($sm instanceof ServiceManager) {
               $this->entityManager = $sm->get('doctrine.entitymanager.orm_default');
            }
        }
        return $this->entityManager;
    }
}

Update code comment for use in PHPStorm.


<?php

namespace Shrikeh\Collection;

use Countable;
use SplFixedArray;

trait FixedArrayStorageTrait
{
    public function __construct(Countable $objects)
    {
        $arr = [];
        foreach ($objects as $object) {
            $arr[] = $object;
        }
        parent::__construct(new SplFixedArray(count($arr)));

        foreach ($arr as $index => $obj) {
            $this->append($obj, $index);
        }
        $this->getStorage()->rewind();
    }

    abstract protected function getStorage();
}

<?php

namespace Shrikeh\Collection;

use Countable;
use SplFixedArray;

trait FixedArrayStorageTrait
{
    public function __construct(Traversable $objects)
    {
        $arr = [];
        foreach ($objects as $object) {
            $arr[] = $object;
        }
        parent::__construct(new SplFixedArray(count($arr)));

        foreach ($arr as $index => $obj) {
            $this->append($obj, $index);
        }
        $this->getStorage()->rewind();
    }

    abstract protected function getStorage();
}

Switch from countable to traversable

Switch from countable to traversable


<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

use \App\User;
use \App\Comments;
use PhpParser\Comment;

class CommentFactory extends Model {

	public function getComment($id) {
		return Comments::find($id);
	}

	public function deleteComment($id) {
		return Comments::destroy($id);
	}

	public function createComment($userId, $propositionId, $body) {

		return Comments::create([
				"commenter_id" => $userId,
				"proposition_id" => $propositionId,
				"body" => $body,
		]);
	}

}

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

use \App\User;
use \App\Comments;
use \App\Likes;
use PhpParser\Comment;

class CommentFactory extends Model {

	public function getComment($id) {
		return Comments::find($id);
	}

	public function deleteComment($id) {
		return Comments::destroy($id);
	}

	public function createComment($userId, $propositionId, $body) {

		return Comments::create([
				"commenter_id" => $userId,
				"proposition_id" => $propositionId,
				"body" => $body,
		]);
	}

	// Like comment
	public function likeComment(User $user, Comments $comment) {
		return Like::create([
				"user_id" => $user->id(),
				"comment_id" => $comment->commentId(),
		]);
	}

	// Remove like
	public function removeLike(Like $like) {
		return Like::destroy($like->id());
	}

}

Create and destroy for comments likes

Create and destroy for comments likes


<?php

if (isset($_GET["r"])) {
	http_response_code($_GET["r"]);
	unset($_GET["r"]);
}

if (count($_GET)) {
	foreach ($_GET as $key => $value) {
		echo isset($_SERVER[$key]) ? $_SERVER[$key] : $_REQUEST[$key];
	}
} else {
	echo ltrim($_SERVER["PATH_INFO"], "/");
}

//phpinfo();

<?php

if (isset($_GET["r"])) {
	http_response_code($_GET["r"]);
	unset($_GET["r"]);
}

if (count($_GET)) {
	foreach ($_GET as $key => $value) {
		echo isset($_SERVER[$key]) ? $_SERVER[$key] : $_REQUEST[$key];
	}
} else {
	$input = file_get_contents('php://input');
	if ($input) echo $input; else echo ltrim($_SERVER["PATH_INFO"], "/");
}

//phpinfo();

Add input (upload) echo for POST/PUT testing


<?php

namespace Faker\Provider\tr_TR;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    protected static $formats = array(
        '0##########',
        '05#########'
    );
}

Update phone number formats for tr_TR

Update phone number formats for tr_TR


<?php

namespace WP_CLI;

use \Composer\IO\NullIO;
use \WP_CLI;

/**
 * A Composer IO class so we can provide some level of interactivity from WP-CLI
 */
class ComposerIO extends NullIO {

	/**
	 * {@inheritDoc}
	 */
	public function isVerbose() {
		return true;
	}

	/**
     * {@inheritDoc}
     */
	public function write( $messages, $newline = true ) {
		self::output_clean_message( $messages );
	}

	/**
	 * {@inheritDoc}
	 */
	public function writeError( $messages, $newline = true ) {
		self::output_clean_message( $messages );
	}

	private static function output_clean_message( $message ) {
		$message = preg_replace( '#<(https?)([^>]+)>#', '$1$2', $message );
		WP_CLI::log( strip_tags( trim( $message ) ) );
	}

}

<?php

namespace WP_CLI;

use \Composer\IO\NullIO;
use \WP_CLI;

/**
 * A Composer IO class so we can provide some level of interactivity from WP-CLI
 */
class ComposerIO extends NullIO {

	/**
	 * {@inheritDoc}
	 */
	public function isVerbose() {
		return true;
	}

	/**
     * {@inheritDoc}
     */
	public function write( $messages, $newline = true, $verbosity = self::NORMAL ) {
		self::output_clean_message( $messages );
	}

	/**
	 * {@inheritDoc}
	 */
	public function writeError( $messages, $newline = true, $verbosity = self::NORMAL ) {
		self::output_clean_message( $messages );
	}

	private static function output_clean_message( $message ) {
		$message = preg_replace( '#<(https?)([^>]+)>#', '$1$2', $message );
		WP_CLI::log( strip_tags( trim( $message ) ) );
	}

}

Use the proper method signature to prevent another fatal


<?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 Drupal\AppConsole\Command;

use Drupal\AppConsole\Command\Helper\DialogHelper;
use Drupal\AppConsole\Generator\Generator;

abstract class GeneratorCommand extends ContainerAwareCommand
{
    private $generator;

    // only useful for unit tests
    public function setGenerator(Generator $generator)
    {
        $this->generator = $generator;
    }

    abstract protected function createGenerator();

    protected function getGenerator()
    {
        if (null === $this->generator) {
            $this->generator = $this->createGenerator();
            $this->generator->setSkeletonDirs($this->getSkeletonDirs());
            $this->generator->setTranslator($this->translator);
        }

        return $this->generator;
    }

    protected function getSkeletonDirs()
    {
        $skeletonDirs = array();
        $skeletonDirs[] = __DIR__.'/../Resources/skeleton';
        $skeletonDirs[] = __DIR__.'/../Resources';

        return $skeletonDirs;
    }

}

<?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 Drupal\AppConsole\Command;

use Drupal\AppConsole\Command\Helper\DialogHelper;
use Drupal\AppConsole\Generator\Generator;

abstract class GeneratorCommand extends ContainerAwareCommand
{
    private $generator;

    // only useful for unit tests
    public function setGenerator(Generator $generator)
    {
        $this->generator = $generator;
    }

    abstract protected function createGenerator();

    protected function getGenerator()
    {
        if (null === $this->generator) {
            $this->generator = $this->createGenerator();
            $this->generator->setSkeletonDirs($this->getSkeletonDirs());
            $this->generator->setTranslator($this->translator);
        }

        $this->addMessage('application.console.messages.completed');
        return $this->generator;
    }

    protected function getSkeletonDirs()
    {
        $skeletonDirs = array();
        $skeletonDirs[] = __DIR__.'/../Resources/skeleton';
        $skeletonDirs[] = __DIR__.'/../Resources';

        return $skeletonDirs;
    }
}

Add completed message-key to generator command class


<?php

namespace Brick\Money\Context;

use Brick\Money\Context;
use Brick\Money\Currency;

use Brick\Math\BigNumber;

/**
 * Adjusts the scale & step of the result to custom values.
 */
class PrecisionContext implements Context
{
    /**
     * @var int
     */
    private $scale;

    /**
     * @var int
     */
    private $step;

    /**
     * @param int $scale
     * @param int $step
     * @param int $roundingMode
     */
    public function __construct($scale, $step = 1)
    {
        $this->scale = (int) $scale;
        $this->step  = (int) $step;
    }

    /**
     * {@inheritdoc}
     */
    public function applyTo(BigNumber $amount, Currency $currency, $roundingMode)
    {
        if ($this->step === 1) {
            return $amount->toScale($this->scale, $roundingMode);
        }

        return $amount
            ->toBigRational()
            ->dividedBy($this->step)
            ->toScale($this->scale, $roundingMode)
            ->multipliedBy($this->step);
    }

    /**
     * {@inheritdoc}
     */
    public function getStep()
    {
        return $this->step;
    }
}

<?php

namespace Brick\Money\Context;

use Brick\Money\Context;
use Brick\Money\Currency;

use Brick\Math\BigNumber;

/**
 * Adjusts the scale & step of the result to custom values.
 */
class PrecisionContext implements Context
{
    /**
     * @var int
     */
    private $scale;

    /**
     * @var int
     */
    private $step;

    /**
     * @param int $scale
     * @param int $step
     */
    public function __construct($scale, $step = 1)
    {
        $this->scale = (int) $scale;
        $this->step  = (int) $step;
    }

    /**
     * {@inheritdoc}
     */
    public function applyTo(BigNumber $amount, Currency $currency, $roundingMode)
    {
        if ($this->step === 1) {
            return $amount->toScale($this->scale, $roundingMode);
        }

        return $amount
            ->toBigRational()
            ->dividedBy($this->step)
            ->toScale($this->scale, $roundingMode)
            ->multipliedBy($this->step);
    }

    /**
     * {@inheritdoc}
     */
    public function getStep()
    {
        return $this->step;
    }
}

Fix doc for non-existing parameter

Fix doc for non-existing parameter


<?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\Security\Core;

/**
 * This class holds security information.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
final class Security
{
    const ACCESS_DENIED_ERROR  = '_security.403_error';
    const AUTHENTICATION_ERROR = '_security.last_error';
    const LAST_USERNAME        = '_security.last_username';
}

Remove aligned '=>' and '='

Remove aligned '=>' and '='


<?php

namespace Dusterio\AwsWorker\Integrations;

use Dusterio\AwsWorker\Wrappers\WorkerInterface;
use Dusterio\AwsWorker\Wrappers\DefaultWorker;
use Dusterio\AwsWorker\Wrappers\Laravel53Worker;

/**
 * Class BindsWorker
 * @package Dusterio\AwsWorker\Integrations
 */
trait BindsWorker
{
    /**
     * @var array
     */
    protected $workerImplementations = [
        '5\.[34].*' => Laravel53Worker::class
    ];

    /**
     * @param $version
     * @return mixed
     */
    protected function findWorkerClass($version)
    {
        foreach ($this->workerImplementations as $regexp => $class) {
            if (preg_match('/' . $regexp . '/', $version)) return $class;
        }

        return DefaultWorker::class;
    }

    /**
     * @return void
     */
    protected function bindWorker()
    {
        $this->app->bind(WorkerInterface::class, $this->findWorkerClass($this->app->version()));
    }
}

<?php

namespace Dusterio\AwsWorker\Integrations;

use Dusterio\AwsWorker\Wrappers\WorkerInterface;
use Dusterio\AwsWorker\Wrappers\DefaultWorker;
use Dusterio\AwsWorker\Wrappers\Laravel53Worker;

/**
 * Class BindsWorker
 * @package Dusterio\AwsWorker\Integrations
 */
trait BindsWorker
{
    /**
     * @var array
     */
    protected $workerImplementations = [
        '5\.[345].*' => Laravel53Worker::class
    ];

    /**
     * @param $version
     * @return mixed
     */
    protected function findWorkerClass($version)
    {
        foreach ($this->workerImplementations as $regexp => $class) {
            if (preg_match('/' . $regexp . '/', $version)) return $class;
        }

        return DefaultWorker::class;
    }

    /**
     * @return void
     */
    protected function bindWorker()
    {
        $this->app->bind(WorkerInterface::class, $this->findWorkerClass($this->app->version()));
    }
}

Include Laravel 5.5 in Laravel53Worker implementation