<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2004-2009 Chris Corbyn
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Sends Messages over SMTP with ESMTP support.
 * @package Swift
 * @subpackage Transport
 * @author Chris Corbyn
 */
class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport
{
    /**
     * Create a new SmtpTransport, optionally with $host, $port and $security.
     * @param string $host
     * @param int    $port
     * @param int    $security
     */
    public function __construct($host = 'localhost', $port = 25, $security = null)
    {
        call_user_func_array(
            array($this, 'Swift_Transport_EsmtpTransport::__construct'),
            Swift_DependencyContainer::getInstance()
                ->createDependenciesFor('transport.smtp')
            );

        $this->setHost($host);
        $this->setPort($port);
        $this->setEncryption($security);
    }

    /**
     * Create a new SmtpTransport instance.
     * @param  string              $host
     * @param  int                 $port
     * @param  int                 $security
     * @return Swift_SmtpTransport
     */
    public static function newInstance($host = 'localhost', $port = 25, $security = null)
    {
        return new self($host, $port, $security);
    }
}

<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2004-2009 Chris Corbyn
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Sends Messages over SMTP with ESMTP support.
 * @package Swift
 * @subpackage Transport
 * @author Chris Corbyn
 */
class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport
{
    /**
     * Create a new SmtpTransport, optionally with $host, $port and $security.
     * @param string $host
     * @param int    $port
     * @param string $security
     */
    public function __construct($host = 'localhost', $port = 25, $security = null)
    {
        call_user_func_array(
            array($this, 'Swift_Transport_EsmtpTransport::__construct'),
            Swift_DependencyContainer::getInstance()
                ->createDependenciesFor('transport.smtp')
            );

        $this->setHost($host);
        $this->setPort($port);
        $this->setEncryption($security);
    }

    /**
     * Create a new SmtpTransport instance.
     * @param  string              $host
     * @param  int                 $port
     * @param  string              $security
     * @return Swift_SmtpTransport
     */
    public static function newInstance($host = 'localhost', $port = 25, $security = null)
    {
        return new self($host, $port, $security);
    }
}

Fix type hint, setEncryption accept string parameter


<?php

declare(strict_types=1);

namespace SpotifyWebAPI;

class SpotifyWebAPIException extends \Exception
{
    public const TOKEN_EXPIRED = 'The access token expired';
    public const RATE_LIMIT_STATUS = 429;

    /**
     * The reason string from the request's error object.
     *
     * @var string
     */
    private $reason;

    /**
     * Returns the reason string from the request's error object.
     *
     * @see https://developer.spotify.com/documentation/web-api/reference/object-model/#player-error-reasons
     *
     * @return string
     */
    public function getReason()
    {
        return $this->reason;
    }

    /**
     * Returns whether the exception was thrown because of an expired access token.
     *
     * @return bool
     */
    public function hasExpiredToken()
    {
        return $this->getMessage() === self::TOKEN_EXPIRED;
    }

    /**
     * Returns whether the exception was thrown because of rate limiting.
     *
     * @return bool
     */
    public function isRateLimited()
    {
        return $this->getCode() === self::RATE_LIMIT_STATUS;
    }

    /**
     * Set the reason string.
     *
     * @param string $reason
     *
     * @return void
     */
    public function setReason($reason)
    {
        $this->reason = $reason;
    }
}

<?php

declare(strict_types=1);

namespace SpotifyWebAPI;

class SpotifyWebAPIException extends \Exception
{
    public const TOKEN_EXPIRED = 'The access token expired';
    public const RATE_LIMIT_STATUS = 429;

    /**
     * The reason string from a player request's error object.
     *
     * @var string
     */
    private $reason;

    /**
     * Returns the reason string from a player request's error object.
     *
     * @return string
     */
    public function getReason()
    {
        return $this->reason;
    }

    /**
     * Returns whether the exception was thrown because of an expired access token.
     *
     * @return bool
     */
    public function hasExpiredToken()
    {
        return $this->getMessage() === self::TOKEN_EXPIRED;
    }

    /**
     * Returns whether the exception was thrown because of rate limiting.
     *
     * @return bool
     */
    public function isRateLimited()
    {
        return $this->getCode() === self::RATE_LIMIT_STATUS;
    }

    /**
     * Set the reason string.
     *
     * @param string $reason
     *
     * @return void
     */
    public function setReason($reason)
    {
        $this->reason = $reason;
    }
}

Remove outdated player error reasons link


<?php
namespace Maphper\DataSource;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
	private $processCache;

	public function replaceDates($obj, $reset = true) {
		//prevent infinite recursion, only process each object once
		if ($reset) $this->processCache = new \SplObjectStorage();
		if (is_object($obj) && $this->processCache->contains($obj)) return $obj;
		else if (is_object($obj)) $this->processCache->attach($obj, true);

		if (is_array($obj) || (is_object($obj) && (!$obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
		if (is_string($obj) && is_numeric($obj[0]) && strlen($obj) <= 20) {
			try {
				$date = new \DateTime($obj);
				if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date;
			}
			catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
			}
		}
		return $obj;
	}
}

<?php
namespace Maphper\DataSource;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
	private $processCache;

	public function replaceDates($obj, $reset = true) {
		//prevent infinite recursion, only process each object once
		if ($reset) $this->processCache = new \SplObjectStorage();
		if (is_object($obj) && $this->processCache->contains($obj)) return $obj;
		else if (is_object($obj)) $this->processCache->attach($obj, true);

		if (is_array($obj) || (is_object($obj) && (!$obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
		if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) {
			try {
				$date = new \DateTime($obj);
				if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date;
			}
			catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
			}
		}
		return $obj;
	}
}

Fix error if column has empty string

Fix error if column has empty string


<?php

class Info
{
    function getUsername($id)
    {
        $sql = "SELECT username FROM user WHERE id=" . (int)$id;
        $result = mysql_fetch_array(mysql_query($sql));

        return $result[0];
    }
}

<?php

class Info
{
    function getUsername($id)
    {
        global $container;
        $userRepository = $container->get('acme.demo.repository.user');
        $user = $userRepository->find($id);

        return $user->getUsername();
    }
}

Use UserRepository in legacy side

Use UserRepository in legacy side


<?php
namespace VXML;

/**
 * Autoloader for loading rules, without having to include them first
 */
class Loader
{
	/**
	 * Register autoloader, call this to have classes automatically included.
	 * Required VXML to be in include path.
	 */
	static public function registerAutoload()
	{
		spl_autoload_register(array('VXML\Loader', 'autoload'));
	}

	/**
	 * Actual autoloader method
	 *
	 * @param string $class
	 */
	static public function autoload($class)
	{
		if(class_exists($class, false) || interface_exists($class, false))
		{
			return;
		}

		$file = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
		require_once $file;
	}
}

<?php
namespace VXML;

/**
 * Autoloader for loading rules, without having to include them first
 */
class Loader
{
	/**
	 * Register autoloader, call this to have classes automatically included.
	 * Required VXML to be in include path.
	 */
	static public function registerAutoload()
	{
		spl_autoload_register(array('VXML\Loader', 'autoload'));
	}

	/**
	 * Actual autoloader method
	 *
	 * @param string $class
	 */
	static public function autoload($class)
	{
		if(class_exists($class, false) || interface_exists($class, false))
		{
			return;
		}

		$file = str_replace('\\', \DIRECTORY_SEPARATOR, $class) . '.php';
		require_once $file;
	}
}

Fix autoload to work properly with namespace separators (was working by accident on windows)


<?php
namespace nochso\WriteMe\Test\Placeholder;

use nochso\WriteMe\Document;
use nochso\WriteMe\Placeholder\TOC;

class TOCTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider applyProvider
     *
     * @param string $input
     * @param string $expected
     */
    public function testApply($input, $expected)
    {
        $document = new Document($input);
        $toc = new TOC();
        $toc->apply($document);
        $this->assertSame($expected, $document->getContent());
    }

    public function applyProvider()
    {
        return [
            [
                '@toc@',
                '',
            ],
            [
                '',
                '',
            ],
            [
                "@toc@\n# a",
                "- [a](#a)\n# a",
            ],
            'Links must be stripped from headers' => [
                "@toc@\n# [0.3.2] - 2016-03-16",
                "- [0.3.2 - 2016-03-16](#032---2016-03-16)\n# [0.3.2] - 2016-03-16",
            ],
            'Only links must be stripped from headers' => [
                "@toc@\n# [link text](target.md) in **header**",
                "- [link text in **header**](#link-text-in-header)\n# [link text](target.md) in **header**",
            ],
        ];
    }
}

<?php
namespace nochso\WriteMe\Test\Placeholder;

use nochso\WriteMe\Document;
use nochso\WriteMe\Placeholder\Call;
use nochso\WriteMe\Placeholder\TOC;

class TOCTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider callProvider
     *
     * @param string $input
     * @param string $expected
     */
    public function testCall($input, $expected)
    {
        $document = new Document($input);
        $toc = new TOC();
        $call = Call::extractFirstCall($document);
        $toc->call($call);
        $this->assertSame($expected, $document->getContent());
    }

    public function callProvider()
    {
        return [
            [
                '@toc@',
                '',
            ],
            [
                "@toc@\n# a",
                "- [a](#a)\n# a",
            ],
            'Links must be stripped from headers' => [
                "@toc@\n# [0.3.2] - 2016-03-16",
                "- [0.3.2 - 2016-03-16](#032---2016-03-16)\n# [0.3.2] - 2016-03-16",
            ],
            'Only links must be stripped from headers' => [
                "@toc@\n# [link text](target.md) in **header**",
                "- [link text in **header**](#link-text-in-header)\n# [link text](target.md) in **header**",
            ],
        ];
    }
}

test: Update TOC test to reflect new behaviour


<?php
class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{

	// Create the xml for the user supplied
	function export( $uid ){

		$options = array(
			'table'=>'bookmarks',
			'matchcol'=>'user_id',
			'matchval'=>$uid,
			'idcol'=>'id'
		);
		$ids = OC_Migrate::copyRows( $options );
		$ids = array('1');
		$options = array(
			'table'=>'bookmarks_tags',
			'matchcol'=>'bookmark_id',
			'matchval'=>$ids
		);

		// Export tags
		OC_Migrate::copyRows( $options );

	}

	// Import function for bookmarks
	function import( $data, $uid ){

		// new id mapping
		$newids = array();

		// Import bookmarks
		foreach($data['bookmarks'] as $bookmark){
			$bookmark['user_id'] = $uid;
			// import to the db now
			$newids[$bookmark['id']] = OC_DB::insertid();
		}

		// Import tags
		foreach($data['bookmarks_tags'] as $tag){
			// Map the new ids
			$tag['id'] = $newids[$tag['id']];
			// Import to the db now using OC_DB
		}
	}

}

new OC_Migrate_Provider_Bookmarks( 'bookmarks' );

<?php
class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{

	// Create the xml for the user supplied
	function export( $uid ){
		OC_Log::write('migration','starting export for bookmarks',OC_Log::INFO);
		$options = array(
			'table'=>'bookmarks',
			'matchcol'=>'user_id',
			'matchval'=>$uid,
			'idcol'=>'id'
		);
		$ids = OC_Migrate::copyRows( $options );

		$options = array(
			'table'=>'bookmarks_tags',
			'matchcol'=>'bookmark_id',
			'matchval'=>$ids
		);

		// Export tags
		OC_Migrate::copyRows( $options );

	}

	// Import function for bookmarks
	function import( $data, $uid ){

		// new id mapping
		$newids = array();

		// Import bookmarks
		foreach($data['bookmarks'] as $bookmark){
			$bookmark['user_id'] = $uid;
			// import to the db now
			$newids[$bookmark['id']] = OC_DB::insertid();
		}

		// Import tags
		foreach($data['bookmarks_tags'] as $tag){
			// Map the new ids
			$tag['id'] = $newids[$tag['id']];
			// Import to the db now using OC_DB
		}
	}

}

new OC_Migrate_Provider_Bookmarks( 'bookmarks' );

Fix copyRows() and sqlite connection

Fix copyRows() and sqlite connection


<?php
error_reporting(E_ALL);

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

<?php
error_reporting(E_ALL);

require_once(realpath(dirname(__FILE__)) . '/../vendor/autoload.php');

Fix tests for Travis CI

Fix tests for Travis CI


<?php
require_once  __DIR__ . '/../vendor/autoload.php';

function autoload( $rootDir ) {
    spl_autoload_register(function( $className ) use ( $rootDir ) {
        $file = sprintf(
            '%s/%s.php',
            $rootDir,
            str_replace( '\\', '/', $className )
        );

        if ( file_exists($file) ) {
            require $file;
        }
    });
}

autoload( '/usr/share/php' );
autoload( __DIR__ . '/');

<?php
ini_set('display_errors', 'On');
ini_set('error_reporting', -1);

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

function autoload( $rootDir ) {
    spl_autoload_register(function( $className ) use ( $rootDir ) {
        $file = sprintf(
            '%s/%s.php',
            $rootDir,
            str_replace( '\\', '/', $className )
        );

        if ( file_exists($file) ) {
            require $file;
        }
    });
}

autoload( '/usr/share/php' );
autoload( __DIR__ . '/');

Enable maximum error reporting for tests


<?php

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

class CreatePostsTable extends Migration {

	/**
	 * Run the migrations.
	 *P
	 * @return void
	 */
	public function up()
	{
		Schema::create('posts', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('user_id');
			$table->string('title');
			$table->string('slug')->unique();
			$table->text('body');
			$table->string('image')->nullable();
			$table->timestamp('published_at')->nullable();
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreatePostsTable extends Migration {

	/**
	 * Run the migrations.
	 *P
	 * @return void
	 */
	public function up()
	{
		Schema::create('posts', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('user_id');
			$table->string('type')->default('post');
			$table->string('title');
			$table->string('slug')->unique();
			$table->text('body');
			$table->string('image')->nullable();
			$table->timestamp('published_at')->nullable();
			$table->timestamps();
		});
	}

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

}

Add type column to posts table

Add type column to posts table


<?php

namespace Elchristo\Calendar\Converter;

use Elchristo\Calendar\Exception\RuntimeException;
use Elchristo\Calendar\Model\Event\CalendarEventInterface;

/**
 * Factory to build convertible events
 */
class ConvertibleEventFactory
{
    const DEFAULT_NAMESPACE_PREFIX = __NAMESPACE__ . '\\';

    private $registeredConverters = [];

    /**
     * @param array $registeredConverters Declared converters in configuration
     */
    public function __construct(array $registeredConverters = [])
    {
        $this->registeredConverters = $registeredConverters;
    }

    /**
     * Build instance of convertable event (default event if not found)
     *
     * @param CalendarEventInterface $event  Calendar event to convert
     * @param string                 $format Output format
     */
    public function build(CalendarEventInterface $event, $format)
    {
        $key = \get_class($event);
        $name = \ucfirst($format);

        try {
            if (isset($this->registeredConverters[$name]) && \array_key_exists($key, $this->registeredConverters[$name])) {
                $eventClass = $this->registeredConverters[$name][$key];
                return new $eventClass($event);
            }

            $defaultEventClass = self::DEFAULT_NAMESPACE_PREFIX . "{$name}\Event\Default{$name}Event";
            return new $defaultEventClass($event);
        } catch (\Exception $e) {
            throw new RuntimeException("Impossible to build event of type {$event->getType()}.", $e->getCode(), $e);
        }
    }
}

<?php

namespace Elchristo\Calendar\Converter;

use Elchristo\Calendar\Exception\RuntimeException;
use Elchristo\Calendar\Model\Event\CalendarEventInterface;

/**
 * Factory to build events which can be converted into various output formats
 */
class ConvertibleEventFactory
{
    private $registeredConverters = [];

    /**
     * @param array $registeredConverters Declared converters in configuration
     */
    public function __construct(array $registeredConverters = [])
    {
        $this->registeredConverters = $registeredConverters;
    }

    /**
     * Build instance of event converter ("default" if not found)
     *
     * @param CalendarEventInterface $event  Calendar event to convert
     * @param string                 $format Output format
     * @return ConvertibleEventInterface
     */
    public function build(CalendarEventInterface $event, $format)
    {
        $key = \get_class($event);
        $name = \ucfirst($format);

        try {
            $eventClass = (isset($this->registeredConverters[$name]) && isset($this->registeredConverters[$name][$key]))
                ? $this->registeredConverters[$name][$key]
                : __NAMESPACE__ . "\\" . $name . "\Event\Default{$name}Event";

            return new $eventClass($event);
        } catch (\Exception $e) {
            throw new RuntimeException("Impossible to build converter for calendar event of type {$event->getType()}.", $e->getCode(), $e);
        }
    }
}

Improve documentation and clean up

Improve documentation and clean up


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Application Path
	|--------------------------------------------------------------------------
	|
	| Here we just defined the path to the application directory. Most likely
	| you will never need to change this value as the default setup should
	| work perfectly fine for the vast majority of all our applications.
	|
	*/

	'app' => __DIR__.'/../app',

	/*
	|--------------------------------------------------------------------------
	| Public Path
	|--------------------------------------------------------------------------
	|
	| The public path contains the assets for your web application, such as
	| your JavaScript and CSS files, and also contains the primary entry
	| point for web requests into these applications from the outside.
	|
	*/

	'public' => __DIR__.'/../public',

	/*
	|--------------------------------------------------------------------------
	| Base Path
	|--------------------------------------------------------------------------
	|
	| The base path is the root of the Laravel installation. Most likely you
	| will not need to change this value. But, if for some wild reason it
	| is necessary you will do so here, just proceed with some caution.
	|
	*/

	'base' => __DIR__.'/..',

	/*
	|--------------------------------------------------------------------------
	| Storage Path
	|--------------------------------------------------------------------------
	|
	| The storage path is used by Laravel to store cached Blade views, logs
	| and other pieces of information. You may modify the path here when
	| you want to change the location of this directory for your apps.
	|
	*/

	'storage' => __DIR__.'/../storage',

);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Application Path
	|--------------------------------------------------------------------------
	|
	| Here we just defined the path to the application directory. Most likely
	| you will never need to change this value as the default setup should
	| work perfectly fine for the vast majority of all our applications.
	|
	*/

	'app' => __DIR__.'/../app',

	/*
	|--------------------------------------------------------------------------
	| Public Path
	|--------------------------------------------------------------------------
	|
	| The public path contains the assets for your web application, such as
	| your JavaScript and CSS files, and also contains the primary entry
	| point for web requests into these applications from the outside.
	|
	*/

	'public' => __DIR__.'/../www',

	/*
	|--------------------------------------------------------------------------
	| Base Path
	|--------------------------------------------------------------------------
	|
	| The base path is the root of the Laravel installation. Most likely you
	| will not need to change this value. But, if for some wild reason it
	| is necessary you will do so here, just proceed with some caution.
	|
	*/

	'base' => __DIR__.'/..',

	/*
	|--------------------------------------------------------------------------
	| Storage Path
	|--------------------------------------------------------------------------
	|
	| The storage path is used by Laravel to store cached Blade views, logs
	| and other pieces of information. You may modify the path here when
	| you want to change the location of this directory for your apps.
	|
	*/

	'storage' => __DIR__.'/../storage',

);

Fix uploading for files with troubles another root domain


<?php

if ( is_single() ) :
	$thumbnail_size = 'large';
else :
	$thumbnail_size = 'thumbnail';
endif;

?>

	<a href="<?php the_permalink(); ?>">
		<?php the_post_thumbnail( $thumbnail_size ); ?>

<?php

if ( is_single() ) :
	$thumbnail_size = 'large';
else :
	$thumbnail_size = 'thumbnail';
endif;

$thumbnail_caption = esc_html( get_the_post_thumbnail_caption() );

?>

    <a href="<?php (is_single() ? the_post_thumbnail_url() : the_permalink() ); ?>">
		<?php the_post_thumbnail( $thumbnail_size ); ?>

    <?php if ($thumbnail_caption) : printf( '
%s
', $thumbnail_caption ); endif ?>

Add thumbnail caption and restructure code


<?php

namespace FullyBaked\Pslackr\Messages;

use PHPUnit_Framework_TestCase;
use Exception;

class MessageTest extends PHPUnit_Framework_TestCase
{
    public function testAsJson()
    {
        $message = new Message();
        $message->text('Message text goes here');
        $result = $message->asJson();
        $expected = '{"text":"Message text goes here"}';
        $this->assertEquals($result, $expected);

        $message->text('Change the message and check');
        $result = $message->asJson();
        $expected = '{"text":"Change the message and check"}';
        $this->assertEquals($result, $expected);
    }
}

<?php

namespace FullyBaked\Pslackr\Messages;

use PHPUnit_Framework_TestCase;
use Exception;

class MessageTest extends PHPUnit_Framework_TestCase
{
    public function testAsJsonReturnsMinimumJsonRequired()
    {
        $message = new Message();
        $message->text('Message text goes here');
        $result = $message->asJson();
        $expected = '{"text":"Message text goes here"}';
        $this->assertEquals($result, $expected);

        $message->text('Change the message and check');
        $result = $message->asJson();
        $expected = '{"text":"Change the message and check"}';
        $this->assertEquals($result, $expected);
    }
}

Change test name for json test

Change test name for json test


<?php

return [
    /*
     * 各 model 對應的顯示路由
     */
    'route' => [
        \App\User::class     => 'user.show',
        \App\Club::class     => 'clubs.show',
        \App\TeaParty::class => 'tea-party.show',
    ],
];

<?php

return [
    /*
     * 各 model 對應的顯示路由
     */
    'route' => [
        \App\User::class              => 'user.show',
        \App\Club::class              => 'clubs.show',
        \App\TeaParty::class          => 'tea-party.show',
        \App\DataUpdateRequest::class => 'data-update-request.show',
    ],
];

Make DataUpdateRequest in ActivityLog clickable


<?php

namespace ShvetsGroup\LaravelEmailDatabaseLog;

use DB;
use Illuminate\Mail\Events\MessageSending;

class EmailLogger
{
    /**
     * Handle the event.
     *
     * @param MessageSending $event
     */
    public function handle(MessageSending $event)
    {
        $message = $event->message;

        DB::table('email_log')->insert([
            'date' => date('Y-m-d H:i:s'),
            'to' => $message->getHeaders()->get('To')->getFieldBody(),
            'subject' => $message->getHeaders()->get('Subject')->getFieldBody(),
            'body' => $this->getMimeEntityString($message),
        ]);
    }

    /**
     * Get a loggable string out of a Swiftmailer entity.
     *
     * @param  \Swift_Mime_MimeEntity $entity
     * @return string
     */
    protected function getMimeEntityString(\Swift_Mime_MimeEntity $entity)
    {
        $string = (string) $entity->getHeaders().PHP_EOL.$entity->getBody();

        foreach ($entity->getChildren() as $children) {
            $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children);
        }

        return $string;
    }
}

<?php

namespace ShvetsGroup\LaravelEmailDatabaseLog;

use DB;
use Illuminate\Mail\Events\MessageSending;

class EmailLogger
{
    /**
     * Handle the event.
     *
     * @param MessageSending $event
     */
    public function handle(MessageSending $event)
    {
        $message = $event->message;

        DB::table('email_log')->insert([
            'date' => date('Y-m-d H:i:s'),
            'to' => !$message->getHeaders()->get('To') ? null : $message->getHeaders()->get('To')->getFieldBody(),
			'bcc' => !$message->getHeaders()->get('Bcc') ? null : $message->getHeaders()->get('Bcc')->getFieldBody(),
            'subject' => $message->getHeaders()->get('Subject')->getFieldBody(),
            'body' => $this->getMimeEntityString($message),
        ]);
    }

    /**
     * Get a loggable string out of a Swiftmailer entity.
     *
     * @param  \Swift_Mime_MimeEntity $entity
     * @return string
     */
    protected function getMimeEntityString(\Swift_Mime_MimeEntity $entity)
    {
        $string = (string) $entity->getHeaders().PHP_EOL.$entity->getBody();

        foreach ($entity->getChildren() as $children) {
            $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children);
        }

        return $string;
    }
}

Fix error to address not present

Fix error to address not present

Same times to address not pass to mail class, just bcc address.


<?php

namespace Pagon\Utility;

class Cli
{
    /**
     * Color output text for the CLI
     *
     * @param string      $text       to color
     * @param string      $color      of text
     * @param bool|string $bold       color
     * @param string      $bg_color   background color
     * @return string
     */
    public static function colorize($text, $color, $bold = false, $bg_color = 'default')
    {
        $colors = array_flip(array(30 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'default'));

        $bg_colors = array_flip(array(40 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'default'));

        return "\033[" . ($bold ? '1' : '0') . ';' . $colors[$color] . ';' . $bg_colors[$bg_color] . "m$text\033[0m";
    }

}

<?php

namespace Pagon\Utility;

class Cli
{
    /**
     * Color output text for the CLI
     *
     * @param string      $text       to color
     * @param string      $color      of text
     * @param bool|string $bold       color
     * @param string      $bg_color   background color
     * @return string
     */
    public static function colorize($text, $color, $bold = false, $bg_color = 'default')
    {
        $colors = array_flip(array(30 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white'));

        $bg_colors = array_flip(array(40 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 49 => 'default'));

        return "\033[" . ($bold ? '1' : '0') . ';' . $colors[$color] . ';' . $bg_colors[$bg_color] . "m$text\033[0m";
    }

}

Add background colors of cli support

Add background colors of cli support


<?php

class FreshRSS_Share {

	static public function generateUrl($options, $selected, $link, $title) {
		$share = $options[$selected['type']];
		$matches = array(
			'~URL~',
			'~TITLE~',
			'~LINK~',
		);
		$replaces = array(
			$selected['url'],
			self::transformData($title, self::getTransform($share, 'title')),
			self::transformData($link, self::getTransform($share, 'link')),
		);
		$url = str_replace($matches, $replaces, $share['url']);
		return $url;
	}

	static private function transformData($data, $transform) {
		if (!is_array($transform)) {
			return $data;
		}
		if (count($transform) === 0) {
			return $data;
		}
		foreach ($transform as $action) {
			$data = call_user_func($action, $data);
		}
		return $data;
	}

	static private function getTransform($options, $type) {
		$transform = $options['transform'];

		if (array_key_exists($type, $transform)) {
			return $transform[$type];
		}

		return $transform;
	}

}

<?php

class FreshRSS_Share {

	static public function generateUrl($options, $selected, $link, $title) {
		if (!array_key_exists('url', $selected)) {
			$selected['url'] = '';
		}
		$share = $options[$selected['type']];
		$matches = array(
			'~URL~',
			'~TITLE~',
			'~LINK~',
		);
		$replaces = array(
			$selected['url'],
			self::transformData($title, self::getTransform($share, 'title')),
			self::transformData($link, self::getTransform($share, 'link')),
		);
		$url = str_replace($matches, $replaces, $share['url']);
		return $url;
	}

	static private function transformData($data, $transform) {
		if (!is_array($transform)) {
			return $data;
		}
		if (count($transform) === 0) {
			return $data;
		}
		foreach ($transform as $action) {
			$data = call_user_func($action, $data);
		}
		return $data;
	}

	static private function getTransform($options, $type) {
		$transform = $options['transform'];

		if (array_key_exists($type, $transform)) {
			return $transform[$type];
		}

		return $transform;
	}

}

Add a default URL value

Add a default URL value


<?php

use JsLocalization\StaticFileResponse;

Route::get('/js-localization/messages', 'JsLocalizationController@createJsMessages');

Route::get('/js-localization/localization.js', function()
{
    $response = new StaticFileResponse( __DIR__."/../public/js/localization.min.js" );
    $response->setPublic();

    return $response;
});

<?php

use JsLocalization\StaticFileResponse;

Route::get('/js-localization/messages', 'JsLocalizationController@createJsMessages');

Route::get('/js-localization/localization.js', function()
{
    $response = new StaticFileResponse( __DIR__."/../public/js/localization.min.js" );
    $response->setPublic();
    $response->header('Content-Type', 'application/javascript');

    return $response;
});

Set Content-Type application/javascript for localization.js


<?php

declare(strict_types=1);

return [

    /*
    |--------------------------------------------------------------------------
    | Default Preset
    |--------------------------------------------------------------------------
    |
    | This option controls the default preset that will be used by PHP Insights
    | to make your code reliable, simple, and clean. However, you can always
    | adjust the `Metrics` and `Insights` below in this configuration file.
    |
    | Supported: "default", "laravel", "symfony"
    |
    */

    'preset' => 'symfony',

    /*
    |--------------------------------------------------------------------------
    | Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may adjust all the various `Insights` that will be used by PHP
    | Insights. You can either add, remove or configure `Insights`. Keep in
    | mind, that all added `Insights` must belong to a specific `Metric`.
    |
    */

    'add' => [
        //  ExampleMetric::class => [
        //      ExampleInsight::class,
        //  ]
    ],

    'remove' => [
        //  ExampleInsight::class,
    ],

    'config' => [
        //  ExampleInsight::class => [
        //      'key' => 'value',
        //  ],
    ],

];

<?php

declare(strict_types=1);

return [

    /*
    |--------------------------------------------------------------------------
    | Default Preset
    |--------------------------------------------------------------------------
    |
    | This option controls the default preset that will be used by PHP Insights
    | to make your code reliable, simple, and clean. However, you can always
    | adjust the `Metrics` and `Insights` below in this configuration file.
    |
    | Supported: "default", "laravel", "symfony"
    |
    */

    'preset' => 'symfony',

    /*
    |--------------------------------------------------------------------------
    | Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may adjust all the various `Insights` that will be used by PHP
    | Insights. You can either add, remove or configure `Insights`. Keep in
    | mind, that all added `Insights` must belong to a specific `Metric`.
    |
    */

    'add' => [
        //  ExampleMetric::class => [
        //      ExampleInsight::class,
        //  ]
    ],

    'remove' => [
        //  ExampleInsight::class,
        ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
        ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
    ],

    'config' => [
        //  ExampleInsight::class => [
        //      'key' => 'value',
        //  ],
    ],

];

Disable some PHP insights sniffs

tests: Disable some PHP insights sniffs


<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraints\GroupSequence;

class MaterialItemUpdateGroupSequence {
    public function __invoke() {
        return new GroupSequence(['materialItem:update', 'Default']); // now, no matter which is first in the class declaration, it will be tested in this order.
    }
}

<?php

namespace App\Validator;

use ApiPlatform\Core\Bridge\Symfony\Validator\ValidationGroupsGeneratorInterface;
use Symfony\Component\Validator\Constraints\GroupSequence;

class MaterialItemUpdateGroupSequence implements ValidationGroupsGeneratorInterface {
    public function __invoke($object) {
        return new GroupSequence(['materialItem:update', 'Default']); // now, no matter which is first in the class declaration, it will be tested in this order.
    }
}

Fix deprecation warnings for api platform 2.6


    <?= e('%s updated a comment on the task #%d', Helper\escape($author), $task_id, $task_id) ?>

    <?= Helper\escape($task['title']) ?>

<?= Helper\markdown($comment['comment']) ?>

Remove content of a comment update event


<?php
  if ( is_page( 'Home' ) ) { ?>

Latest opportunities from the last 7 days

        <?php
          $args = array('category_name' => 'Solicitations', 'date_query' => array(array('after' => '1 week ago')));
          $posts_query = new WP_Query( $args );

          while ($posts_query->have_posts()) : $posts_query->the_post(); ?>

              <a href="<?php echo the_permalink(); ?>"><?php echo the_title(); ?>

        <?php endwhile; remove_filter( 'posts_where', 'filter_where' ); wp_reset_query(); ?>

<?php } ?>

<?php
  if ( is_page( 'Home' ) ) { ?>

Latest opportunities from the last 7 days

        <?php
          $args = array('category_name' => 'Solicitations', 'date_query' => array(array('after' => '1 week ago')));
          $posts_query = new WP_Query( $args );

          while ($posts_query->have_posts()) : $posts_query->the_post(); ?>

              <a href="<?php echo the_permalink(); ?>"><?php echo the_title(); ?>

        <?php endwhile;
              remove_filter( 'posts_where', 'filter_where' );
              wp_reset_query();

              if(!$posts_query->have_posts()): ?>
                No new solicitations posted within the last week. <a href="<?php echo site_url( '/solicitations/' ); ?>">See previous solicitations.
        <?php endif; ?>

<?php } ?>

Cover what happens if no new solicitations are posted.


<?php

class Default_Model_UserMapper extends Default_Model_AbstractMapper
{
	public function findNickname($nickname)
	{
		$select = $this->getDbTable()->select()
			->where('nickname = ?', $nickname);

		$record = $this->getDbTable()->fetchRow($select);

		return $record;
	}

	public function findEmailPassword($email, $password)
	{
		$select = $this->getDbTable()->select()
			->where('email = ?', $email)
			->where('password = ?', $password);

		$record = $this->getDbTable()->fetchRow($select);

		return $record;
	}

    public function find($id)
    {
        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll(null, 'nickname');

        return $resultSet;
    }
}

?>

<?php

class Default_Model_UserMapper extends Default_Model_AbstractMapper
{
	public function findNickname($nickname)
	{
		$select = $this->getDbTable()->select()
			->where('nickname = ?', $nickname);

		$record = $this->getDbTable()->fetchRow($select);

		return $record;
	}

	public function findEmailPassword($email, $password)
	{
		$select = $this->getDbTable()->select()
			->where('email = ?', $email)
			->where('password = ?', $password);

		$record = $this->getDbTable()->fetchRow($select);

		return $record;
	}

    public function find($id)
    {
        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll(null, 'LOWER(nickname)');

        return $resultSet;
    }
}

?>

FIX user are sorted case insensitive

FIX user are sorted case insensitive


<?php

namespace Phramework\ValidateFiller;

use Phramework\Validate\BaseValidator;
use Phramework\Validate\IntegerValidator;

/**
 * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @since  0.1.0
 * @author Xenofon Spafaridis <nohponex@gmail.com>
 */
class IntegerValidatorFiller implements IValidatorFiller
{
    /**
     * @param IntegerValidator $validator
     * @return int
     */
    public function fill(BaseValidator $validator)
    {
        $faker = \Faker\Factory::create();

        $minimum = $validator->minimum ?? PHP_INT_MIN;

        $maximum = $validator->maximum ?? PHP_INT_MAX;

        if ($validator->exclusiveMinimum) {
            $minimum +=1;
        }

        if ($validator->exclusiveMaximum) {
            $maximum -= 1;
        }

        /*
         * generate an non exclusive number
         */
        $number = $faker->numberBetween(
            $minimum,
            $maximum
        );

        /*
         * Ensure multipleOf
         */
        $number = ((int) ($number / $validator->multipleOf)) * $validator->multipleOf;

        return $number;
    }
}

<?php

namespace Phramework\ValidateFiller;

use Phramework\Validate\BaseValidator;
use Phramework\Validate\IntegerValidator;

/**
 * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @since  0.1.0
 * @author Xenofon Spafaridis <nohponex@gmail.com>
 */
class IntegerValidatorFiller implements IValidatorFiller
{
    /**
     * @param IntegerValidator $validator
     * @return int
     */
    public function fill(BaseValidator $validator)
    {
        $faker = \Faker\Factory::create();

        $minimum = $validator->minimum ?? PHP_INT_MIN;

        $maximum = $validator->maximum ?? PHP_INT_MAX;

        if ($validator->exclusiveMinimum) {
            $minimumRemainder = ($validator->minimum % $validator->multipleOf) ?: $validator->multipleOf;
            $minimum = $validator->minimum + $minimumRemainder;
        }

        if ($validator->exclusiveMaximum) {
            $maximumRemainder = ($validator->maximum % $validator->multipleOf) ?: $validator->multipleOf;
            $maximum = $validator->maximum - $maximumRemainder;
        }

        /*
         * generate an non exclusive number
         */
        $number = $faker->numberBetween(
            $minimum,
            $maximum
        );

        /*
         * Ensure multipleOf
         */
        $number = ((int) ($number / $validator->multipleOf)) * $validator->multipleOf;

        return $number;
    }
}

Improve integer filler to avoid random failures when using exclusive limits


<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        return Json::make($file->getRealPath())->toArray();
    }

}

<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        $attributes = Json::make($path = $file->getRealPath())->toArray();

        $attributes['path'] = dirname($path);

        return $attributes;
    }

}

Add path to theme attributes

Add path to theme attributes


<?php
namespace Tabster\Application;

use Tabster\Application\Auth\Auth;
use Tabster\Application\Config\ConfigCollection;
use Tabster\Application\Cookie\Cookie;
use Tabster\Application\Database\Database;
use Tabster\Application\Session\Session;
use Tabster\Models\Users;
use \AltoRouter as Router;

class Application {

    private $auth;
    private $acl;
    private $config;
    private $cookie;
    private $database;
    private $session;
    private $router;
    private $user;

    public function __construct(ConfigCollection $config) {
        $this->config = $config;
        $this->database = new Database($this->config->database);
        $this->session = new Session('TabsterSession');
        $this->cookie = new Cookie($this->config->cookie);
        $this->router = new Router($this->config->routes->getConfig());
        $this->auth = new Auth($this->database, $this->session, $this->cookie);
        $this->user = $this->auth->getCurrentUser();
        $this->acl = new Acl($this->database);

        $this->session->auth = [
            'id' => $this->user->id,
            'banned' => $this->user->banned,
            'suspended' => $this->user->suspended,
            'active' => $this->user->active,
            'role' => $this->user->role
        ];
    }

}

<?php
namespace Tabster\Application;

use Tabster\Application\Acl\Acl;
use Tabster\Application\Auth\Auth;
use Tabster\Application\Config\ConfigCollection;
use Tabster\Application\Cookie\Cookie;
use Tabster\Application\Database\Database;
use Tabster\Application\Session\Session;
use Tabster\Models\Users;
use \AltoRouter as Router;

class Application {

    private $auth;
    private $acl;
    private $config;
    private $cookie;
    private $database;
    private $session;
    private $router;
    private $user;

    public function __construct(ConfigCollection $config) {
        $this->config = $config;
        $this->database = new Database($this->config->database);
        $this->session = new Session('TabsterSession');
        $this->cookie = new Cookie($this->config->cookie);
        $this->router = new Router($this->config->routes->getConfig());
        $this->auth = new Auth($this->database, $this->session, $this->cookie);
        $this->user = $this->auth->getCurrentUser();
        $this->acl = new Acl($this->database);

        $this->session->auth = [
            'id' => $this->user->id,
            'banned' => $this->user->banned,
            'suspended' => $this->user->suspended,
            'active' => $this->user->active,
            'role' => $this->user->role
        ];
    }

}

Add right namespace for Acl

Add right namespace for Acl


<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use mcordingley\Regression\Helpers;

final class Identity extends Linking
{
    public function delinearize(float $value): float
    {
        return $value;
    }

    public function linearize(float $value): float
    {
        return $value;
    }

    public function loss(array $coefficients, array $observations, float $outcome, int $index): float
    {
        $sumProduct = Helpers::sumProduct($coefficients, $observations);
        $hypothesis = $this->delinearize($sumProduct);

        return -2 * ($outcome - $hypothesis) * $observations[$index];
    }
}

<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use mcordingley\Regression\Helpers;

final class Identity extends Linking
{
    public function delinearize(float $value): float
    {
        return $value;
    }

    public function linearize(float $value): float
    {
        return $value;
    }

    public function loss(array $coefficients, array $observations, float $outcome, int $index): float
    {
        return -2 * ($outcome - Helpers::sumProduct($coefficients, $observations)) * $observations[$index];
    }
}

Simplify and inline the identity loss function.


<?php

namespace Dara\Origins;

use PDO;
use Dotenv;

abstract class BaseModel
{

}

<?php

namespace Dara\Origins;

use PDO;
use Dotenv;

abstract class BaseModel
{

    public function __construct()
    {
        $this->loadEnv();
        $this->connection = new Connection($_ENV['P_DRIVER'], $_ENV['P_HOST'], $_ENV['P_DBNAME'], $_ENV['P_USER'], $_ENV['P_PASS']);
        $this->className = get_called_class();
    }

    /**
     * Load environment variables
     *
     * @return null
     */
    public function loadEnv()
    {
        $dotenv = new Dotenv\Dotenv(__DIR__.'/../..');
        $dotenv->load();
    }

    /**
     * Create an instance of the called model
     *
     * @return mixed
     */
    protected static function createModelInstance()
    {
        $model = get_called_class();
        return new $model();
    }

    /**
     * Return  all the rows from a table
     *
     * @return array
     */
    public static function getAll()
    {
        return self::doSearch()->resultRows;
    }

    /**
     * Choose to either search database for one row or all rows depending on whether the $id argument is passed
     *
     * @param int $id
     * @return mixed
     */
    protected static function doSearch($id = null)
    {
        $model = self::createModelInstance();
        $tableName = $model->getTableName($model->className);

        return $id ? self::selectOne($model, $tableName, $id) : self::selectAll($model, $tableName);
    }

    /**
     * Search database for all rows
     *
     * @param $model
     * @param $tableName
     * @return mixed
     */
    protected static function selectAll($model, $tableName)
    {
        $getAll = $model->connection->prepare('select * from '.$tableName);
        $getAll->execute();

        while ($allRows = $getAll->fetch(PDO::FETCH_ASSOC)) {
            array_push($model->resultRows, $allRows);
        }

        return $model;
    }

    /**
     * Search database for one row
     *
     * @param $model
     * @param $tableName
     * @param $id
     * @return mixed
     */
    protected static function selectOne($model, $tableName, $id)
    {
        $getAll = $model->connection->prepare('select * from '.$tableName.' where id='.$id);
        $getAll->execute();

        $row = $getAll->fetch(PDO::FETCH_ASSOC);
        array_push($model->resultRows, $row);

        return $model;
    }

}

Implement retrieval of all table rows

Implement retrieval of all table rows


<?php

namespace Zerg\Field;

use Zerg\Stream\AbstractStream;

/**
 * String represents string type data.
 *
 * Data, parsed by this type of field returns as it is in binary file.
 * @since 0.1
 * */
class String extends Scalar
{
    /**
     * @var bool Whether returned string should process like UTF-8 encoded.
     * */
    protected $utf;

    /**
     * Read string from stream as it is.
     *
     * @param AbstractStream $stream Stream from which read.
     * @return string Returned string.
     */
    public function read(AbstractStream $stream)
    {
        $string = $stream->getReader()
            ->setCurrentBit(0)
            ->readString($this->getSize());

        if ($this->utf) {

            if (strlen($string) < 2) {
                return '';
            }

            if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff ||
                ord($string[0]) == 0xff && ord($string[1]) == 0xfe) {
                $string = substr($string, 2);
            }

            return $string;

        }

        return $this->format($string);
    }
}

<?php

namespace Zerg\Field;

use Zerg\Stream\AbstractStream;

/**
 * String represents string type data.
 *
 * Data, parsed by this type of field returns as it is in binary file.
 * @since 0.1
 * */
class String extends Scalar
{
    /**
     * @var bool Whether returned string should process like UTF-8 encoded.
     * */
    protected $utf;

    /**
     * Read string from stream as it is.
     *
     * @param AbstractStream $stream Stream from which read.
     * @return string Returned string.
     */
    public function read(AbstractStream $stream)
    {
        $string = $stream->getReader()
            ->setCurrentBit(0)
            ->readString($this->getSize());

        if ($this->utf) {

            if (strlen($string) < 2) {
                return '';
            }

            if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff ||
                ord($string[0]) == 0xff && ord($string[1]) == 0xfe) {
                $string = substr($string, 2);
            }

            return $string;

        }

        return $string;
    }
}

Delete double formatting in string field


<?php
declare(strict_types=1);

namespace Lcobucci\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Definition of how the container builder should behave
 *
 * @author Luís Otávio Cobucci Oblonczyk <lcobucci@gmail.com>
 */
interface Builder
{
    /**
     * Changes the generator to handle the files
     */
    public function setGenerator(Generator $generator): Builder;

    /**
     * Add a file to be loaded
     */
    public function addFile(string $file): Builder;

    /**
     * Add a compiler pass
     */
    public function addPass(
        CompilerPassInterface $pass,
        string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION
    ): Builder;

    /**
     * Mark the container to be used as development mode
     */
    public function useDevelopmentMode(): Builder;

    /**
     * Configures the dump directory
     */
    public function setDumpDir(string $dir): Builder;

    /**
     * Adds a default parameter
     */
    public function setParameter(string $name, $value): Builder;

    /**
     * Adds a path to load the files
     */
    public function addPath(string $path): Builder;

    /**
     * Configures the container's base class
     */
    public function setBaseClass(string $class): Builder;

    /**
     * Creates the container with the given configuration
     */
    public function getContainer(): ContainerInterface;
}

<?php
declare(strict_types=1);

namespace Lcobucci\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Definition of how the container builder should behave
 *
 * @author Luís Otávio Cobucci Oblonczyk <lcobucci@gmail.com>
 */
interface Builder
{
    /**
     * Changes the generator to handle the files
     */
    public function setGenerator(Generator $generator): Builder;

    /**
     * Add a file to be loaded
     */
    public function addFile(string $file): Builder;

    /**
     * Add a compiler pass
     */
    public function addPass(
        CompilerPassInterface $pass,
        string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION
    ): Builder;

    /**
     * Mark the container to be used as development mode
     */
    public function useDevelopmentMode(): Builder;

    /**
     * Configures the dump directory
     */
    public function setDumpDir(string $dir): Builder;

    /**
     * Adds a default parameter
     */
    public function setParameter(string $name, $value): Builder;

    /**
     * Adds a path to load the files
     */
    public function addPath(string $path): Builder;

    /**
     * Configures the container's base class
     */
    public function setBaseClass(string $class): Builder;

    /**
     * Creates the container with the given configuration
     */
    public function getContainer(): ContainerInterface;

    /**
     * Creates a test container with the given configuration
     */
    public function getTestContainer(): ContainerInterface;
}

Add method to create a test container to interface

I've simply forgot that...


<?php

namespace App\Http\Controllers;

use App\User;
use Auth;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showProfile()
    {
        $controller = new AdminController();
        return $controller->editUser(Auth::user()->id);
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->intended('login');
    }
}

<?php

namespace App\Http\Controllers;

use Auth;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showProfile()
    {
        $controller = new AdminController();
        return $controller->editUser(Auth::user()->id);
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->intended('login');
    }
}

Remove unused Use statement from User controller


<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'urlManager' => [
            'baseUrl' => '/',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ],
        ],
    ],
    'bootstrap' => [
        [
            'class' => 'common\components\LanguageSelector',
            'supportedLanguages' => ['en_US', 'ru_RU'],
        ],
    ],
];

<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'urlManager' => [
            'baseUrl' => '/',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ],
        ],
    ]
];

Remove unused LanguageSelector from settings


<?php
namespace Psalm\Type\Atomic;

class TIterable extends \Psalm\Type\Atomic
{
    use HasIntersectionTrait;

    /**
     * @var string
     */
    public $value = 'iterable';

    public function __toString()
    {
        return 'iterable';
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return 'iterable';
    }

    /**
     * @return bool
     */
    public function canBeFullyExpressedInPhp()
    {
        return true;
    }

    /**
     * @param  string|null   $namespace
     * @param  array<string> $aliased_classes
     * @param  string|null   $this_class
     * @param  int           $php_major_version
     * @param  int           $php_minor_version
     *
     * @return string|null
     */
    public function toPhpString(
        $namespace,
        array $aliased_classes,
        $this_class,
        $php_major_version,
        $php_minor_version
    ) {
        return $php_major_version >= 7 && $php_minor_version >= 2 ? 'iterable' : null;
    }
}

<?php
namespace Psalm\Type\Atomic;

class TIterable extends \Psalm\Type\Atomic
{
    use HasIntersectionTrait;

    /**
     * @var string
     */
    public $value = 'iterable';

    public function __toString()
    {
        return 'iterable';
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return 'iterable';
    }

    /**
     * @return bool
     */
    public function canBeFullyExpressedInPhp()
    {
        return true;
    }

    /**
     * @param  string|null   $namespace
     * @param  array<string> $aliased_classes
     * @param  string|null   $this_class
     * @param  int           $php_major_version
     * @param  int           $php_minor_version
     *
     * @return string|null
     */
    public function toPhpString(
        $namespace,
        array $aliased_classes,
        $this_class,
        $php_major_version,
        $php_minor_version
    ) {
        return $php_major_version >= 7 && $php_minor_version >= 1 ? 'iterable' : null;
    }
}

Allow iterable to be output in PHP 7.1 too


<?php

/*
 * This file is part of Laravel Chartist.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Chartist.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Chartist;

use BrianFaust\ServiceProvider\ServiceProvider;

class ChartistServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot(): void
    {
        $this->publishViews();

        $this->loadViews();
    }

    /**
     * Register the application services.
     */
    public function register(): void
    {
        parent::register();

        $this->app->singleton('chartist', function ($app) {
            return new Builder();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return array_merge(parent::provides(), ['chartist']);
    }

    /**
     * Get the default package name.
     *
     * @return string
     */
    public function getPackageName(): string
    {
        return 'chartist';
    }
}

<?php

/*
 * This file is part of Laravel Chartist.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Chartist.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Chartist;

use BrianFaust\ServiceProvider\AbstractServiceProvider;

class ChartistServiceProvider extends AbstractServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot(): void
    {
        $this->publishViews();

        $this->loadViews();
    }

    /**
     * Register the application services.
     */
    public function register(): void
    {
        parent::register();

        $this->app->singleton('chartist', function ($app) {
            return new Builder();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return array_merge(parent::provides(), ['chartist']);
    }

    /**
     * Get the default package name.
     *
     * @return string
     */
    public function getPackageName(): string
    {
        return 'chartist';
    }
}

Fix extending service provider name

Fix extending service provider name


<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

use Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UpdateFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email', array(
                'description' => 'Email address. Must be unique.',
                'required' => true,
            ))
            ->add('title', 'text', array(
                'description' => 'Salutation.',
                'required' => true,
            ))
            ->add('firstNames', 'text', array(
                'description' => 'First name(s).',
                'required' => true,
            ))
            ->add('middleNames', 'text', array(
                'description' => 'Middle name(s).',
                'required' => false,
            ))
            ->add('lastNames', 'text', array(
                'description' => 'Last name.',
                'required' => true,
            ))
            ->add('dob', 'text', array(
                'widget' => 'single_text',
                'description' => 'Date of birth.',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_update'),
        ));
    }

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

<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

use Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UpdateFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email', array(
                'description' => 'Email address. Must be unique.',
                'required' => true,
            ))
            ->add('title', 'text', array(
                'description' => 'Salutation.',
                'required' => true,
            ))
            ->add('firstNames', 'text', array(
                'description' => 'First name(s).',
                'required' => true,
            ))
            ->add('middleNames', 'text', array(
                'description' => 'Middle name(s).',
                'required' => false,
            ))
            ->add('lastNames', 'text', array(
                'description' => 'Last name.',
                'required' => true,
            ))
            ->add('dob', 'birthday', array(
                'widget' => 'single_text',
                'description' => 'Date of birth.',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_update'),
        ));
    }

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

Add DOB field to User entity (JANUS-40) * Fix DOB form definition.


<?php

Object::add_extension('ContentController', 'MenuControllerExtension');

<?php

if (class_exists('ContentController')) {
    Object::add_extension('ContentController', 'MenuControllerExtension');
}

BUGFIX: Fix issue where content controller is not defined


<?php

namespace FireDIY\PrivateMessageBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ConversationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('subject')
            ->add('firstMessage', PrivateMessageType::class)
            ->add('save', SubmitType::class, array('label' => 'Send'))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'firediy_privatemessagebundle_conversation';
    }

}

<?php

namespace FireDIY\PrivateMessageBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ConversationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('subject')
            ->add('firstMessage', PrivateMessageType::class)
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'firediy_privatemessagebundle_conversation';
    }

}

Remove submit button from form class

Remove submit button from form class


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Spark\Spark;

class File extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'file';
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Spark\Spark;

class File extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'files';
}

Correct the name of the table from file to files


<?php

class Userbin_SessionSerializer
{
  public function destroy()
  {
    unset($_SESSION['userbin']);
  }

  public function read()
  {
    if (array_key_exists('userbin', $_SESSION)) {
      return $_SESSION['userbin'];
    }
    return null;
  }

  public function write($value)
  {
    $_SESSION['userbin'] = $value;
  }
}

<?php

class Userbin_SessionSerializer
{
  public function destroy()
  {
    unset($_SESSION['userbin']);
  }

  public function read()
  {
    if (isset($_SESSION) && array_key_exists('userbin', $_SESSION)) {
      return $_SESSION['userbin'];
    }
    return null;
  }

  public function write($value)
  {
    if ($_SESSION) {
      $_SESSION['userbin'] = $value;
    }
  }
}

Check for global in session serializer

Check for global in session serializer


<?php
/**
 * Generic instruction for the callback setup
 * @author: budiartoa
 * @license http://www.opensource.org/licenses/BSD-3-Clause
 */
?>

	Make it static alse features some enhancements to the editor

			Ability to inject raw html codes such as scripts Use with caution

			Putting any code between shortcode [static_code] [/static_code] will cause the section to be saved unescaped hence custom css and js are possible

		[TOC]

		Putting this string [TOC] anywhere in the editor when authoring a page will replace the contents of the generated static files with the table of contents of items below the current page

Add some [TOC] string descriptions

Add some [TOC] string descriptions


<?php
namespace Craft;

class CryptographerPlugin extends BasePlugin
{
    function getName()
    {
        return Craft::t('Cryptographer');
    }

    function getVersion()
    {
        return '0.1';
    }

    function getDeveloper()
    {
        return 'Miranj';
    }

    function getDeveloperUrl()
    {
        return 'http://miranj.in';
    }

    protected function defineSettings()
    {
        return array(
            'secret'    => array(AttributeType::String, 'default' => md5(rand())),
        );
    }

    public function getSettingsHtml()
    {
        return craft()->templates->render('cryptographer/_settings', array(
            'settings' => $this->getSettings(),
        ));
    }

    public function addTwigExtension()
    {
        Craft::import('plugins.cryptographer.twigextensions.CryptographerTwigExtension');
        return new CryptographerTwigExtension();
    }
}

<?php
namespace Craft;

class CryptographerPlugin extends BasePlugin
{
    function getName()
    {
        return Craft::t('Cryptographer');
    }

    function getVersion()
    {
        return '0.1';
    }

    function getDeveloper()
    {
        return 'Miranj';
    }

    function getDeveloperUrl()
    {
        return 'http://miranj.in';
    }

    protected function defineSettings()
    {
        return array(
            'secret'    => array(AttributeType::String, 'default' => md5(rand())),
        );
    }

    public function getSettingsHtml()
    {
        return craft()->templates->render('cryptographer/_settings', array(
            'settings' => $this->getSettings(),
        ));
    }

    public function onAfterInstall()
    {
        // Save plugin settings immediately after install
        craft()->plugins->savePluginSettings($this, $this->getSettings());
    }

    public function addTwigExtension()
    {
        Craft::import('plugins.cryptographer.twigextensions.CryptographerTwigExtension');
        return new CryptographerTwigExtension();
    }
}

Save settings immediately after installation.


<?php

namespace Djebbz\TicketBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('DjebbzTicketBundle:Default:index.html.twig', array('name' => $name));
    }
}

<?php

namespace Djebbz\TicketBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('DjebbzTicketBundle:Default:index.html.twig', array('content' => 'Test content'));
    }
}

Fix controller that doesn't have a `name` param in path


<?php

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

namespace Sylius\Bundle\UserBundle\Context;

use Sylius\Component\User\Context\CustomerContextInterface;
use Sylius\Component\User\Model\CustomerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;

/**
 * @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
 */
class CustomerContext implements CustomerContextInterface
{
    /**
     * @var SecurityContextInterface
     */
    private $securityContext;

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

    /**
     * Gets customer based on currently logged user.
     *
     * @return CustomerInterface|null
     */
    public function getCustomer()
    {
        if ($this->securityContext->getToken() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
            && $this->securityContext->getToken()->getUser()
        ) {
            return $this->securityContext->getToken()->getUser()->getCustomer();
        }

        return null;
    }
}

<?php

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

namespace Sylius\Bundle\UserBundle\Context;

use Sylius\Component\User\Context\CustomerContextInterface;
use Sylius\Component\User\Model\CustomerInterface;
use Sylius\Component\User\Model\UserInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;

/**
 * @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
 */
class CustomerContext implements CustomerContextInterface
{
    /**
     * @var SecurityContextInterface
     */
    private $securityContext;

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

    /**
     * Gets customer based on currently logged user.
     *
     * @return CustomerInterface|null
     */
    public function getCustomer()
    {
        if ($this->securityContext->getToken() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
            && $this->securityContext->getToken()->getUser() instanceof UserInterface
        ) {
            return $this->securityContext->getToken()->getUser()->getCustomer();
        }

        return null;
    }
}

Add check to customer context

Add check to customer context

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Fixed tickets |
| License       | MIT
| Doc PR        |

In one part of our site we don't need sylius autentication, just basic http with a generic username and password (which by default uses a Symfony user), so the Customer context fails when calling `->getCustomer()`.
Adding this check allows us to use basic http autentication.


<?php

namespace UghAuthentication\Authentication\Adapter;

use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Result;

abstract class Adapter implements AdapterInterface
{

    /** @var AdapterInterface */
    private $successor;

    /**
     *
     * @return Result
     */
    public function authenticate()
    {
        $result = $this->doAuthentication();

        if (!$result->isValid()) {
            return $this->successor->authenticate();
        }

        return $result;
    }

    /**
     *
     * @param AdapterInterface $successor
     */
    public function setSuccessor(AdapterInterface $successor)
    {
        $this->successor = $successor;
    }

    /**
     * @return Result
     */
    abstract protected function doAuthentication();
}

<?php

namespace UghAuthentication\Authentication\Adapter;

use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Result;

abstract class Adapter implements AdapterInterface
{

    /** @var AdapterInterface */
    private $successor;

    /**
     *
     * @return Result
     */
    public function authenticate()
    {
        $result = $this->doAuthentication();

        if (!$result->isValid() && !is_null($this->successor)) {
            return $this->successor->authenticate();
        }

        return $result;
    }

    /**
     *
     * @param AdapterInterface $successor
     */
    public function setSuccessor(AdapterInterface $successor)
    {
        $this->successor = $successor;
    }

    /**
     * @return Result
     */
    abstract protected function doAuthentication();
}

Add scenario where successor is null

Add scenario where successor is null


<?php namespace Nwidart\MoneyFormatter\Tests;

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

<?php namespace Nwidart\MoneyFormatter\Tests;

use Money\Currency;
use Money\Money;
use Nwidart\MoneyFormatter\MoneyFormatter;

class MoneyFormatterTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function should_format_as_english_pounds()
    {
        $formatter = new MoneyFormatter('en_GB');
        $this->assertEquals('£10.00', $formatter->format(new Money(1000, new Currency('GBP'))));
    }

    /** @test */
    public function should_format_as_american_dollars()
    {
        $formatter = new MoneyFormatter('en_US');
        $this->assertEquals('$10.00', $formatter->format(new Money(1000, new Currency('USD'))));
    }

    public function should_format_as_european_euros()
    {
        $formatter = new MoneyFormatter('fr_BE');
        $this->assertEquals('10,00 €', $formatter->format(new Money(1000, new Currency('EUR'))));
    }
}

Add basic tests for the formatting

Add basic tests for the formatting


<?php

namespace Lexik\Bundle\PayboxBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class LexikPayboxExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter('lexik_paybox.servers', $config['servers']);
        $container->setParameter('lexik_paybox.parameters', $config['parameters']);
        $container->setParameter('lexik_paybox.transport.class', $config['transport']);

        if (null === $config['parameters']['public_key']) {
            $config['parameters']['public_key'] = __DIR__ . '/../Resources/config/paybox_public_key.pem';
        }

        $container->setParameter('lexik_paybox.public_key', $config['parameters']['public_key']);
    }
}

<?php

namespace Lexik\Bundle\PayboxBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class LexikPayboxExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        if (null === $config['parameters']['public_key']) {
            $config['parameters']['public_key'] = __DIR__ . '/../Resources/config/paybox_public_key.pem';
        }

        $container->setParameter('lexik_paybox.servers', $config['servers']);
        $container->setParameter('lexik_paybox.parameters', $config['parameters']);
        $container->setParameter('lexik_paybox.transport.class', $config['transport']);
        $container->setParameter('lexik_paybox.public_key', $config['parameters']['public_key']);
    }
}

Fix public_key default value in lexik_paybox.parameters parameter

The parameter lexik_paybox.public_key seems to never been used in services, default value is now defined before parameter registration for parameter lexik_paybox.parameters


<?php namespace SimpleSoftwareIO\QrCode;

/**
 * Simple Laravel QrCode Generator
 * A simple wrapper for the popular BaconQrCode made for Laravel.
 *
 * @link http://www.simplesoftware.io
 * @author SimpleSoftware support@simplesoftware.io
 *
 */

use Illuminate\Support\ServiceProvider;

class QrCodeServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('simplesoftwareio/simple-qrcode');
    }

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app->bindShared('qrcode', function()
        {
            return new BaconQrCodeGenerator;
        });
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('qrcode');
	}

}

<?php namespace SimpleSoftwareIO\QrCode;

/**
 * Simple Laravel QrCode Generator
 * A simple wrapper for the popular BaconQrCode made for Laravel.
 *
 * @link http://www.simplesoftware.io
 * @author SimpleSoftware support@simplesoftware.io
 *
 */

use Illuminate\Support\ServiceProvider;

class QrCodeServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app->bindShared('qrcode', function()
        {
            return new BaconQrCodeGenerator;
        });
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('qrcode');
	}

}

Remove uneeded boot to make compatible with Laravel 5

Removing this because this package does not use any resources and thus
is not needed for Laravel 4.


<?php

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

class CreateProjectsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('stage')->nullable();
            $table->integer('server_id')->unsigned();
            $table->string('repository');
            $table->string('email_notification_recipient')->nullable();
            $table->text('attributes');
            $table->integer('days_to_keep_deployments')->unsigned()->nullable();
            $table->integer('max_number_of_deployments_to_keep')->unsigned()->nullable();
            $table->tinyInteger('keep_last_deployment')->unsigned();
            $table->string('github_webhook_secret')->nullable();
            $table->integer('github_webhook_user_id')->unsigned()->nullable();
            $table->timestamps();

            $table->foreign('server_id')
                ->references('id')
                ->on('servers');
            $table->foreign('github_webhook_user_id')
                ->references('id')
                ->on('users');
        });
    }

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

<?php

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

class CreateProjectsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('stage')->nullable();
            $table->integer('server_id')->unsigned();
            $table->string('repository');
            $table->string('email_notification_recipient')->nullable();
            $table->text('attributes');
            $table->integer('days_to_keep_deployments')->unsigned()->nullable();
            $table->integer('max_number_of_deployments_to_keep')->unsigned()->nullable();
            $table->tinyInteger('keep_last_deployment')->unsigned();
            $table->string('github_webhook_secret')->nullable();
            $table->integer('github_webhook_user_id')->unsigned()->nullable();
            $table->timestamps();

            $table->foreign('server_id')
                ->references('id')
                ->on('servers');
            $table->foreign('github_webhook_user_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
        });
    }

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

Fix an error when deleting a GitHub webhook user


<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

/**
 * User "/echo" command
 */
class EchoCommand extends UserCommand
{
    /**#@+
     * {@inheritdoc}
     */
    protected $name = 'echo';
    protected $description = 'Show text';
    protected $usage = '/echo <text>';
    protected $version = '1.0.1';
    /**#@-*/

    /**
     * Execute command
     *
     * @return boolean
     */
    public function execute()
    {
        $message = $this->getMessage();
        $chat_id = $message->getChat()->getId();
        $text = $message->getText(true);

        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
        ];

        return Request::sendMessage($data)->isOk();
    }
}

<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

/**
 * User "/echo" command
 */
class EchoCommand extends UserCommand
{
    /**#@+
     * {@inheritdoc}
     */
    protected $name = 'echo';
    protected $description = 'Show text';
    protected $usage = '/echo <text>';
    protected $version = '1.0.1';
    /**#@-*/

    /**
     * Execute command
     *
     * @return boolean
     */
    public function execute()
    {
        $message = $this->getMessage();
        $chat_id = $message->getChat()->getId();
        $text = trim($message->getText(true));

        if ($text === '') {
            $text = 'Command usage: ' . $this->getUsage();
        }

        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
        ];

        return Request::sendMessage($data)->isOk();
    }
}

Add error message to /echo command if no input.


<?php

/*
 * Detail class file
 */
namespace Moneybird\Invoice;

use Moneybird\Detail\AbstractDetail;

/**
 * Detail
 */
class Detail extends AbstractDetail
{

    protected $invoiceId;

    /**
     * Copy the invoice detail
     * @param array $filter
     * @return self
     */
    public function copy(array $filter = array())
    {
        return parent::copy(array(
                'invoiceId',
            ));
    }
}

<?php

/*
 * Detail class file
 */
namespace Moneybird\Invoice;

use Moneybird\Detail\AbstractDetail;

/**
 * Detail
 */
class Detail extends AbstractDetail
{

    protected $invoiceId;

    /**
     * Copy the invoice detail
     * @param array $filter
     * @return self
     */
    public function copy(array $filter = array())
    {
        return parent::copy(array(
                'invoiceId',
            ));
    }

    /**
     * Extract will take an array and try to automatically map the array values
     * to properties in this object
     *
     * @param Array $values
     * @param Array $filter
     * @param bool $isDirty new data is dirty, defaults to true
     * @access protected
     */
    protected function extract(Array $values, $filter = array(), $isDirty = true)
    {
        $product = &$values['product'];
        if (isset($product) && $product instanceof Product) {
            $filter[] = 'product';
            $values = array_merge($values, array(
                'description' => $product->description,
                'ledgerAccountId' => $product->ledgerAccountId,
                'price' => $product->price,
                'taxRateId' => $product->taxRateId,
            ));
        }
        return parent::extract($values, $filter, $isDirty);
    }
}

Add product to detail line

Add product to detail line


<?php

namespace HCLabs\ModelManagerBundle\Pool;

use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;

class ModelManagerPool
{
    /** @var ModelManagerInterface[] */
    protected $managers = [];

    /**
     * Add a model manager to the pool
     *
     * @param ModelManagerInterface $manager
     */
    public function addManager(ModelManagerInterface $manager)
    {
        $this->managers[] = $manager;
    }

    /**
     * Get manager for an entity out of the pool
     *
     * @param ModelInterface $model
     * @return ModelManagerInterface
     * @throws \HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException
     */
    public function getManager(ModelInterface $model)
    {
        foreach ($this->managers as $manager) {
            if ($manager->supports($model)) {
                return $manager;
            }
        }

        throw new ModelManagerNotFoundException($model);
    }
}

<?php

namespace HCLabs\ModelManagerBundle\Pool;

use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;

class ModelManagerPool
{
    /** @var ModelManagerInterface[] */
    protected $managers = [];

    /**
     * Add a model manager to the pool
     *
     * @param ModelManagerInterface $manager
     */
    public function addManager(ModelManagerInterface $manager)
    {
        $this->managers[] = $manager;
    }

    /**
     * Get manager for an entity out of the pool
     *
     * @param ModelInterface|string $model
     * @return ModelManagerInterface
     * @throws \HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException
     * @throws \RuntimeException
     */
    public function getManager($model)
    {
        if (!is_string($model) && !$model instanceof ModelInterface) {
            throw new \RuntimeException(sprintf('Model provided (\'%s\') is neither a string nor an instance of ModelInterface', $model));
        }

        foreach ($this->managers as $manager) {
            if ($manager->supports($model)) {
                return $manager;
            }
        }

        throw new ModelManagerNotFoundException($model);
    }
}

[Pool] Allow retrieval of a model manager with only a class name rather than a class instance


<?php

namespace App\Http\Controllers;

use App\DuesTransaction;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    /**
     * Returns view with data for the user dashboard
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $needsPayment = $user->needsPayment;
        $transactions = DuesTransaction::where('user_id', $user->id)
            ->whereHas('package', function ($q) {
                $q->whereDate('effective_start', '<=', date('Y-m-d'))
                    ->whereDate('effective_end', '>=', date('Y-m-d'));
            })->get();
        $needsTransaction = (count($transactions) == 0);
        $data = ['needsTransaction' => $needsTransaction, 'needsPayment' => $needsPayment];
        return view('welcome', $data);
    }
}

<?php

namespace App\Http\Controllers;

use App\DuesTransaction;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    /**
     * Returns view with data for the user dashboard
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        //User needs a transaction if they don't have one for an active dues package
        $user = $request->user();
        $transactionsQuery = DuesTransaction::where('user_id', $user->id)
            ->whereHas('package', function ($q) {
                $q->whereDate('effective_start', '<=', date('Y-m-d'))
                    ->whereDate('effective_end', '>=', date('Y-m-d'));
            });
        $needsTransaction = (count($transactionsQuery->get()) == 0);

        /* User needs a payment if they either:
         * (1) Have a DuesTransaction for an active DuesPackage with payment less than payable amount, OR
         * (2) Have a DuesTransaction for an active DuesPackage without any payment attempts
         */
        //Get transactions with payments
        $txnWithPayment = $transactionsQuery->whereHas('payment')->get();
        if (count($txnWithPayment) > 0) {
            //Compare sum of payments for last transaction to package payable amount
            $paidSum = $txnWithPayment->last()->payment->sum('amount');
            $needsPayment = ($paidSum < $txnWithPayment->last()->getPayableAmount());
        } elseif ($needsTransaction == false && count($txnWithPayment) == 0) {
            //Transaction already exists, but no payment attempts have been made
            $needsPayment = true;
        } else {
            //Transaction already exists, full amount has been paid
            //I don't think we'll ever make it to this part of the conditional
            $needsPayment = false;
        }

        $data = ['needsTransaction' => $needsTransaction, 'needsPayment' => $needsPayment];
        return view('welcome', $data);
    }
}

Put payment logic here instead of in the user model; Allow for multiple payments instead of a single payment