<?php
namespace DreadLabs\VantomasWebsite\Page;

use DreadLabs\VantomasWebsite\Archive\SearchInterface;
use DreadLabs\VantomasWebsite\RssFeed\ConfigurationInterface as RssFeedConfigurationInterface;
use DreadLabs\VantomasWebsite\Sitemap\ConfigurationInterface as SitemapConfiguration;
use DreadLabs\VantomasWebsite\Taxonomy\TagSearchInterface;

interface PageRepositoryInterface {

	/**
	 * Searches for archived (page) nodes by given criteria
	 *
	 * @param SearchInterface $search
	 * @return Page[]
	 */
	public function findArchived(SearchInterface $search);

	/**
	 * Finds last updated pages within $parentPageId
	 *
	 * @param PageId $parentPageId
	 * @param int $offset
	 * @param int $limit
	 * @return Page[]
	 */
	public function findLastUpdated(PageId $parentPageId, $offset = 0, $limit = 1);

	/**
	 * Finds all pages with tags
	 *
	 * @return Page[]
	 */
	public function findAllWithTags();

	/**
	 * @param TagSearchInterface $tagSearch
	 * @return Page[]
	 */
	public function findAllByTag(TagSearchInterface $tagSearch);

	/**
	 * @param SitemapConfiguration $configuration
	 * @return Page[]
	 */
	public function findForSitemapXml(SitemapConfiguration $configuration);

	/**
	 * @param RssFeedConfigurationInterface $configuration
	 * @return Page[]
	 */
	public function findAllForRssFeed(RssFeedConfigurationInterface $configuration);
}

<?php
namespace DreadLabs\VantomasWebsite\Page;

use DreadLabs\VantomasWebsite\Archive\SearchInterface;
use DreadLabs\VantomasWebsite\RssFeed\ConfigurationInterface as RssFeedConfigurationInterface;
use DreadLabs\VantomasWebsite\Sitemap\ConfigurationInterface as SitemapConfiguration;
use DreadLabs\VantomasWebsite\Taxonomy\TagSearchInterface;

interface PageRepositoryInterface {

	/**
	 * Searches for archived (page) nodes by given criteria
	 *
	 * @param SearchInterface $search
	 * @return Page[]
	 */
	public function findArchived(SearchInterface $search);

	/**
	 * Finds last updated pages of type $pageType
	 *
	 * @param PageType $pageType
	 * @param int $offset
	 * @param int $limit
	 * @return Page[]
	 */
	public function findLastUpdated(PageType $pageType, $offset = 0, $limit = 1);

	/**
	 * Finds all pages with tags
	 *
	 * @return Page[]
	 */
	public function findAllWithTags();

	/**
	 * @param TagSearchInterface $tagSearch
	 * @return Page[]
	 */
	public function findAllByTag(TagSearchInterface $tagSearch);

	/**
	 * @param SitemapConfiguration $configuration
	 * @return Page[]
	 */
	public function findForSitemapXml(SitemapConfiguration $configuration);

	/**
	 * @param RssFeedConfigurationInterface $configuration
	 * @return Page[]
	 */
	public function findAllForRssFeed(RssFeedConfigurationInterface $configuration);
}

[TASK] Switch lastUpdated pages rendering to PageType usage


<?php

namespace Junaidnasir\Larainvite;

trait InviteTrait
{
    /**
     * return all invitation as laravel collection
     * @return hasMany invitation Models
     */
    public function invitations()
    {
        return $this->hasMany('Junaidnasir\Larainvite\Models\LaraInviteModel');
    }

    /**
     * return successful initation by a user
     * @return hasMany
     */
    public function invitationSuccess()
    {
        return $this->invitations()->where('status', 'successful');
    }
    /**
     * return pending invitations by a user
     * @return hasMany
     */
    public function invitationPending()
    {
        return $this->invitations()->where('status', 'pending');
    }
}

<?php

namespace Junaidnasir\Larainvite;

trait InviteTrait
{
    /**
     * return all invitation as laravel collection
     * @return hasMany invitation Models
     */
    public function invitations()
    {
        return $this->hasMany(config('larainvite.InvitationModel'));
    }

    /**
     * return successful initation by a user
     * @return hasMany
     */
    public function invitationSuccess()
    {
        return $this->invitations()->where('status', 'successful');
    }
    /**
     * return pending invitations by a user
     * @return hasMany
     */
    public function invitationPending()
    {
        return $this->invitations()->where('status', 'pending');
    }
}

Correct the model in the trait

Correct the model in the trait


<?php
# $Id$
#
# read and evaluate the configuration file
#
include_once "./conf.php";

# These are settings derived from the configuration settings, and
# should not be modified.  This file will be overwritten on package upgrades,
# while changes made in conf.php should be preserved

$rrd_options = "";
if( isset( $rrdcached_socket ) )
{
    if(!empty( $rrdcached_socket ) )
    {
        $rrd_options .= " --daemon $rrdcached_socket";
    }
}

?>

<?php
# $Id$
#
# read and evaluate the configuration file
#
if ( file_exists("./conf.php") ) {
   include_once "./conf.php";
} else {
   $docroot = getcwd();
   print "<H4>$docroot/conf.php does not exist, did you forget to run 'make -C web install' in the ganglia source directory?</H4>\n";
   exit;
}

# These are settings derived from the configuration settings, and
# should not be modified.  This file will be overwritten on package upgrades,
# while changes made in conf.php should be preserved

$rrd_options = "";
if( isset( $rrdcached_socket ) )
{
    if(!empty( $rrdcached_socket ) )
    {
        $rrd_options .= " --daemon $rrdcached_socket";
    }
}

?>

[web] Add code to check if conf.php exists, if not, then an error message is displayed

git-svn-id: 27e0aca8c7a52a9ae65dfba2e16879604119af8c@2318 93a4e39c-3214-0410-bb16-828d8e3bcd0f


<?php namespace Laravel\Database\Eloquent;

class Pivot extends Model {

	/**
	 * The name of the pivot table's table.
	 *
	 * @var string
	 */
	public $pivot_table;

	/**
	 * Indicates if the model has update and creation timestamps.
	 *
	 * @var bool
	 */
	public static $timestamps = true;

	/**
	 * Create a new pivot table instance.
	 *
	 * @param  string  $table
	 * @param  string  $connection
	 * @return void
	 */
	public function __construct($table, $connection = null)
	{
		$this->pivot_table = $table;
		static::$connection = $connection;

		parent::__construct(array(), true);
	}

	/**
	 * Get the name of the pivot table.
	 *
	 * @return string
	 */
	public function table()
	{
		return $this->pivot_table;
	}

}

<?php namespace Laravel\Database\Eloquent;

class Pivot extends Model {

	/**
	 * The name of the pivot table's table.
	 *
	 * @var string
	 */
	protected $pivot_table;

	/**
	 * The database connection used for this model.
	 *
	 * @var Laravel\Database\Connection
	 */
	protected $pivot_connection;

	/**
	 * Indicates if the model has update and creation timestamps.
	 *
	 * @var bool
	 */
	public static $timestamps = true;

	/**
	 * Create a new pivot table instance.
	 *
	 * @param  string  $table
	 * @param  string  $connection
	 * @return void
	 */
	public function __construct($table, $connection = null)
	{
		$this->pivot_table = $table;
		$this->pivot_connection = $connection;

		parent::__construct(array(), true);
	}

	/**
	 * Get the name of the pivot table.
	 *
	 * @return string
	 */
	public function table()
	{
		return $this->pivot_table;
	}

	/**
	 * Get the connection used by the pivot table.
	 *
	 * @return string
	 */
	public function connection()
	{
		return $this->pivot_connection;
	}

}

Fix Pivot table losing its connection.

Fix Pivot table losing its connection.

This hopefully fixes #1198 and while it doesn't solve the underlying problem mentioned in #1429, it does the tackle the resulting mess. :)


<?php
error_reporting(E_ALL);
if (! defined('DS')) {
	define('DS', DIRECTORY_SEPARATOR);
	define('ROOT', __DIR__ . \DS . '..' . \DS . 'app' . \DS);
}
$config = include ROOT . 'config/config.php';
$sConfig = include __DIR__ . \DS . 'config.php';
$config["siteUrl"] = 'http://' . $sConfig['host'] . ':' . $sConfig['port'] . '/';
$config['sessionName'] = $sConfig['sessionName'];
require ROOT . './../vendor/autoload.php';
$config['debug'] = true;
if (class_exists("\\Monolog\\Logger")) {
	$config['logger'] = function () use ($sConfig) {
		return new \Ubiquity\log\libraries\UMonolog($sConfig['sessionName'], \Monolog\Logger::INFO);
	};
	\Ubiquity\log\Logger::init($config);
}

require ROOT . 'config/services.php';

if (Ubiquity\devtools\debug\Debug::hasLiveReload()) {
	echo Ubiquity\devtools\debug\Debug::liveReload();
}
\Ubiquity\controllers\Startup::run($config);

<?php
error_reporting(E_ALL);
if (! defined('DS')) {
	define('DS', DIRECTORY_SEPARATOR);
	define('ROOT', __DIR__ . \DS . '..' . \DS . 'app' . \DS);
}
$config = include ROOT . 'config/config.php';
$sConfig = include __DIR__ . \DS . 'config.php';
$config["siteUrl"] = 'http://' . $sConfig['host'] . ':' . $sConfig['port'] . '/';
$config['sessionName'] = $sConfig['sessionName'];
require ROOT . './../vendor/autoload.php';
$config['debug'] = true;
if (class_exists("\\Monolog\\Logger")) {
	$config['logger'] = function () use ($sConfig) {
		return new \Ubiquity\log\libraries\UMonolog($sConfig['sessionName'], \Monolog\Logger::INFO);
	};
	\Ubiquity\log\Logger::init($config);
}

require ROOT . 'config/services.php';

if (\Ubiquity\debug\Debug::hasLiveReload()) {
	echo \Ubiquity\debug\Debug::liveReload();
}
\Ubiquity\controllers\Startup::run($config);

Update index for Debug class location

Update index for Debug class location


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

use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Vendor\ComposerPackageReader;
use Jivoo\Vendor\VendorLoader;
use Jivoo\Vendor\VendorCommand;

/**
 * Initializes the third-party library loading system.
 */
class VendorUnit extends UnitBase {
  /**
   * {@inheritdoc}
   */
  public function run(App $app, Document $config) {
    $app->m->vendor = new VendorLoader($app);
    $vendor = $this->p('app/../vendor');
    if (is_dir($vendor))
      $app->m->vendor->addPath($vendor, new ComposerPackageReader());
    $vendor = $this->p('share/vendor');
    if (is_dir($vendor))
      $app->m->vendor->addPath($vendor, new ComposerPackageReader());

    $app->m->addProperty('vendor', $app->m->vendor);

    $this->m->lazy('shell')->addCommand('vendor', new VendorCommand($app));
  }
}

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

use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Vendor\ComposerPackageReader;
use Jivoo\Vendor\VendorLoader;
use Jivoo\Vendor\VendorCommand;
use Jivoo\Vendor\VendorInstaller;
use Jivoo\Vendor\LocalRepository;

/**
 * Initializes the third-party library loading system.
 */
class VendorUnit extends UnitBase {
  /**
   * {@inheritdoc}
   */
  public function run(App $app, Document $config) {
    $app->m->vendor = new VendorLoader($app);
    $vendor = $this->p('app/../vendor');
    if (is_dir($vendor))
      $app->m->vendor->addPath($vendor, new ComposerPackageReader());
    $vendor = $this->p('share/vendor');
    if (is_dir($vendor))
      $app->m->vendor->addPath($vendor, new ComposerPackageReader());

    $app->m->addProperty('vendor', $app->m->vendor);

    $app->m->vendorInstaller = new VendorInstaller($app);
    $app->m->vendorInstaller->addRepository('share', new LocalRepository($this->app, $this->p('share/vendor')));

    $this->m->lazy('shell')->addCommand('vendor', new VendorCommand($app));
  }
}

Move repo code to vendor installer.

Move repo code to vendor installer.


<?php
class Person
{
    protected $name;

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

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

<?php
class Person
{
    protected $name;

    public function __construct($name)
    {
        if (empty($name))
        {
            $name = '';
        }

        $this->name = $name;
    }

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

Introduce brace break for __construct

Introduce brace break for __construct


<?php

namespace test\Widmogrod\Primitive;

use Widmogrod\FantasyLand\Monoid;
use Widmogrod\Helpful\MonoidLaws;
use Widmogrod\Primitive\Stringg;
use Widmogrod\Functional as f;

class StringgTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @dataProvider provideRandomizedData
     */
    public function test_it_should_obey_monoid_laws(Monoid $x, Monoid $y, Monoid $z)
    {
        MonoidLaws::test(
            f\curryN(3, [$this, 'assertEquals']),
            $x,
            $y,
            $z
        );
    }

    private function randomize()
    {
        return Stringg::of(md5(random_int(0, 100)));
    }

    public function provideRandomizedData()
    {
        return array_map(function () {
            return [
                $this->randomize(),
                $this->randomize(),
                $this->randomize(),
            ];
        }, array_fill(0, 50, null));
    }
}

<?php

namespace test\Widmogrod\Primitive;

use Widmogrod\FantasyLand\Monoid;
use Widmogrod\Functional as f;
use Widmogrod\Helpful\MonoidLaws;
use Widmogrod\Primitive\Product;
use Widmogrod\Primitive\Stringg;

class StringgTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @dataProvider provideRandomizedData
     */
    public function test_it_should_obey_monoid_laws(Monoid $x, Monoid $y, Monoid $z)
    {
        MonoidLaws::test(
            f\curryN(3, [$this, 'assertEquals']),
            $x,
            $y,
            $z
        );
    }

    /**
     * @expectedException \Widmogrod\Primitive\TypeMismatchError
     * @expectedExceptionMessage Expected type is Widmogrod\Primitive\Stringg but given Widmogrod\Primitive\Product
     * @dataProvider provideRandomizedData
     */
    public function test_it_should_reject_concat_on_different_type(Stringg $a)
    {
        $a->concat(Product::of(1));
    }

    private function randomize()
    {
        return Stringg::of(md5(random_int(0, 100)));
    }

    public function provideRandomizedData()
    {
        return array_map(function () {
            return [
                $this->randomize(),
                $this->randomize(),
                $this->randomize(),
            ];
        }, array_fill(0, 50, null));
    }
}

Improve code coverage for String

Improve code coverage for String


<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model {

	//

}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model {

	protected $fillable = [
		'body',
		'type',
		'topic_id',
		'reply_id',
		'user_id',
		'from_user_id',
	];

	public function user()
	{
		return $this->belongsTo('User');
	}

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

	public function fromUser()
	{
		return $this->belongsTo('User', 'from_user_id');
	}

}

Set the relationships for the notification model.


<?php

abstract class LoaderFile extends Loader{
    protected $fileName;

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

    protected function getLines(){
        $ret = file($this->fileName, FILE_IGNORE_NEW_LINES);
        if($ret === false){
            throw new Exception('Unable to read file');
        }
        return $ret;
    }
}

<?php

abstract class LoaderFile extends Loader{
    protected $fileName;

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

    /**
     * get an array of all lines in this file
     *
     * @return array[string]
     * @throws Exception if file can not be read
     */
    protected function getLines(){
        $ret = file($this->fileName);
        if($ret === false){
            throw new Exception('Unable to read file');
        }
        $lines = array();
        foreach($ret as $line){
            $lines[] = rtrim($line);
        }
        return $lines;
    }

    /**
     * read integer value for given line string
     *
     * @param string $line
     * @return int
     * @throws Exception
     */
    protected function readInt($line){
        if((string)(int)$line !== $line){
            throw new Exception('Invalid integer');
        }
        return (int)$line;
    }

    /**
     * read float value for given line string
     *
     * @param string $line
     * @return float
     * @throws Exception
     */
    protected function readFloat($line){
        if((string)(float)$line !== $line){
            throw new Exception('Invalid float');
        }
        return (float)$line;
    }

    /**
     * read given line string into given array of parts (int, float, vertex)
     *
     * @param string $line
     * @param array  $parts
     * @param Graph  $graph
     * @return array[mixed]
     * @throws Exception
     */
    protected function readLine($line,$parts,Graph $graph=NULL){
        $ret = array();
        $explode = explode("\t",$line);
        $i = 0;
        foreach($parts as $key=>$part){
            if(!isset($explode[$i])){
                throw new Exception('Line does not split into enough parts');
            }
            $value = $explode[$i++];
            if($part === 'int'){
                $value = $this->readInt($value);
            }else if($part === 'float'){
                $value = $this->readFloat($value);
            }else if($part === 'vertex'){
                $value = $graph->getVertex($value);
            }else{
                throw new Exception('Invalid type "'.$part.'"');
            }
            $ret[$key] = $value;
        }
        return $ret;
    }
}

Add helpers to properly parse lines

Add helpers to properly parse lines


<?php

namespace OpenOrchestra\ThemeBundle\Tests\DependencyInjection;

use \OpenOrchestra\ThemeBundle\DependencyInjection\OpenOrchestraThemeExtension;

/**
 * OpenOrchestraThemeExtensionTest class
 */
class OpenOrchestraThemeExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $configs = array();

        $container = $this
            ->getMockBuilder('\\Symfony\\Component\\DependencyInjection\\ContainerBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $container
            ->expects($this->exactly(1))
            ->method('addResource')
            ->with($this->isInstanceOf('\\Symfony\\Component\\Config\\Resource\\FileResource'));

        $extension = new OpenOrchestraThemeExtension();
        $extension->load($configs, $container);
    }
}

<?php

namespace OpenOrchestra\ThemeBundle\Tests\DependencyInjection;

use \OpenOrchestra\ThemeBundle\DependencyInjection\OpenOrchestraThemeExtension;
use Phake;

/**
 * OpenOrchestraThemeExtensionTest class
 */
class OpenOrchestraThemeExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $configs = array();

        $container = Phake::mock('\Symfony\Component\DependencyInjection\ContainerBuilder');

        $extension = new OpenOrchestraThemeExtension();
        $extension->load($configs, $container);

        Phake::verify($container)->addResource($this->isInstanceOf('\Symfony\Component\Config\Resource\FileResource'));
    }
}

Update OpenOrchestraThemeExtensionTest to use Phake


<?php

class Tag
{
	/**
	 * 입력받은 태그 string을 규칙에 맞게 정리하는 함수
	 * @param $tag_string
	 * @return string
	 */
	public function refine_tags($tag_string)
	{
		$tags = '';
		$tag_array = [];

		$parts = preg_split('/\s+/', $tag_string);
		foreach ($parts as $part) {
			if ($part[0] === '#') {
				$tag_array[] = $part;
			}
		}

		if (count($tag_array) > 0) {
			$tags = implode(' ', $tag_array);
		}

		return $tags;
	}
}

<?php

class Tag
{
	/**
	 * 입력받은 태그 string을 규칙에 맞게 정리하는 함수
	 * @param $tag_string
	 * @return string
	 */
	public function refine_tags($tag_string)
	{
		$tags = '';
		$tag_array = [];

		$parts = preg_split('/\s+/', $tag_string);
		foreach ($parts as $part) {
			if (!empty($part) && $part[0] === '#') {
				$tag_array[] = trim($part);
			}
		}

		if (count($tag_array) > 0) {
			$tags = implode(' ', $tag_array);
		}

		return $tags;
	}
}

Add a feature to trimming spaces

Add a feature to trimming spaces


<?php

namespace SebastiaanLuca\Router\Tests;

use Orchestra\Testbench\TestCase as OrchestraTestCase;
use SebastiaanLuca\Router\RouterServiceProvider;

class TestCase extends OrchestraTestCase
{

    protected function getPackageProviders($app)
    {
        return [RouterServiceProvider::class];
    }

}

<?php

namespace SebastiaanLuca\Router\Tests;

use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
use SebastiaanLuca\Router\RouterServiceProvider;

class TestCase extends OrchestraTestCase
{

    use MockeryPHPUnitIntegration;

    /**
     * Get package providers.
     *
     * @param \Illuminate\Foundation\Application $app
     *
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [RouterServiceProvider::class];
    }

    /**
     * Mock a class and bind it in the IoC container.
     *
     * @param string $class
     * @param mixed $parameters
     *
     * @return \Mockery\MockInterface
     */
    protected function mock($class, $parameters = [])
    {
        $mock = Mockery::mock($class, $parameters);

        $this->app->instance($class, $mock);

        return $mock;
    }

}

Set up Mockery and add PHPDoc to default test case


<?php
class DansTonChatBridge extends BridgeAbstract {

	const MAINTAINER = 'Astalaseven';
	const NAME = 'DansTonChat Bridge';
	const URI = 'https://danstonchat.com/';
	const CACHE_TIMEOUT = 21600; //6h
	const DESCRIPTION = 'Returns latest quotes from DansTonChat.';

	public function collectData(){

		$html = getSimpleHTMLDOM(self::URI . 'latest.html')
			or returnServerError('Could not request DansTonChat.');

		foreach($html->find('div.item') as $element) {
			$item = array();
			$item['uri'] = $element->find('a', 0)->href;
			$item['title'] = 'DansTonChat ' . $element->find('a', 1)->plaintext;
			$item['content'] = $element->find('a', 0)->innertext;
			$this->items[] = $item;
		}
	}
}

<?php
class DansTonChatBridge extends BridgeAbstract {

	const MAINTAINER = 'Astalaseven';
	const NAME = 'DansTonChat Bridge';
	const URI = 'https://danstonchat.com/';
	const CACHE_TIMEOUT = 21600; //6h
	const DESCRIPTION = 'Returns latest quotes from DansTonChat.';

	public function collectData(){

		$html = getSimpleHTMLDOM(self::URI . 'latest.html')
			or returnServerError('Could not request DansTonChat.');

		foreach($html->find('div.item') as $element) {
			$item = array();
			$item['uri'] = $element->find('a', 0)->href;
			$item['title'] = 'DansTonChat ' . html_entity_decode($element->find('h3 a', 0)->plaintext, ENT_QUOTES);
			$item['content'] = $element->find('div.item-content a', 0)->innertext;
			$this->items[] = $item;
		}
	}
}

Update to follow DTC website changes

Update to follow DTC website changes

Now, entry title is optionnal and may be found in h3 HTML element.
Entry content is mandatory and may be found in div[class="item-content"] HTML element.

Moreover, the title may contain simple quotes (here, encoded) so the bridge have to decode first to apply format library function. In case we don't do that, the format function double encode the quote and something like &#039; could appear.


<?php

print $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'];

Fix IP retrieval for PHP server

Fix IP retrieval for PHP server


<?php

namespace ATP\ActiveRecord;

class File
{
	public $name = "";
	public $type = "";
	public $size = "";

	public function setFrom($data)
	{
		if(is_null($data)) return;

		if(!is_array($data)) $data = get_object_vars(json_decode($data));

		$this->name = $data['name'];
		$this->type = $data['type'];
		$this->size = $data['size'];
	}

	public function toJson()
	{
		return json_encode(array(
			'name' => $this->name,
			'type' => $this->type,
			'size' => $this->size
		));
	}
}

<?php

namespace ATP\ActiveRecord;

class File
{
	public $name = "";
	public $type = "";
	public $size = "";

	public function setFrom($data)
	{
		if(is_null($data)) return;

		if(!is_array($data)) $data = get_object_vars(json_decode($data));

		$this->name = $data['name'];
		$this->type = $data['type'];
		$this->size = $data['size'];
	}

	public function toJson()
	{
		return json_encode(array(
			'name' => $this->name,
			'type' => $this->type,
			'size' => $this->size
		));
	}

	public function exists()
	{
		return !empty($this->name);
	}
}

Add exists() method to active record files


<?php namespace PhilipBrown\WorldPay;

use Assert\Assertion;

class Currency {

  /**
   * @var string
   */
  private $name;

  /**
   * @var array
   */
  private static $currencies;

  /**
   * @param string $name
   */
  private function __construct($name)
  {
    if ( ! isset(static::$currencies))
    {
      static::$currencies = require __DIR__.'/currencies.php';
    }

    Assertion::keyExists(static::$currencies, $name);

    $this->name = $name;
  }

  /**
   * Set the Currency
   *
   * @param string $name
   * @return PhilipBrown\WorldPay\Currency
   */
  public static function set($name)
  {
    return new Currency($name);
  }

  /**
   * Return the Currency when cast to string
   *
   * @return string
   */
  public function __toString()
  {
    return $this->name;
  }

}

<?php namespace PhilipBrown\WorldPay;

use Assert\Assertion;

class Currency {

  /**
   * @var string
   */
  private $name;

  /**
   * @var array
   */
  private static $currencies;

  /**
   * @param string $name
   */
  private function __construct($name)
  {
    if ( ! isset(self::$currencies))
    {
      self::$currencies = require __DIR__.'/currencies.php';
    }

    Assertion::keyExists(self::$currencies, $name);

    $this->name = $name;
  }

  /**
   * Set the Currency
   *
   * @param string $name
   * @return PhilipBrown\WorldPay\Currency
   */
  public static function set($name)
  {
    return new Currency($name);
  }

  /**
   * Return the Currency when cast to string
   *
   * @return string
   */
  public function __toString()
  {
    return $this->name;
  }

}

Change static reference to self

Change static reference to self


<?php

/**
 * This file configures default behavior for all workers
 *
 * To modify these parameters, copy this file into your own CakePHP APP/Config directory.
 *
 */

$config['Queue'] = [
	// seconds to sleep() when no executable job is found
	'sleeptime' => 10,

	// probability in percent of a old job cleanup happening
	'gcprob' => 10,

	// time (in seconds) after which a job is requeued if the worker doesn't report back
	'defaultworkertimeout' => 120,

	// number of retries if a job fails or times out.
	'defaultworkerretries' => 4,

	// seconds of running time after which the worker will terminate (0 = unlimited)
	'workermaxruntime' => 20,

	// minimum time (in seconds) which a task remains in the database before being cleaned up.
	'cleanuptimeout' => 2000,

	// instruct a Workerprocess quit when there are no more tasks for it to execute (true = exit, false = keep running)
	'exitwhennothingtodo' => false,

	// pid file path directory (by default goes to the app/tmp/queue folder)
	'pidfilepath' => TMP . 'queue' . DS,

	// determine whether logging is enabled
	'log' => true,

	// set to false to disable (tmp = file in TMP dir)
	'notify' => 'tmp',
];

<?php

/**
 * This file configures default behavior for all workers
 *
 * To modify these parameters, copy this file into your own CakePHP APP/Config directory.
 *
 */

$config['Queue'] = [
	// seconds to sleep() when no executable job is found
	'sleeptime' => 10,

	// probability in percent of a old job cleanup happening
	'gcprob' => 10,

	// time (in seconds) after which a job is requeued if the worker doesn't report back
	'defaultworkertimeout' => 120,

	// number of retries if a job fails or times out.
	'defaultworkerretries' => 4,

	// seconds of running time after which the worker will terminate (0 = unlimited)
	'workermaxruntime' => 20*60,

	// minimum time (in seconds) which a task remains in the database before being cleaned up.
	'cleanuptimeout' => 2000,

	// instruct a Workerprocess quit when there are no more tasks for it to execute (true = exit, false = keep running)
	'exitwhennothingtodo' => false,

	// pid file path directory (by default goes to the app/tmp/queue folder)
	'pidfilepath' => TMP . 'queue' . DS,

	// determine whether logging is enabled
	'log' => true,

	// set to false to disable (tmp = file in TMP dir)
	'notify' => 'tmp',
];

Set worker lifetime to 20 minutes, not 20 seconds


<?php

namespace Interop\Async;

/**
 * Simple interface for awaitable objects representing the future value of asynchronous operations.
 */
interface Awaitable
{
    /**
     * Registers a callback to be invoked when the awaitable is resolved.
     *
     * @param callable(\Throwable|\Exception $exception = null, mixed $result = null) $onResolved
     *
     * @return void
     */
    public function when(callable $onResolved);
}

<?php

namespace Interop\Async;

/**
 * Awaitable object representing the future value of an asynchronous operation.
 */
interface Awaitable
{
    /**
     * Registers a callback to be invoked when the awaitable is resolved.
     *
     * @param callable(\Throwable|\Exception|null $exception, mixed $result) $onResolved
     *
     * @return void
     */
    public function when(callable $onResolved);
}

Update interface description and callable definition


<?php

class CM_RenderEnvironment extends CM_Class_Abstract {

    /** @var CM_Model_User|null */
    protected $_viewer;

    /** @var CM_Site_Abstract */
    protected $_site;

    /**
     * @param CM_Site_Abstract   $site
     * @param CM_Model_User|null $viewer
     */
    public function __construct(CM_Site_Abstract $site, CM_Model_User $viewer = null) {
        if (!$site) {
            $site = CM_Site_Abstract::factory();
        }
        $this->_site = $site;
        $this->_viewer = $viewer;
    }

    /**
     * @return \CM_Site_Abstract
     */
    public function getSite() {
        return $this->_site;
    }

    /**
     * @param boolean|null $needed
     * @return CM_Model_User|null
     * @throws CM_Exception_AuthRequired
     */
    public function getViewer($needed = null) {
        if (!$this->_viewer) {
            if ($needed) {
                throw new CM_Exception_AuthRequired();
            }
            return null;
        }
        return $this->_viewer;
    }
}

<?php

class CM_RenderEnvironment extends CM_Class_Abstract {

    /** @var CM_Model_User|null */
    protected $_viewer;

    /** @var CM_Site_Abstract */
    protected $_site;

    /**
     * @param CM_Site_Abstract|null $site
     * @param CM_Model_User|null    $viewer
     */
    public function __construct(CM_Site_Abstract $site = null, CM_Model_User $viewer = null) {
        if (!$site) {
            $site = CM_Site_Abstract::factory();
        }
        $this->_site = $site;
        $this->_viewer = $viewer;
    }

    /**
     * @return \CM_Site_Abstract
     */
    public function getSite() {
        return $this->_site;
    }

    /**
     * @param boolean|null $needed
     * @return CM_Model_User|null
     * @throws CM_Exception_AuthRequired
     */
    public function getViewer($needed = null) {
        if (!$this->_viewer) {
            if ($needed) {
                throw new CM_Exception_AuthRequired();
            }
            return null;
        }
        return $this->_viewer;
    }
}

Make site optional for RenderEvironment

Make site optional for RenderEvironment


<?php

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

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @api
 */
class Email extends Constraint
{
    public $message = 'This value is not a valid email address.';
    public $checkMX = false;
    public $checkHost = false;
    public $strict = null;

    /**
     * {@inheritDoc}
     */
    public function validatedBy()
    {
        return 'validator.email';
    }
}

<?php

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

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @api
 */
class Email extends Constraint
{
    public $message = 'This value is not a valid email address.';
    public $checkMX = false;
    public $checkHost = false;
    public $strict = null;
}

Change in validator.email service alias to match the validator FQCN


<?php

/**
 * @package elemental
 */
class ElementalGridFieldDeleteAction extends GridFieldDeleteAction {

    public function getColumnContent($gridField, $record, $columnName) {
        if(!$record->canEdit()) return;

        $field = new CompositeField();

		if($record->getClassName() != "ElementVirtualLinked") {
            $field->push(GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false,
                        "unlinkrelation", array('RecordID' => $record->ID))
                ->addExtraClass('gridfield-button-unlink')
                ->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink"))
                ->setAttribute('data-icon', 'chain--minus')
            );
		}

        if($record->canDelete() && $record->VirtualClones()->count() == 0) {
            $field->push(GridField_FormAction::create($gridField,  'DeleteRecord'.$record->ID, false, "deleterecord",
                    array('RecordID' => $record->ID))
                ->addExtraClass('gridfield-button-delete')
                ->setAttribute('title', _t('GridAction.Delete', "Delete"))
                ->setAttribute('data-icon', 'cross-circle')
                ->setDescription(_t('GridAction.DELETE_DESCRIPTION','Delete'))
            );
        }

        return $field->Field();
    }
}

<?php

/**
 * @package elemental
 */
class ElementalGridFieldDeleteAction extends GridFieldDeleteAction {

    public function getColumnContent($gridField, $record, $columnName) {
        if(!$record->canEdit()) return;

        $field = new CompositeField();

		if(!$record instanceof ElementVirtualLinked) {
          $field->push(GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false,
                      "unlinkrelation", array('RecordID' => $record->ID))
              ->addExtraClass('gridfield-button-unlink')
              ->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink"))
              ->setAttribute('data-icon', 'chain--minus')
          );
		}

        if($record->canDelete() && $record->VirtualClones()->count() == 0) {
            $field->push(GridField_FormAction::create($gridField,  'DeleteRecord'.$record->ID, false, "deleterecord",
                    array('RecordID' => $record->ID))
                ->addExtraClass('gridfield-button-delete')
                ->setAttribute('title', _t('GridAction.Delete', "Delete"))
                ->setAttribute('data-icon', 'cross-circle')
                ->setDescription(_t('GridAction.DELETE_DESCRIPTION','Delete'))
            );
        }

        return $field->Field();
    }
}

Use instanceof to include subclasses

Use instanceof to include subclasses


<?php
require_once 'icat.php';
?>
<!doctype html>

<title>Scoreboard</title>

<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="katalyze/css/katalyze.css" />
<meta charset="utf-8">

<?php navigation_container() ?>

Scoreboard

(Katalyzer must be running for this to work)

Update icat API functions to new location. Fix made by someone else.


<?php

namespace Emonkak\Database\Tests;

use Emonkak\Database\PDO;

/**
 * @covers Emonkak\Database\PDO
 *
 * @requires extension sqlite3
 */
class PDOTest extends AbstractPDOTest
{
    public function preparePdo()
    {
        return new PDO('sqlite::memory:', null, null, array(
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
        ));
    }
}

<?php

namespace Emonkak\Database\Tests;

use Emonkak\Database\PDO;

/**
 * @covers Emonkak\Database\PDO
 *
 * @requires extension sqlite3
 */
class PDOTest extends AbstractPDOTest
{
    protected function preparePdo()
    {
        return new PDO('sqlite::memory:', null, null, array(
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
        ));
    }
}

Fix visibility on a test method

Fix visibility on a test method


<?php

function collect_cpuUsage($debug, $log) {
    $usage = explode(" ", exec('vmstat 1 2'));

	print_r($usage);

	// Get CPU usage
	$cpu = 100 - $usage[43];

	// Get WA CPU usage
	$wa = $usage[44];

    if ($debug == TRUE) {
        debug("[DEBUG_COLLECT] CPU Usage: ".$cpu." WA CPU Usage: ".$wa."\n", $log);
    }

    $return = $cpu.",".$wa;

    return $return;

}
?>

<?php

function collect_cpuUsage($debug, $log) {
    $usage = explode(" ", exec('vmstat 1 2'));

	// Get CPU usage
	$cpu = 100 - $usage[43];

	// Get WA CPU usage
	$wa = $usage[44];

    if ($debug == TRUE) {
        debug("[DEBUG_COLLECT] CPU Usage: ".$cpu."% WA CPU Usage: ".$wa."%\n", $log);
    }

    $return = $cpu.",".$wa;

    return $return;

}
?>

Remove some debugging code. Add more debug info.


Add "name_mask" value in configuration file


<?php

require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php';

// Define version of Omise-OpenCart
if (!defined('OMISE_OPENCART_VERSION'))
    define('OMISE_OPENCART_VERSION', '2.2');

// Just mockup
$datetime = new DateTime('now');
$datetime->format('Y-m-d\TH:i:s\Z');
if (!defined('OMISE_OPENCART_RELEASED_DATE'))
    define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z'));

$opencart_version = defined('VERSION') ? " OpenCart/".VERSION : "";

// Define 'OMISE_USER_AGENT_SUFFIX'
if (!defined('OMISE_USER_AGENT_SUFFIX'))
    define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version);

// Define 'OMISE_API_VERSION'
if(!defined('OMISE_API_VERSION'))
    define('OMISE_API_VERSION', '2014-07-27');

?>

<?php

require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php';

// Define version of Omise-OpenCart
if (!defined('OMISE_OPENCART_VERSION'))
    define('OMISE_OPENCART_VERSION', '2.3');

// Just mockup
$datetime = new DateTime('now');
$datetime->format('Y-m-d\TH:i:s\Z');
if (!defined('OMISE_OPENCART_RELEASED_DATE'))
    define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z'));

$opencart_version = defined('VERSION') ? " OpenCart/".VERSION : "";

// Define 'OMISE_USER_AGENT_SUFFIX'
if (!defined('OMISE_USER_AGENT_SUFFIX'))
    define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version);

// Define 'OMISE_API_VERSION'
if(!defined('OMISE_API_VERSION'))
    define('OMISE_API_VERSION', '2014-07-27');

?>

Change version from 2.2 to 2.3

Change version from 2.2 to 2.3


<?php

namespace Affinity\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Affinity\AppBundle\Entity\Employee;

class EmployeeController extends Controller
{
    public function loginFormAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        $stuff = new \Affinity\AppBundle\DependencyInjection\AffinityAppExtension;

        if( $request->attributes->has( SecurityContext::AUTHENTICATION_ERROR )) {
            $error = $request->attributes->get( SecurityContext::AUTHENTICATION_ERROR );
        } else {
            $error = $session->get( SecurityContext::AUTHENTICATION_ERROR );
            $session->remove( SecurityContext::AUTHENTICATION_ERROR );
        }

        return $this->render( 'AffinityAppBundle:Employee:login.html.twig', array(
            'last_username' => $session->get( SecurityContext::LAST_USERNAME),
            'error'         => $error
        ));
    }
}

<?php

namespace Affinity\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Affinity\AppBundle\Entity\Employee;

class EmployeeController extends Controller
{
    public function loginFormAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        // Adding a comment for a commit!

        $stuff = new \Affinity\AppBundle\DependencyInjection\AffinityAppExtension;

        if( $request->attributes->has( SecurityContext::AUTHENTICATION_ERROR )) {
            $error = $request->attributes->get( SecurityContext::AUTHENTICATION_ERROR );
        } else {
            $error = $session->get( SecurityContext::AUTHENTICATION_ERROR );
            $session->remove( SecurityContext::AUTHENTICATION_ERROR );
        }

        return $this->render( 'AffinityAppBundle:Employee:login.html.twig', array(
            'last_username' => $session->get( SecurityContext::LAST_USERNAME),
            'error'         => $error
        ));
    }
}

Test commit from another location.

Test commit from another location.


<?php

namespace Common\Core\Twig\Extensions;

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class IncludeOnceExtension extends AbstractExtension
{
    /** @var array */
    private $includedTemplates = [];

    public function getFunctions(): array
    {
        return [
            new TwigFunction(
                'include_once',
                [$this, 'includeOnce'],
                ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
            ),
            new TwigFunction(
                'is_included',
                [$this, 'isIncluded']
            ),
        ];
    }

    public function includeOnce(
        Environment $env,
        array $context,
        string $template,
        array $variables = [],
        bool $withContext = true,
        bool $ignoreMissing = false,
        bool $sandboxed = false
    ): string {
        if ($this->isIncluded($template)) {
            return '';
        }

        $this->includedTemplates[$template] = true;

        return twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
    }

    public function isIncluded(string $template): bool
    {
        return array_key_exists($template, $this->includedTemplates);
    }
}

<?php

namespace Common\Core\Twig\Extensions;

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class IncludeOnceExtension extends AbstractExtension
{
    /** @var array */
    private $includedTemplates = [];

    public function getFunctions(): array
    {
        return [
            new TwigFunction(
                'include_once',
                [$this, 'includeOnce'],
                ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
            ),
            new TwigFunction(
                'is_included',
                [$this, 'isIncluded']
            ),
            new TwigFunction(
                'set_included',
                [$this, 'setIncluded']
            ),
        ];
    }

    public function includeOnce(
        Environment $env,
        array $context,
        string $template,
        array $variables = [],
        bool $withContext = true,
        bool $ignoreMissing = false,
        bool $sandboxed = false
    ): string {
        if ($this->isIncluded($template)) {
            return '';
        }

        $output = twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);

        // this needs to happen after we capture the output so we can check if it was previously included
        $this->setIncluded($template);

        return $output;
    }

    public function isIncluded(string $template): bool
    {
        return $this->includedTemplates[$template] ?? false;
    }

    public function setIncluded(string $template, bool $isIncluded = true): void
    {
        $this->includedTemplates[$template] = $isIncluded;
    }
}

Add set_included function to twig to change the status of a template


<?php namespace CJAN\Gateways;

class ProjectGateway {

	protected $projectRepository;

	public __construct(ProjectRepository $projectRepository)
	{
		$this->projectRepository = $projectRepository;
	}

	public function findProjectsByLetter($letter)
	{
		return array();
	}

}

<?php namespace CJAN\Gateways;

use CJAN\Repositories\ProjectRepository;

class ProjectGateway {

	protected $projectRepository;

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

	public function findProjectsByLetter($letter)
	{
		return array();
	}

}

Fix reference to ProjectRepository in the gateway


<?php

namespace App\Mail;

use Illuminate\Container\Container;
use Illuminate\Mail\Mailable as BaseMailable;

class Mailable extends BaseMailable
{
    public function send($mailer)
    {
        parent::send($mailer);

        Container::getInstance()->call([$this, 'success']);
    }
}

<?php

namespace App\Mail;

use Illuminate\Container\Container;
use Illuminate\Mail\Mailable as BaseMailable;

class Mailable extends BaseMailable
{
    public function send($mailer)
    {
        parent::send($mailer);

        if (method_exists($this, 'success')) {
            $this->success();
        }
    }
}

Fix success method called event if not exists


<?php
$title = "Glidein Service :: Download";
include_once("../../includes/header.inc");
?>

Glidein Service :: Download

Binary Releases

The latest stable release is 1.0.6. Click here for older releases.

Service and Client

glidein_service.gar
Download this if you want both the service and the client

Client Only

glidein_service_client.gar
Download this if you want the client only

Source Code

Subversion: https://smarty.isi.edu/svn/repo1/glidein

To checkout the code from the repository run:

svn co https://smarty.isi.edu/svn/repo1/glidein/trunk GlideinService

<?php
include_once("../../includes/footer.inc");
?>

<?php
$title = "Glidein Service :: Download";
include_once("../../includes/header.inc");
?>

Glidein Service :: Download

Binary Releases

The latest stable release is 1.0.7. Click here for older releases.

Service and Client

glidein_service.gar
Download this if you want both the service and the client

Client Only

glidein_service_client.gar
Download this if you want the client only

Source Code

Subversion: https://smarty.isi.edu/svn/repo1/glidein

To checkout the code from the repository run:

svn co https://smarty.isi.edu/svn/repo1/glidein/trunk GlideinService

<?php
include_once("../../includes/footer.inc");
?>

Update web pages for 1.0.7

Update web pages for 1.0.7

git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1641 e217846f-e12e-0410-a4e5-89ccaea66ff7


<?php if ( !in_array($_SERVER['REMOTE_ADDR'],array('10.14.27.13','10.14.22.162','10.14.22.163')) ):?>

<?php endif; ?>
  Spokane Is Reading
  News
  Get a Library Card
  Support Your Library!

<?php if ( !in_array($_SERVER['REMOTE_ADDR'],array('10.14.27.13','10.14.22.162','10.14.22.163')) ):?>

<?php endif; ?>
  Spokane Is Reading
  Get a Library Card
  Support Your Library!

Remove News button from social bar

Remove News button from social bar


<?php

namespace Foo;

class FooTest extends \PHPUnit_Framework_TestCase {

    public function testDummy()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);

        $foo = new Foo($dependency->reveal());

        $this->assertTrue($foo->bar());
    }

    public function testStub()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $dependency->boolGenerator(1)->willReturn(true);
        $foo = new Foo($dependency->reveal());

        $this->assertTrue($foo->baz());
    }

    public function testMock()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $foo = new Foo($dependency->reveal());

        $foo->baz();

        $dependency->boolGenerator(1)->shouldBeCalled();
    }

    public function testSpy()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $foo = new Foo($dependency->reveal());

        $foo->baz();

        $dependency->boolGenerator(1)->shouldHaveBeenCalled();
    }

}

<?php

namespace Foo;

class FooTest extends \PHPUnit_Framework_TestCase {

    public function testDummy()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);

        $foo = new Foo($dependency->reveal());

        $this->assertTrue($foo->bar());
    }

    public function testStub()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $dependency->boolGenerator(1)->willReturn(true);
        $foo = new Foo($dependency->reveal());

        $this->assertTrue($foo->baz());
    }

    public function testMock()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $foo = new Foo($dependency->reveal());

        $dependency->boolGenerator(1)->shouldBeCalled();

        $foo->baz();
    }

    public function testSpy()
    {
        $dependency = $this->prophesize(\Foo\DependencyInterface::class);
        $foo = new Foo($dependency->reveal());

        $foo->baz();

        $dependency->boolGenerator(1)->shouldHaveBeenCalled();
    }

}

Make the mock actually a mock instead of a spy


<?php

namespace RKA;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class ExampleForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name' => 'email',
            'options' => [
                'label' => 'Email address',
            ],
            'attributes' => [
                'id'       => 'email',
                'class'    => 'form-control',
                'required' => 'required',
            ],
        ]);

        $this->add([
            'name' => 'submit',
            'type' => 'button',
            'options' => [
                'label' => 'Go!',
            ],
            'attributes' => [
                'class' => 'btn btn-default',
            ],
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            'email' => [
                'required' => true,
                'filters'  => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
                'validators' => [
                    ['name' => 'EmailAddress'],
                ],
            ],
        ];
    }
}

<?php

namespace RKA;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class ExampleForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name' => 'email',
            'options' => [
                'label' => 'Email address',
            ],
            'attributes' => [
                'id'       => 'email',
                'class'    => 'form-control',
                'required' => 'required',
            ],
        ]);

        $this->add([
            'name' => 'submit',
            'type' => 'button',
            'options' => [
                'label' => 'Go!',
            ],
            'attributes' => [
                'class' => 'btn btn-default',
                'type'  => 'submit',
            ],
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            'email' => [
                'required' => true,
                'filters'  => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
                'validators' => [
                    ['name' => 'EmailAddress'],
                ],
            ],
        ];
    }
}

Set type of the button to submit.

Set type of the button to submit.


<?php
use BryanCrowe\Growl\Builder\GrowlNotifyWindowsBuilder;

class GrowlNotifyWindowsBuilderTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->GrowlNotifyWindowsBuilder = new GrowlNotifyWindowsBuilder();
    }

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

    public function testBuild()
    {
        $options = [
            'title' => 'Hello',
            'image' => 'Mail',
            'url' => 'http://www.example.com',
            'message' => 'World',
            'sticky' => true
        ];
        $expected = 'growlnotify /t:Hello /i:Mail /cu:' .
                    'http://www.example.com /s:true World';
        $result = $this->GrowlNotifyWindowsBuilder->build($options);
        $this->assertSame($expected, $result);

        $options = [
            'title' => 'Hello',
            'message' => 'World',
            'sticky' => false
        ];
        $expected = 'growlnotify /t:Hello World';
        $result = $this->GrowlNotifyWindowsBuilder->build($options);
        $this->assertSame($expected, $result);
    }
}

<?php
use BryanCrowe\Growl\Builder\GrowlNotifyWindowsBuilder;

class GrowlNotifyWindowsBuilderTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->GrowlNotifyWindowsBuilder = new GrowlNotifyWindowsBuilder();
    }

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

    public function testBuild()
    {
        $options = [
            'title' => 'Hello',
            'image' => 'C:\okay.jpg',
            'url' => 'http://www.example.com',
            'message' => 'World',
            'sticky' => true
        ];
        $expected = 'growlnotify /t:Hello /i:C:\okay.jpg /cu:' .
                    'http://www.example.com /s:true World';
        $result = $this->GrowlNotifyWindowsBuilder->build($options);
        $this->assertSame($expected, $result);

        $options = [
            'title' => 'Hello',
            'message' => 'World',
            'sticky' => false
        ];
        $expected = 'growlnotify /t:Hello World';
        $result = $this->GrowlNotifyWindowsBuilder->build($options);
        $this->assertSame($expected, $result);
    }
}

Update image path for Windows builder test


<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\CacheRMData::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('app:cachermdata')
            ->everyFiveMinutes();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('app/routes/console.php');
    }
}

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\CacheRMData::class,
    ];

    public function __construct(Application $app, Dispatcher $events)
    {
        define('ARTISAN_BINARY', 'bin/artisan');

        parent::__construct($app, $events);
    }

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('app:cachermdata')
            ->everyFiveMinutes();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('app/routes/console.php');
    }
}

Set artisan binary in console kernel

Set artisan binary in console kernel


<?php

namespace h4cc\StackFlysystem\Handler;

use h4cc\StackFlysystem\HandlerInterface;
use League\Flysystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Reader implements HandlerInterface
{
    private $filesystem;

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

    public function handlesRequest(Request $request)
    {
        return ('GET' == $request->getMethod());
    }

    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        /** @var \League\Flysystem\File $file */
        $file = $this->filesystem->get($request->getRequestUri());

        $response = new Response($file->read(), 200);
        $response->headers->set('Content-Type', $file->getMimetype());
        $timestamp = $file->getTimestamp();
        if ($timestamp) {
            $response->setLastModified(new \DateTime('@' . $timestamp));
        }

        return $response;
    }
}

<?php

namespace h4cc\StackFlysystem\Handler;

use DateTime;
use h4cc\StackFlysystem\HandlerInterface;
use League\Flysystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class Reader implements HandlerInterface
{
    private $filesystem;

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

    public function handlesRequest(Request $request)
    {
        return ('GET' == $request->getMethod());
    }

    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        /** @var \League\Flysystem\File $file */
        $file = $this->filesystem->get($request->getRequestUri());

        $response = new StreamedResponse(function () use ($file) {
            $stream = $file->readStream();
            fpassthru($stream);
        }, 200);

        $response->headers->set('Content-Type', $file->getMimetype());
        $timestamp = $file->getTimestamp();

        if ($timestamp) {
            $response->setLastModified(new DateTime('@' . $timestamp));
        }

        return $response;
    }
}

Use streams instead of strings for the response when reading.


<?php

namespace ATPComic\Model;

require_once("Arc.php");

class Commentary extends \ATP\ActiveRecord
{
	public function displayName()
	{
		return "'" . $this->title . "' for '" . $this->page->title . "' by " . $this->user->username;
	}
}
Commentary::init();

<?php

namespace ATPComic\Model;

require_once("Arc.php");

class Commentary extends \ATP\ActiveRecord
{
    public function __construct()
    {
        parent::__construct();

        //Necessary to make sure the admin user class is loaded
        $user = new \ATPAdmin\Model\User();
    }

	public function displayName()
	{
		return "'" . $this->title . "' for '" . $this->page->title . "' by " . $this->user->username;
	}
}
Commentary::init();

Make sure admin user class is loaded for commentaries


<?php
namespace ClassTemplate;
use ClassTemplate\Utils;

class ClassMethod extends UserFunction
{
    public $scope = 'public';

    public function setScope($scope)
    {
        $this->scope = $scope;
    }

    public function render(array $args = array())
    {
        $block = $this->getBlock();
        $block->setIndent(1);
        return Utils::indent(1)  . $this->scope . ' function ' . $this->name . '(' . $this->renderArguments() . ") \n"
            . $block->render($args)
            ;
    }

}

<?php
namespace ClassTemplate;
use ClassTemplate\Utils;

class ClassMethod extends UserFunction
{
    public $scope = 'public';

    public function setScope($scope)
    {
        $this->scope = $scope;
    }

    public function render(array $args = array())
    {
        $block = $this->getBlock();
        $block->setIndent(1);
        return Utils::indent(1)  . $this->scope . ' function ' . $this->name . '(' . $this->renderArguments() . ")\n"
            . $block->render($args)
            ;
    }

}

Remove trailing space for the generated code


<?php
/**
 * FluxBB - fast, light, user-friendly PHP forum software
 * Copyright (C) 2008-2012 FluxBB.org
 * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public license for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @category	FluxBB
 * @package		Core
 * @copyright	Copyright (c) 2008-2012 FluxBB (http://fluxbb.org)
 * @license		http://www.gnu.org/licenses/gpl.html	GNU General Public License
 */

namespace FluxBB\Controllers;

use FluxBB\Models\Category;

class Search extends Base
{

	public function get_index()
	{
		$categories = Category::all();
		return View::make('fluxbb::search.index')
				->with('categories', $categories);
	}

}

<?php
/**
 * FluxBB - fast, light, user-friendly PHP forum software
 * Copyright (C) 2008-2012 FluxBB.org
 * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public license for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @category	FluxBB
 * @package		Core
 * @copyright	Copyright (c) 2008-2012 FluxBB (http://fluxbb.org)
 * @license		http://www.gnu.org/licenses/gpl.html	GNU General Public License
 */

namespace FluxBB\Controllers;

use FluxBB\Models\Category;

class Search extends Base
{

	public function get_index()
	{
		$categories = Category::all();
		return \View::make('fluxbb::search.index')
				->with('categories', $categories);
	}

}

Fix namespace issue in search controller.


<?php

require_once 'Doctrine/Common/ClassLoader.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();

$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';
$configuration = new \Doctrine\Common\Cli\Configuration();

if (file_exists($configFile)) {
    if ( ! is_readable($configFile)) {
        trigger_error(
            'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
        );
    }

    require $configFile;

    foreach ($GLOBALS as $configCandidate) {
        if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) {
            $configuration = $configCandidate;
            break;
        }
    }
}

$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']);

<?php

require_once 'Doctrine/Common/ClassLoader.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();

$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';

$configuration = null;
if (file_exists($configFile)) {
    if ( ! is_readable($configFile)) {
        trigger_error(
            'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
        );
    }

    require $configFile;

    foreach ($GLOBALS as $configCandidate) {
        if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) {
            $configuration = $configCandidate;
            break;
        }
    }
}

$configuration = ($configuration) ?: new \Doctrine\Common\Cli\Configuration();

$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']);

[2.0] Fix bug in detection of global Doctrine Cli Configuration finding the empty replacement configuration before the correct one.


<?php

$contents = "";
const TESTS_DIRECTORY = __DIR__ . "/cases/";

$directory = new RecursiveDirectoryIterator(TESTS_DIRECTORY);
$iterator = new RecursiveIteratorIterator($directory);

/** @var SplFileInfo $file */
foreach ($iterator as $file)
{
    if (!$file->isFile() || "js" !== $file->getExtension())
    {
        continue;
    }

    $module = "";

    if (1 === preg_match('~' . preg_quote(TESTS_DIRECTORY, '~') . '(?<module>.*?)/~', $file->getPathname(), $matches))
    {
        $module = $matches["module"];
    }

    $module = 'QUnit.module("' . addslashes($module) . '");' . "\n\n";

    $contents .= "(function () {\n" . $module . file_get_contents($file->getPathname()) . "\n})();\n\n";
}

header("Content-Type: application/javascript; charset=utf-8");
echo $contents;

<?php

$contents = "";
const TESTS_DIRECTORY = __DIR__ . "/cases/";

$directory = new RecursiveDirectoryIterator(TESTS_DIRECTORY);
$iterator = new RecursiveIteratorIterator($directory);

/** @var SplFileInfo $file */
foreach ($iterator as $file)
{
    if (!$file->isFile() || "js" !== $file->getExtension())
    {
        continue;
    }

    $relativeName = substr($file->getPathname(), strlen(TESTS_DIRECTORY));
    $moduleName = addslashes($relativeName);
    $testContent = file_get_contents($file->getPathname());

    $contents .= <<<TEST
(function () {
    QUnit.module("{$moduleName}", function () {
        {$testContent}
    });
})();

TEST;
}

header("Content-Type: application/javascript; charset=utf-8");
echo $contents;

Improve handling of modules in tests loader


<?php
/**
 * @file
 * A script containing any set-up steps required for PHPUnit testing.
 */

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

$env_prefix = (new \Platformsh\Cli\Service\Config())->get('application.env_prefix');
if (!getenv($env_prefix . 'DRUSH')) {
    putenv($env_prefix . 'DRUSH=' . CLI_ROOT . '/vendor/bin/drush');
}

Remove Drush location hack for travis/phpunit


<?php

namespace Snout\Tests {
    require __DIR__ . '/../vendor/autoload.php';
}

Add blank line for psr2

Add blank line for psr2


<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r($data);

}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r(json_decode($data, 'utf-8'));
	exit;
}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

Improve DiscoJuice Feed debug view

Improve DiscoJuice Feed debug view


<?php

class EventsCest
{
    public function testIfICantCreateAnEventWithoutBeingAuthenticated(AcceptanceTester $I)
    {
        $I->am('guest');
        $I->wantTo('see that i can\'t create an event');
        $I->amOnPage('event/create');
        $I->canSeeResponseCodeIs(301);
    }
}

<?php

class EventsCest
{
    public function testIfICantCreateAnEventWithoutBeingAuthenticated(AcceptanceTester $I)
    {
        $I->am('guest');
        $I->wantTo('see that i can\'t create an event');
        $I->amOnPage('event/create');
        $I->canSee('have to be logged in', '.alert-danger');
    }
}

Refactor event create test to check for words instead of response code


<?php

abstract class LoaderFile extends Loader{
    protected $fileName;

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

    protected function getLines(){
        $ret = file($this->fileName, FILE_IGNORE_NEW_LINES);
        if($ret === false){
            throw new Exception('Unable to read file');
        }
        return $ret;
    }
}

<?php

abstract class LoaderFile extends Loader{
    protected $fileName;

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

    /**
     * get an array of all lines in this file
     *
     * @return array[string]
     * @throws Exception if file can not be read
     */
    protected function getLines(){
        $ret = file($this->fileName);
        if($ret === false){
            throw new Exception('Unable to read file');
        }
        $lines = array();
        foreach($ret as $line){
            $lines[] = rtrim($line);
        }
        return $lines;
    }

    /**
     * read integer value for given line string
     *
     * @param string $line
     * @return int
     * @throws Exception
     */
    protected function readInt($line){
        if((string)(int)$line !== $line){
            throw new Exception('Invalid integer');
        }
        return (int)$line;
    }

    /**
     * read float value for given line string
     *
     * @param string $line
     * @return float
     * @throws Exception
     */
    protected function readFloat($line){
        if((string)(float)$line !== $line){
            throw new Exception('Invalid float');
        }
        return (float)$line;
    }

    /**
     * read given line string into given array of parts (int, float, vertex)
     *
     * @param string $line
     * @param array  $parts
     * @param Graph  $graph
     * @return array[mixed]
     * @throws Exception
     */
    protected function readLine($line,$parts,Graph $graph=NULL){
        $ret = array();
        $explode = explode("\t",$line);
        $i = 0;
        foreach($parts as $key=>$part){
            if(!isset($explode[$i])){
                throw new Exception('Line does not split into enough parts');
            }
            $value = $explode[$i++];
            if($part === 'int'){
                $value = $this->readInt($value);
            }else if($part === 'float'){
                $value = $this->readFloat($value);
            }else if($part === 'vertex'){
                $value = $graph->getVertex($value);
            }else{
                throw new Exception('Invalid type "'.$part.'"');
            }
            $ret[$key] = $value;
        }
        return $ret;
    }
}

Add helpers to properly parse lines

Add helpers to properly parse lines


<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Common;

interface GatewayedObjectInterface
{
    /**
     * Return parent gateway.
     *
     * @return GatewayedObjectInterface
     */
    public function getGateway();
}

<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Common;

use ActiveCollab\Payments\Gateway\GatewayInterface;

interface GatewayedObjectInterface
{
    /**
     * Return parent gateway.
     *
     * @return GatewayInterface
     */
    public function getGateway();
}

Correct error in return type

Correct error in return type


<?php namespace Devfactory\Variables\Controllers;

use Config;
use Input;
use Lang;
use Redirect;
use URL;
use View;

use \Variables;

use Illuminate\Routing\Controller as BaseController;

class VariablesController extends BaseController {

  /**
   * Initializer.
   *
   * @return void
   */
  public function __construct() {
    parent::__construct();

    View::composer('variables::*', 'Devfactory\Variables\Composers\VariablesComposer');
  }

  /**
   * Show a list of all the variables.
   *
   * @return View
   */
  public function getIndex() {
    $variables = Variables::getAll();

    $edit_url = URL::action(get_class($this) . '@postUpdate');

    return View::make('variables::index', compact('variables', 'edit_url'));
  }

  /**
   * Update all the variables according to the value set in the form
   *
   * @return
   */
  public function postUpdate() {
    $variables = Variables::getAll();

    foreach ($variables as $key => $variable) {
      if (Input::get($key) != $variable['value']) {
        Variables::set($key, Input::get($key));
      }
    }

    return Redirect::to(URL::action(get_class($this) . '@getIndex'));
  }

}

<?php namespace Devfactory\Variables\Controllers;

use Config;
use Input;
use Lang;
use Redirect;
use URL;
use View;

use \Variables;

use Illuminate\Routing\Controller as BaseController;

class VariablesController extends BaseController {

  /**
   * Initializer.
   *
   * @return void
   */
  public function __construct() {
    View::composer('variables::*', 'Devfactory\Variables\Composers\VariablesComposer');
  }

  /**
   * Show a list of all the variables.
   *
   * @return View
   */
  public function getIndex() {
    $variables = Variables::getAll();

    $edit_url = URL::action(get_class($this) . '@postUpdate');

    return View::make('variables::index', compact('variables', 'edit_url'));
  }

  /**
   * Update all the variables according to the value set in the form
   *
   * @return
   */
  public function postUpdate() {
    $variables = Variables::getAll();

    foreach ($variables as $key => $variable) {
      if (Input::get($key) != $variable['value']) {
        Variables::set($key, Input::get($key));
      }
    }

    return Redirect::to(URL::action(get_class($this) . '@getIndex'));
  }

}

Remove call to parent constructor in Controller


<?php

namespace PhpSpec\Matcher;

use PhpSpec\Formatter\Presenter\PresenterInterface;

use PhpSpec\Exception\Example\FailureException;

class CallbackMatcher extends BasicMatcher
{
    private $name;
    private $callback;
    private $presenter;

    public function __construct($name, $callback, PresenterInterface $presenter)
    {
        $this->name      = $name;
        $this->callback  = $callback;
        $this->presenter = $presenter;
    }

    public function supports($name, $subject, array $arguments)
    {
        return $name === $this->name;
    }

    protected function matches($subject, array $arguments)
    {
        array_unshift($arguments, $subject);

        return (Boolean) call_user_func_array($this->callback, $arguments);
    }

    protected function getFailureException($name, $subject, array $arguments)
    {
        return new FailureException(sprintf(
            '%s expected to %s, but it is not.',
            $this->presenter->presentValue($subject),
            $this->presenter->presentString($name)
        ));
    }

    protected function getNegativeFailureException($name, $subject, array $arguments)
    {
        return new FailureException(sprintf(
            '%s not expected to %s, but it is.',
            $this->presenter->presentValue($subject),
            $this->presenter->presentString($name)
        ));
    }
}

<?php

namespace PhpSpec\Matcher;

use PhpSpec\Formatter\Presenter\PresenterInterface;

use PhpSpec\Exception\Example\FailureException;

class CallbackMatcher extends BasicMatcher
{
    private $name;
    private $callback;
    private $presenter;

    public function __construct($name, $callback, PresenterInterface $presenter)
    {
        $this->name      = $name;
        $this->callback  = $callback;
        $this->presenter = $presenter;
    }

    public function supports($name, $subject, array $arguments)
    {
        return $name === $this->name;
    }

    protected function matches($subject, array $arguments)
    {
        array_unshift($arguments, $subject);

        return (Boolean) call_user_func_array($this->callback, $arguments);
    }

    protected function getFailureException($name, $subject, array $arguments)
    {
        return new FailureException(sprintf(
            '%s expected to %s(%s), but it is not.',
            $this->presenter->presentValue($subject),
            $this->presenter->presentString($name),
            implode(', ', array_map(array($this->presenter, 'presentValue'), $arguments))
        ));
    }

    protected function getNegativeFailureException($name, $subject, array $arguments)
    {
        return new FailureException(sprintf(
            '%s not expected to %s(%s), but it is.',
            $this->presenter->presentValue($subject),
            $this->presenter->presentString($name),
            implode(', ', array_map(array($this->presenter, 'presentValue'), $arguments))
        ));
    }
}

Add more information to callback matchers exception messages


<?php

namespace Test\Unit;

use Test\TestCase;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class ModelHelperTest extends TestCase
{
    public function testGetModelWithoutNamespaceReturnsFalse()
    {
        $crudApi = new CrudApi(['namespace' => null]);

        $this->assertFalse($crudApi->getModel());
    }

    public function testGetModelUser()
    {
        $namespace = 'Test\\Models\\';

        $options = [
            'namespace' => $namespace,
            'model' => 'User',
        ];

        $crudApi = new CrudApi($options);

        $fqModel = $crudApi->getModel();

        $this->assertEquals($namespace . 'User', $fqModel);
    }

    public function testUserGetModelCanBeInstantiated()
    {
        $namespace = 'Test\\Models\\';

        $options = [
            'namespace' => $namespace,
            'model' => 'User',
        ];

        $crudApi = new CrudApi($options);

        $fqModel = $crudApi->getModel();
        $model = new $fqModel;
        $this->assertEquals('Test\\Models\\User', get_class($model));
    }
}

<?php

namespace Test\Unit;

use Test\TestCase;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class ModelHelperTest extends TestCase
{
    public function testGetModelWithoutNamespaceReturnsFalse()
    {
        $crudApi = new CrudApi(['namespace' => null]);

        $this->assertFalse($crudApi->getModel());
    }

    public function testGetModelUser()
    {
        $namespace = 'Test\\Models\\';

        $options = [
            'namespace' => $namespace,
            'model' => 'User',
        ];

        $crudApi = new CrudApi($options);

        $fqModel = $crudApi->getModel();

        $this->assertEquals($namespace . 'User', $fqModel);
    }

    public function testUserGetModelCanBeInstantiated()
    {
        $namespace = 'Test\\Models\\';

        $options = [
            'namespace' => $namespace,
            'model' => 'User',
        ];

        $crudApi = new CrudApi($options);

        $fqModel = $crudApi->getModel();
        $model = new $fqModel;
        $this->assertEquals('Test\\Models\\User', get_class($model));
    }

    public function testAdditionalModelCanBeInstantiated()
    {
        $namespace = 'Test\\Models\\';

        $options = [
            'namespace' => $namespace,
            'model' => 'AdditionalModel',
        ];

        $crudApi = new CrudApi($options);

        $fqModel = $crudApi->getModel();
        $model = new $fqModel;
        $this->assertEquals('Test\\AnotherNamespace\\AdditionalModel', get_class($model));
    }
}

Add test for additional namespace models. (currently red).


<?php

namespace Kibo\Phast\Filters\CSS\FontSwap;

use Kibo\Phast\Services\ServiceFilter;
use Kibo\Phast\ValueObjects\Resource;

class Filter implements ServiceFilter {
    const FONT_FACE_REGEXP = '/(@font-face\s*\{)([^}]*)/i';

    const ICON_FONT_FAMILIES = [
        'Font Awesome',
        'GeneratePress',
        'Dashicons',
    ];

    private $fontDisplayBlockPattern;

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

    public function apply(Resource $resource, array $request) {
        $css = $resource->getContent();
        $filtered = preg_replace_callback(self::FONT_FACE_REGEXP, function ($match) {
            list($block, $start, $contents) = $match;
            $mode = preg_match($this->fontDisplayBlockPattern, $contents) ? 'block' : 'swap';
            return $start . 'font-display:' . $mode . ';' . $contents;
        }, $css);
        return $resource->withContent($filtered);
    }

    private function getFontDisplayBlockPattern() {
        $patterns = [];
        foreach (self::ICON_FONT_FAMILIES as $family) {
            $chars = str_split($family);
            $chars = array_map(function ($char) {
                return preg_quote($char, '~');
            }, $chars);
            $patterns[] = implode('\s*', $chars);
        }
        return '~' . implode('|', $patterns) . '~i';
    }
}

<?php

namespace Kibo\Phast\Filters\CSS\FontSwap;

use Kibo\Phast\Services\ServiceFilter;
use Kibo\Phast\ValueObjects\Resource;

class Filter implements ServiceFilter {
    const FONT_FACE_REGEXP = '/(@font-face\s*\{)([^}]*)/i';

    const ICON_FONT_FAMILIES = [
        'Font Awesome',
        'GeneratePress',
        'Dashicons',
        'Ionicons',
    ];

    private $fontDisplayBlockPattern;

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

    public function apply(Resource $resource, array $request) {
        $css = $resource->getContent();
        $filtered = preg_replace_callback(self::FONT_FACE_REGEXP, function ($match) {
            list($block, $start, $contents) = $match;
            $mode = preg_match($this->fontDisplayBlockPattern, $contents) ? 'block' : 'swap';
            return $start . 'font-display:' . $mode . ';' . $contents;
        }, $css);
        return $resource->withContent($filtered);
    }

    private function getFontDisplayBlockPattern() {
        $patterns = [];
        foreach (self::ICON_FONT_FAMILIES as $family) {
            $chars = str_split($family);
            $chars = array_map(function ($char) {
                return preg_quote($char, '~');
            }, $chars);
            $patterns[] = implode('\s*', $chars);
        }
        return '~' . implode('|', $patterns) . '~i';
    }
}

Add Ionicons to icon font list

Add Ionicons to icon font list


<?php

namespace BotMan\BotMan;

use BotMan\BotMan\Cache\LaravelCache;
use BotMan\BotMan\Container\LaravelContainer;
use BotMan\BotMan\Storages\Drivers\FileStorage;
use Illuminate\Support\ServiceProvider;

class BotManServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any package services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../assets/config.php' => config_path('botman/config.php'),
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../assets/config.php', 'botman.config');

        $this->app->singleton('botman', function ($app) {
            $storage = new FileStorage(storage_path('botman'));

            $botman = BotManFactory::create(
                config('botman', []),
                new LaravelCache(),
                $app->make('request'),
                $storage
            );

            $botman->setContainer(new LaravelContainer($this->app));

            return $botman;
        });
    }
}

<?php

namespace BotMan\BotMan;

use BotMan\BotMan\Cache\LaravelCache;
use BotMan\BotMan\Container\LaravelContainer;
use BotMan\BotMan\Storages\Drivers\FileStorage;
use Illuminate\Support\ServiceProvider;

class BotManServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any package services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../assets/config.php' => config_path('botman/config.php'),
        ], 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../assets/config.php', 'botman.config');

        $this->app->singleton('botman', function ($app) {
            $storage = new FileStorage(storage_path('botman'));

            $botman = BotManFactory::create(
                config('botman', []),
                new LaravelCache(),
                $app->make('request'),
                $storage
            );

            $botman->setContainer(new LaravelContainer($this->app));

            return $botman;
        });
    }
}

Fix missing group in configuration publishing


<?php

namespace Encore\Admin\Grid\Tools;

use Encore\Admin\Grid;

class CreateButton extends AbstractTool
{
    /**
     * @var Grid
     */
    protected $grid;

    /**
     * Create a new CreateButton instance.
     *
     * @param Grid $grid
     */
    public function __construct(Grid $grid)
    {
        $this->grid = $grid;
    }

    /**
     * Render CreateButton.
     *
     * @return string
     */
    public function render()
    {
        if (!$this->grid->allowCreation()) {
            return '';
        }

        $new = trans('admin.new');

        return <<<EOT

    grid->getCreateUrl()}" class="btn btn-sm btn-success" title="{$new}">
          {$new}

EOT;
    }
}

Use better icon for create-button of Grid

Use "fa-plus" icon instead of "fa-save" for create button


<?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\Component\Locale\Model;

use Doctrine\Common\Collections\Collection;

/**
 * Interface implemented by objects related to multiple locales
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface LocalesAwareInterface
{
    /**
     * @return Collection|LocaleInterface[]
     */
    public function getLocales();

    /**
     * @param Collection $collection
     */
    public function setLocales(Collection $collection);

    /**
     * @param LocaleInterface $locale
     *
     * @return bool
     */
    public function hasLocale(LocaleInterface $locale);

    /**
     * @param LocaleInterface $locale
     */
    public function addLocale(LocaleInterface $locale);

    /**
     * @param LocaleInterface $locale
     */
    public function removeLocale(LocaleInterface $locale);
}

<?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\Component\Locale\Model;

use Doctrine\Common\Collections\Collection;

/**
 * Interface implemented by objects related to multiple locales
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface LocalesAwareInterface
{
    /**
     * @return Collection|LocaleInterface[]
     */
    public function getLocales();

    /**
     * @param LocaleInterface $locale
     *
     * @return bool
     */
    public function hasLocale(LocaleInterface $locale);

    /**
     * @param LocaleInterface $locale
     */
    public function addLocale(LocaleInterface $locale);

    /**
     * @param LocaleInterface $locale
     */
    public function removeLocale(LocaleInterface $locale);
}

Remove unused set*(Collection) methods on models


<?php
/**
 * Adds automatic geocoding to a {@link Addressable} object. Uses the Google
 * Maps API to save latitude and longitude on write.
 *
 * @package silverstripe-addressable
 */
class Geocodable extends DataExtension {

	private static $db = array(
		'Lat' => 'Decimal',
		'Lng' => 'Decimal'
	);

	public function onBeforeWrite() {
		if (!$this->owner->isAddressChanged()) return;

		$address = $this->owner->getFullAddress();
		$region  = strtolower($this->owner->Country);

		if(!$point = GoogleGeocoding::address_to_point($address, $region)) {
			return;
		}

		$this->owner->Lat = $point['lat'];
		$this->owner->Lng = $point['lng'];
	}

	public function updateCMSFields(FieldList $fields) {
		$fields->removeByName('Lat');
		$fields->removeByName('Lng');
	}

	public function updateFrontEndFields(FieldList $fields) {
		$this->updateCMSFields($fields);
	}

}

<?php
/**
 * Adds automatic geocoding to a {@link Addressable} object. Uses the Google
 * Maps API to save latitude and longitude on write.
 *
 * @package silverstripe-addressable
 */
class Geocodable extends DataExtension {

	private static $db = array(
		'Lat' => 'Decimal(9,5)',
		'Lng' => 'Decimal(9,5)'
	);

	public function onBeforeWrite() {
		if (!$this->owner->isAddressChanged()) return;

		$address = $this->owner->getFullAddress();
		$region  = strtolower($this->owner->Country);

		if(!$point = GoogleGeocoding::address_to_point($address, $region)) {
			return;
		}

		$this->owner->Lat = $point['lat'];
		$this->owner->Lng = $point['lng'];
	}

	public function updateCMSFields(FieldList $fields) {
		$fields->removeByName('Lat');
		$fields->removeByName('Lng');
	}

	public function updateFrontEndFields(FieldList $fields) {
		$this->updateCMSFields($fields);
	}

}

Increase decimal size to 5

Increase decimal size to 5

Increase decimal size to 5 places


<?php

/**
 * Bootstrap to load the classes.
 *
 * Include this in the bootstrap for you plugin tests.
 *
 * @package WP_Plugin_Uninstall_Tester
 * @since 0.1.0
 */

$dir = dirname( __FILE__ );

/**
 * The commandline options parser.
 */
require_once $dir . '/includes/wp-plugin-uninstall-tester-phpunit-util-getopt.php';

/**
 * General functions.
 */
require_once $dir . '/includes/functions.php';

/**
 * The plugin install/uninstall test case.
 */
require_once $dir . '/includes/wp-plugin-uninstall-unittestcase.php';

/**
 * Table exists constraint.
 */
require_once $dir . '/includes/constraints/is-table-existant.php';

/**
 * Table non-existant constraint.
 */
require_once $dir . '/includes/constraints/table-is-non-existant.php';

/**
 * No rows with prefix constraint.
 */
require_once $dir . '/includes/constraints/no-rows-with-prefix.php';

unset( $dir );

<?php

/**
 * Bootstrap to load the classes.
 *
 * Include this in the bootstrap for you plugin tests.
 *
 * @package WP_Plugin_Uninstall_Tester
 * @since 0.1.0
 */

/**
 * The directory path of the uninstall tester tools.
 *
 * @since 0.2.0
 *
 * @type string
 */
define( 'WP_PLUGIN_UNINSTALL_TESTER_DIR', dirname( __FILE__ ) );

/**
 * The commandline options parser.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/wp-plugin-uninstall-tester-phpunit-util-getopt.php';

/**
 * General functions.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/functions.php';

/**
 * The plugin install/uninstall test case.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/wp-plugin-uninstall-unittestcase.php';

/**
 * Table exists constraint.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/constraints/is-table-existant.php';

/**
 * Table non-existant constraint.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/constraints/table-is-non-existant.php';

/**
 * No rows with prefix constraint.
 */
require_once WP_PLUGIN_UNINSTALL_TESTER_DIR . '/includes/constraints/no-rows-with-prefix.php';

Add a constant for the path to the main directory

This allows the tools to be more easily extended.


<?php

declare(strict_types=1);

namespace Roave\BetterReflection\TypesFinder;

use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context;

class ResolveTypes
{
    /** @var TypeResolver */
    private $typeResolver;

    public function __construct()
    {
        $this->typeResolver = new TypeResolver();
    }

    /**
     * @param string[] $stringTypes
     * @return Type[]
     */
    public function __invoke(array $stringTypes, Context $context) : array
    {
        $resolvedTypes = [];

        foreach ($stringTypes as $stringType) {
            $resolvedTypes[] = $this->typeResolver->resolve($stringType, $context);
        }

        /** @var Type[] */
        return $resolvedTypes;
    }
}

<?php

declare(strict_types=1);

namespace Roave\BetterReflection\TypesFinder;

use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context;

class ResolveTypes
{
    /** @var TypeResolver */
    private $typeResolver;

    public function __construct()
    {
        $this->typeResolver = new TypeResolver();
    }

    /**
     * @param string[] $stringTypes
     * @return Type[]
     */
    public function __invoke(array $stringTypes, Context $context) : array
    {
        $resolvedTypes = [];

        foreach ($stringTypes as $stringType) {
            /** @var Type $resolvedType */
            $resolvedType = $this->typeResolver->resolve($stringType, $context);
            $resolvedTypes[] = $resolvedType;
        }

        return $resolvedTypes;
    }
}

Remove null type in docblock before assigning to array variable


<?php

namespace Phive\Queue;

use Phive\Queue\Exception\InvalidArgumentException;

class QueueUtils
{
    private function __construct()
    {
    }

    /**
     * @param mixed $eta
     *
     * @return int The Unix timestamp.
     *
     * @throws InvalidArgumentException
     */
    public static function normalizeEta($eta)
    {
        if (null === $eta) {
            return time();
        }
        if (is_string($eta)) {
            $eta = date_create($eta);
        }
        if ($eta instanceof \DateTime) {
            return $eta->getTimestamp();
        }
        if (is_int($eta)) {
            return $eta;
        }

        throw new InvalidArgumentException('The eta parameter is not valid.');
    }
}

<?php

namespace Phive\Queue;

use Phive\Queue\Exception\InvalidArgumentException;

class QueueUtils
{
    private function __construct()
    {
    }

    /**
     * @param mixed $eta
     *
     * @return int The Unix timestamp.
     *
     * @throws InvalidArgumentException
     */
    public static function normalizeEta($eta)
    {
        if (null === $eta) {
            return time();
        }
        if (is_string($eta)) {
            $eta = date_create($eta);
        }
        if ($eta instanceof \DateTime || $eta instanceof \DateTimeInterface) {
            return $eta->getTimestamp();
        }
        if (is_int($eta)) {
            return $eta;
        }

        throw new InvalidArgumentException('The eta parameter is not valid.');
    }
}

Add support for PHP 5.5 DateTimeInterface


<?php

namespace AbleCore;

class HTML {

	public static function image($source, $alt = '', $title = '', array $attributes = array(), array $options = array())
	{
		$default_options = array(
			'type' => 'theme',
		);
		$options = array_replace_recursive($default_options, $options);

		$variables = array();
		switch($options['type']) {
			case 'theme':
				global $theme;
				$variables['path'] = drupal_get_path('theme', $theme) . '/' . $source;
				break;
			default:
				$variables['path'] = $source;
		}
		if ($alt) {
			$variables['alt'] = $alt;
		}
		if ($title) {
			$variables['title'] = $title;
		}
		if (count($attributes) > 0) {
			if (array_key_exists('width', $attributes)) {
				$variables['width'] = $attributes['width'];
				unset($attributes['width']);
			}
			if (array_key_exists('height', $attributes)) {
				$variables['height'] = $attributes['height'];
				unset($attributes['height']);
			}
			$variables['attributes'] = $attributes;
		}

		return theme('image', $variables);
	}

}

<?php

namespace AbleCore;

class HTML {

	public static function image($source, $alt = '', $title = '', array $attributes = array(), array $options = array())
	{
		$default_options = array(
			'type' => 'theme',
		);
		$options = array_replace_recursive($default_options, $options);

		$variables = array();
		switch($options['type']) {
			case 'theme':
				global $theme;
				$variables['path'] = drupal_get_path('theme', $theme) . '/' . $source;
				break;
			default:
				$variables['path'] = $source;
		}
		if ($alt) {
			$variables['alt'] = $alt;
		}
		if ($title) {
			$variables['title'] = $title;
		}
		if (count($attributes) > 0) {
			if (array_key_exists('width', $attributes)) {
				$variables['width'] = $attributes['width'];
				unset($attributes['width']);
			}
			if (array_key_exists('height', $attributes)) {
				$variables['height'] = $attributes['height'];
				unset($attributes['height']);
			}
			$variables['attributes'] = $attributes;
		}

		return theme('image', $variables);
	}

	public static function absImage($source, $alt = '', $title = '', array $attributes = array(), array $options = array())
	{
		$options['type'] = 'absolute';
		return self::image($source, $alt, $title, $attributes, $options);
	}

}

Add shortcut function for absolute images.


<?php
p($l->t('Hello %s,', array($_['invitee'])) . "\n\n");

p($l->t('%s has invited you to join %s.' . " ", array($_['inviter'], $_['productname'])));
p($l->t('You can accept this invitation by using the following link:' . "\n\n"));

print_unescaped($_['link'] . "\n\n");

p($l->t('If you have received this notification in error or if you do not wish to join, simply ignore this mail.'));

<?php
print_unescaped($l->t('Hello %s,', array($_['invitee'])) . "\n\n");

print_unescaped($l->t('%s has invited you to join %s.' . " ", array($_['inviter'], $_['productname'])));
print_unescaped($l->t('You can accept this invitation by using the following link:' . "\n\n"));

print_unescaped($_['link'] . "\n\n");

print_unescaped($l->t('If you have received this notification in error or if you do not wish to join, simply ignore this mail.'));

Print unescaped to avoid problems with umlauts in other languages