<?php

/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Lopi\Bundle\PusherBundle\DependencyInjection;

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

/**
 * LopiPusherExtension
 *
 */
class LopiPusherExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('lopi_pusher.config', $config);

        if (null !== $config['auth_service_id']) {
            $container->setAlias('lopi_pusher.authenticator', $config['auth_service_id']);
        }

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'lopi_pusher';
    }
}

<?php

/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Lopi\Bundle\PusherBundle\DependencyInjection;

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

/**
 * LopiPusherExtension
 *
 */
class LopiPusherExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('lopi_pusher.config', $config);

        if (null !== $config['auth_service_id']) {
            $container->setAlias('lopi_pusher.authenticator', $config['auth_service_id'])->setPublic(true);
        }

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'lopi_pusher';
    }
}

Make alias public to work on SF4+

Make alias public to work on SF4+

Services in SF4+ are now private by default. To make the bundle work in SF4+ we have to set the alias to public. Maybe for further versions it would be better to inject the service to the controller instead of accessing it through the container.


<?php

use PhilipBrown\CapsuleCRM\Connection;

class ModelTest extends PHPUnit_Framework_TestCase {

  public function setUp()
  {
    $this->model = new ModelStub(new Connection('', ''), ['name' => 'Philip Brown']);
  }

  public function testConnectionMethodHasConnection()
  {
    $this->assertInstanceOf('PhilipBrown\CapsuleCRM\Connection', $this->model->connection());
  }

  public function testSettingAnArrayOfAttributes()
  {
    $this->assertEquals('Philip Brown', $this->model->name);
  }

  public function testGetSingularEntityName()
  {
    $this->assertEquals('modelstubs', $this->model->base()->lowercase()->plural());
  }

}

class ModelStub extends PhilipBrown\CapsuleCRM\Model {

  protected $fillable = ['name'];

  public function __construct(Connection $connection, $attributes = [])
  {
    parent::__construct($connection);

    $this->fill($attributes);
  }

}

<?php

use PhilipBrown\CapsuleCRM\Connection;

class ModelTest extends PHPUnit_Framework_TestCase {

  public function setUp()
  {
    $this->model = new ModelStub(new Connection('', ''), ['name' => 'Philip Brown']);
  }

  public function testConnectionMethodHasConnection()
  {
    $this->assertInstanceOf('PhilipBrown\CapsuleCRM\Connection', $this->model->connection());
  }

  public function testSettingAnArrayOfAttributes()
  {
    $this->assertEquals('Philip Brown', $this->model->name);
  }

  public function testSettingAProperty()
  {
    $this->model->email = 'phil@ipbrown.com';
    $this->assertEquals('phil@ipbrown.com', $this->model->email);
  }

  public function testGetSingularEntityName()
  {
    $this->assertEquals('modelstubs', $this->model->base()->lowercase()->plural());
  }

}

class ModelStub extends PhilipBrown\CapsuleCRM\Model {

  protected $fillable = ['name', 'email'];

  public function __construct(Connection $connection, $attributes = [])
  {
    parent::__construct($connection);

    $this->fill($attributes);
  }

}

Add test for setting a property on a model


<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        $json = json_decode($this->response, true);

        return is_array($json) ? $json : $this->response;
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        return is_array($this->response) ? $this->response : json_decode($this->response, true);
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

Change order of json_decode within Response


<?php

namespace Intracto\SecretSantaBundle\Controller;

use Intracto\SecretSantaBundle\Response\TransparentPixelResponse;
use Intracto\SecretSantaBundle\Entity\Participant;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class TrackingController extends Controller
{
    /**
     * @Route("email/{participantId}.gif", name="mailopen_tracker")
     */
    public function trackEmailAction($participantId)
    {
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->addListener(KernelEvents::TERMINATE,
            function (KernelEvent $event) use ($participantId) {
                /**@var Participant $participant*/
                $participant = $this->get('intracto_secret_santa.repository.participant')->find($participantId);
                $participant->setOpenEmailDate(new \DateTime());
                $this->get('doctrine.orm.default_entity_manager')->flush($participant);
            }
        );

        return new TransparentPixelResponse();
    }
}

<?php

namespace Intracto\SecretSantaBundle\Controller;

use Intracto\SecretSantaBundle\Response\TransparentPixelResponse;
use Intracto\SecretSantaBundle\Entity\Participant;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class TrackingController extends Controller
{
    /**
     * @Route("email/{participantId}.gif", name="mailopen_tracker")
     */
    public function trackEmailAction($participantId)
    {
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->addListener(KernelEvents::TERMINATE,
            function (KernelEvent $event) use ($participantId) {
                /** @var Participant $participant */
                $participant = $this->get('intracto_secret_santa.repository.participant')->find($participantId);
                if ($participant != null) {
                    $participant->setOpenEmailDate(new \DateTime());
                    $this->get('doctrine.orm.default_entity_manager')->flush($participant);
                }
            }
        );

        return new TransparentPixelResponse();
    }
}

Check if participant exists when tracking pixel is requested


<?php
	class Card {
		public function __construct($value, $suit) {
			$sourceDirectory = '/home/public/img/cards';

			if (TRUE !== class_exists('Imagick')) {
        		echo 'Imagick class does not exist.';
    		}

			$valueImage = new Imagick();
			$valueImage->readImage($sourceDirectory . '/' . $value . '.png');

			$suitImage = new Imagick();
			$suitImage->readImage($sourceDirectory . '/' . $suit . '.png');

			// Onto the suit, put the value...
			$valueImage->compositeImage($suitImage, Imagick::COMPOSITE_OVERLAY, 0, 0);

			header('Content-Type: image/' . $valueImage->getImageFormat());
			echo $valueImage;
		}
	}
?>

<?php
	class Card {

		private $sourceDirectory = '/home/public/img/cards';

		public function __construct($value, $suit) {

			if (class_exists('Imagick')) {
        		$outputImage = $this->IMagicConstruct($value,$suit);
				$fmt = 'image/' . $outputImage->getImageFormat();
    		} elseif (class_exists('gd')) {
				$outputImage['img'] = $this->GDConstruct($value, $suit);
				$fmt = $outputImage['fmt'];
			} else {
				die('No image libraries installed!');
			}

			header('Content-Type: ' . $fmt);
			echo $valueImage;
		}

		private function IMagickConstruct($value, $suit) {
			$valueImage = new Imagick();
			$valueImage->readImage($this->sourceDirectory . '/' . $value . '.png');

			$suitImage = new Imagick();
			$suitImage->readImage($this->sourceDirectory . '/' . $suit . '.png');

			// Onto the suit, put the value...
			$valueImage->compositeImage($suitImage, Imagick::COMPOSITE_OVERLAY, 0, 0);

			return $valueImage;
		}

		private function GDConstruct($value, $suit) {
			$valueImage = imagecreatefrompng($this->sourceDirectory . '/' . $suit . '.png');
			$suitImage = imagecreatefrompng($this-sourceDirectory . '/' . $value . '.png');
			$imageData = getimagesize($suitImage);
			imagecopymerge($suitImage, $valueImage, 0, 0, 0, 0, $imageData[0], $imageData[1], 100);

			$data = [
				'img' => $suitImage,
				'fmt' => $imageData['mime']
			];

			return $suitImage;
		}
	}
?>

Implement GD image - Attempt 1

Implement GD image - Attempt 1

Trying to add support for GD as a fallback for IMagick. first attempt.


<?php

function is_valid_scorecard_id($id) {
    if ($id === "" || preg_match('/\W/', $id) === 1) {
        return false;
    }
    return true;
}

function error($code) {
    if ($code === 400) {
        header('HTTP/1.1 400 Bad Request');
    } else {
        header('HTTP/1.1 500 Internal Server Error');
    }
    exit();
}

if (!isset($_POST['json'])) {
    error(400);
}

$json = json_decode($_POST['json'], true);
if ($json === NULL) {
    error(400);
}

$id = $json['id'];
if (!is_valid_scorecard_id($id)) {
    error(400);
}

$json = json_encode($json, JSON_PRETTY_PRINT);

$file = fopen("scores/$id", "w") or error(500);
$write = fwrite($file, "$json\n");
fclose($file);

if (!$write) {
    error(500);
}

<?php

function is_valid_scorecard_id($id) {
    if (!$id || preg_match('/\W/', $id) !== 0) {
        return false;
    }

    // These checks probably aren't necessary, but they shouldn't hurt, and
    // help check that the scorecards stay in the right directory.
    if (strstr($id, ".") !== false || strstr($id, "/") !== false) {
        return false;
    }

    return true;
}

function error($code) {
    if ($code === 400) {
        header('HTTP/1.1 400 Bad Request');
    } else {
        header('HTTP/1.1 500 Internal Server Error');
    }
    exit();
}

if (!isset($_POST['json'])) {
    error(400);
}

$json = json_decode($_POST['json'], true);
if ($json === NULL) {
    error(400);
}

$id = $json['id'];
if (!is_valid_scorecard_id($id)) {
    error(400);
}

$json = json_encode($json, JSON_PRETTY_PRINT);

$file = fopen("scores/$id", "w") or error(500);
$write = fwrite($file, "$json\n");
fclose($file);

if (!$write) {
    error(500);
}

Strengthen PHP scorecard id validation

Strengthen PHP scorecard id validation


<?php

namespace Princeton\App\DataModel;

use DateTime;

class DocumentObject implements \JsonSerializable
{
	protected $id;
	protected $active;
	protected $created;
	protected $lastModified;

	public function __construct()
	{
		$this->created = $this->lastModified = new DateTime();
		$this->active = true;
	}

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

	public function isActive()
	{
		return ($this->active === true);
	}

	public function activate()
	{
		$this->active = true;
	}

	public function deactivate()
	{
		$this->active = false;
	}

	public function asArray()
	{
		return array(
			'id' => $this->id,
			'active' => $this->active,
			'created' => $this->created,
			'lastModified' => $this->lastModified,
		);
	}

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

<?php
namespace Princeton\App\DataModel;

use DateTime;

/**
 * A generic base class for MongoDB Document classes.
 *
 * @var string $id - The document's unique ID.
 * @var boolean $active - Whether the record is active or not.
 * @var int $created - Timestamp of when the record was created, in milliseconds.
 * @var int $lastModified - Timestamp of when the record was last modified, in milliseconds.
 *
 * @author Kevin Perry, perry@princeton.edu
 * @copyright 2014 The Trustees of Princeton University.
 */
class DocumentObject implements \JsonSerializable
{

    protected $id;

    protected $active;

    protected $created;

    protected $lastModified;

    public function __construct()
    {
        $this->created = $this->lastModified = self::currentTimeMillis();
        $this->active = true;
    }

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

    public function isActive()
    {
        return ($this->active === true);
    }

    public function activate()
    {
        $this->active = true;
    }

    public function deactivate()
    {
        $this->active = false;
    }

    public function updateTimestamp()
    {
        $this->lastModified = self::currentTimeMillis();
    }

    public function asArray()
    {
        return array(
            'id' => $this->id,
            'active' => $this->active,
            'created' => $this->created,
            'lastModified' => $this->lastModified
        );
    }

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

    protected static function currentTimeMillis()
    {
        return (int) (microtime(true) * 1000);
    }
}

Switch to using int milliseconds for timestamps.


<?php

namespace Addr;

use Alert\Reactor,
    LibDNS\Decoder\DecoderFactory,
    LibDNS\Encoder\EncoderFactory,
    LibDNS\Messages\MessageFactory,
    LibDNS\Records\QuestionFactory;

class ResolverFactory
{
    /**
     * Create a new resolver instance
     *
     * @param Reactor $reactor
     * @param string $serverAddr
     * @param int $serverPort
     * @param int $requestTimeout
     * @param string $hostsFilePath
     * @return Resolver
     */
    public function createResolver(
        Reactor $reactor,
        $serverAddr = null,
        $serverPort = null,
        $requestTimeout = null,
        $hostsFilePath = null
    ) {
        $nameValidator = new NameValidator;

        $client = new Client(
            $reactor,
            new RequestBuilder(
                new MessageFactory,
                new QuestionFactory,
                (new EncoderFactory)->create()
            ),
            new ResponseInterpreter(
                (new DecoderFactory)->create()
            ),
            $serverAddr, $serverPort, $requestTimeout
        );

        $cache = new MemoryCache;
        $hostsFile = new HostsFile($nameValidator, $hostsFilePath);

        return new Resolver($reactor, $nameValidator, $client, $cache, $hostsFile);
    }
}

<?php

namespace Addr;

use Alert\Reactor,
    LibDNS\Decoder\DecoderFactory,
    LibDNS\Encoder\EncoderFactory,
    LibDNS\Messages\MessageFactory,
    LibDNS\Records\QuestionFactory;

class ResolverFactory
{
    /**
     * Create a new resolver instance
     *
     * @param Reactor $reactor
     * @param string $serverAddr
     * @param int $serverPort
     * @param int $requestTimeout
     * @param Cache $cache
     * @param string $hostsFilePath
     * @return Resolver
     */
    public function createResolver(
        Reactor $reactor,
        $serverAddr = null,
        $serverPort = null,
        $requestTimeout = null,
        Cache $cache = null,
        $hostsFilePath = null
    ) {
        $nameValidator = new NameValidator;

        $client = new Client(
            $reactor,
            new RequestBuilder(
                new MessageFactory,
                new QuestionFactory,
                (new EncoderFactory)->create()
            ),
            new ResponseInterpreter(
                (new DecoderFactory)->create()
            ),
            $serverAddr, $serverPort, $requestTimeout
        );

        $cache = $cache ?: new MemoryCache;
        $hostsFile = new HostsFile($nameValidator, $hostsFilePath);

        return new Resolver($reactor, $nameValidator, $client, $cache, $hostsFile);
    }
}

Allow injecting of cache through factory


<?php namespace Vinkla\Translator;

use Vinkla\Translator\Exceptions\TranslatorException;
use Config, Session;

trait TranslatorTrait {

	/**
	 * The default localization key.
	 *
	 * @var string
	 */
	private $defaultLocaleKey = 'locale_id';

	/**
	 * Translator instance.
	 *
	 * @var mixed
	 */
	protected $translatorInstance;

	/**
	 * Prepare a translator instance and fetch translations.
	 *
	 * @throws TranslatorException
	 * @return mixed
	 */
	public function translate()
	{
		if (!$this->translator || !class_exists($this->translator))
		{
			throw new TranslatorException('Please set the $translator property to your translation model path.');
		}

		if (!$this->translatorInstance)
		{
			$this->translatorInstance = new $this->translator();
		}

		return $this->translatorInstance
			->where($this->getForeignKey(), $this->id)
			->where($this->getLocaleKey(), $this->getLocale())
			->first();
	}

	/**
	 * Fetch the default localisation key comparison.
	 *
	 * @return mixed
	 */
	public function getLocale()
	{
		return Session::get($this->getLocaleKey());
	}

	/**
	 * Fetch the localisation key.
	 *
	 * @return string
	 */
	private function getLocaleKey()
	{
		return $this->localeKey ? $this->localeKey : $this->defaultLocaleKey;
	}
}

<?php namespace Vinkla\Translator;

use Vinkla\Translator\Exceptions\TranslatorException;
use Config, Session;

trait TranslatorTrait {

	/**
	 * The default localization key.
	 *
	 * @var string
	 */
	private $defaultLocaleKey = 'locale_id';

	/**
	 * Translator instance.
	 *
	 * @var mixed
	 */
	protected $translatorInstance;

	/**
	 * Prepare a translator instance and fetch translations.
	 *
	 * @throws TranslatorException
	 * @return mixed
	 */
	public function translate()
	{
		if (!$this->translator || !class_exists($this->translator))
		{
			throw new TranslatorException('Please set the $translator property to your translation model path.');
		}

		if (!$this->translatorInstance)
		{
			$this->translatorInstance = new $this->translator();
		}

		return $this->translatorInstance
			->where($this->getForeignKey(), $this->id)
			->where($this->getLocaleKey(), $this->getLocale())
			->first();
	}

	/**
	 * Fetch the default localisation key comparison.
	 * If you not want to fetch the localization id from
	 * a session, this could be overwritten in the modal.
	 *
	 * @return mixed
	 */
	public function getLocale()
	{
		return Session::get($this->getLocaleKey());
	}

	/**
	 * Fetch the localisation key.
	 *
	 * @return string
	 */
	private function getLocaleKey()
	{
		return $this->localeKey ? $this->localeKey : $this->defaultLocaleKey;
	}
}

Add documentation to the getLocale method.


<?php

namespace RenderbitTechnologies\AdminLTE;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    const CONFIG_PATH = __DIR__ . '/../config/adminlte.php';

    public function boot()
    {
        $this->publishes([
            self::CONFIG_PATH => config_path('adminlte.php'),
        ], 'config');
    }

    public function register()
    {
        $this->mergeConfigFrom(
            self::CONFIG_PATH,
            'adminlte'
        );

        $this->app->bind('adminlte', function () {
            return new AdminLTE();
        });
    }
}

<?php

namespace RenderbitTechnologies\AdminLTE;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    const CONFIG_PATH = __DIR__ . '/../config/adminlte.php';

    public function boot()
    {
        $this->publishes([
            self::CONFIG_PATH => config_path('adminlte.php'),
        ], 'config');
    }

    public function register()
    {
        $this->mergeConfigFrom(
            self::CONFIG_PATH,
            'adminlte'
        );

        $this->publishes([
            'vendor/almasaeed2010/adminlte/dist' => public_path('adminlte'),
            'vendor/almasaeed2010/adminlte/bower_components' => public_path('adminlte/plugins'),
        ]);

        $this->app->bind('adminlte', function () {
            return new AdminLTE();
        });
    }
}

Add AdminLTE styles mapping to public folder


<?php

namespace React\Espresso;

use React\EventLoop\Factory;
use React\Socket\Server as SocketServer;
use React\Http\Server as HttpServer;

class Stack extends \Pimple
{
    public function __construct($app)
    {
        $this['loop'] = $this->share(function () {
            return Factory::create();
        });

        $this['socket'] = $this->share(function ($stack) {
            return new SocketServer($stack['loop']);
        });

        $this['http'] = $this->share(function ($stack) {
            return new HttpServer($stack['socket']);
        });

        $this['app'] = $this->protect($app);
    }

    public function listen($port, $host = '127.0.0.1')
    {
        $this['http']->on('request', $this['app']);
        $this['socket']->listen($port, $host);
        $this['loop']->run();
    }
}

<?php

namespace React\Espresso;

use React\EventLoop\Factory;
use React\Socket\Server as SocketServer;
use React\Http\Server as HttpServer;

class Stack extends \Pimple
{
    public function __construct($app)
    {
        $this['loop'] = $this->share(function () {
            return Factory::create();
        });

        $this['socket'] = $this->share(function ($stack) {
            return new SocketServer($stack['loop']);
        });

        $this['http'] = $this->share(function ($stack) {
            return new HttpServer($stack['socket']);
        });

        $this['app'] = $app instanceof \Closure ? $this->protect($app) : $app;
    }

    public function listen($port, $host = '127.0.0.1')
    {
        $this['http']->on('request', $this['app']);
        $this['socket']->listen($port, $host);
        $this['loop']->run();
    }
}

Fix stack to only protect closures

[Espresso] Fix stack to only protect closures


<?php

namespace Droath\ProjectX\Tests;

use Droath\ProjectX\ProjectX;
use Robo\Robo;
use Robo\Tasks;
use Symfony\Component\Console\Output\NullOutput;

/**
 * Define test task base class.
 */
abstract class TestTaskBase extends TestBase
{
    /**
     * Project-X application.
     *
     * @var \Droath\ProjectX\ProjectX
     */
    protected $app;

    /**
     * Robo builder object.
     *
     * @var \Robo\Collection\CollectionBuilder
     */
    protected $builder;

    /**
     * Container.
     *
     * @var \League\Container\ContainerInterface
     */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        parent::setUp();

        // $this->app = new ProjectX();
        // $this->container = Robo::createDefaultContainer(null, new NullOutput(), $this->app);

        // ProjectX::setDefaultServices($this->container);
        $this->builder = $this->container->get('collectionBuilder', [new Tasks()]);
    }
}

<?php

namespace Droath\ProjectX\Tests;

use Droath\ProjectX\ProjectX;
use Robo\Robo;
use Robo\Tasks;
use Symfony\Component\Console\Output\NullOutput;

/**
 * Define test task base class.
 */
abstract class TestTaskBase extends TestBase
{
    /**
     * Project-X application.
     *
     * @var \Droath\ProjectX\ProjectX
     */
    protected $app;

    /**
     * Robo builder object.
     *
     * @var \Robo\Collection\CollectionBuilder
     */
    protected $builder;

    /**
     * Container.
     *
     * @var \League\Container\ContainerInterface
     */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        parent::setUp();

        $this->builder = $this->container->get('collectionBuilder', [new Tasks()]);
    }
}

GH-22: Remove commented code from the test file.


<?php declare(strict_types=1);

namespace WyriHaximus\HtmlCompress\Tests;

use WyriHaximus\HtmlCompress\Factory;
use WyriHaximus\TestUtilities\TestCase;

/**
 * @internal
 */
final class EdgeCasesTest extends TestCase
{
    public function providerEdgeCase(): array
    {
        $dirs = [];

        $items = \glob(__DIR__ . \DIRECTORY_SEPARATOR . 'EdgeCases' . \DIRECTORY_SEPARATOR . '*', \GLOB_ONLYDIR);
        if ($items !== false) {
            foreach ($items as $item) {
                $dirs[$item] = [$item . \DIRECTORY_SEPARATOR];
            }
        }

        return $dirs;
    }

    /**
     * @dataProvider providerEdgeCase
     * @param mixed $dir
     */
    public function testEdgeCase($dir): void
    {
        /** @var string $in */
        $in = \file_get_contents($dir . 'in.html');
        /** @var string $out */
        $out = \file_get_contents($dir . 'out.html');

        $result = Factory::constructSmallest()->compress($in);

        self::assertSame(\strlen($out), \strlen($result));
        self::assertSame($out, $result);
    }
}

<?php declare(strict_types=1);

namespace WyriHaximus\HtmlCompress\Tests;

use WyriHaximus\HtmlCompress\Factory;
use WyriHaximus\TestUtilities\TestCase;

/**
 * @internal
 */
final class EdgeCasesTest extends TestCase
{
    public function providerEdgeCase(): array
    {
        $dirs = [];

        $items = \glob(__DIR__ . \DIRECTORY_SEPARATOR . 'EdgeCases' . \DIRECTORY_SEPARATOR . '*', \GLOB_ONLYDIR);
        if ($items !== false) {
            foreach ($items as $item) {
                $item = $item;
                $itemName = \explode(\DIRECTORY_SEPARATOR, $item);
                $itemName = \array_pop($itemName);
                $dirs[$itemName] = [$item . \DIRECTORY_SEPARATOR];
            }
        }

        return $dirs;
    }

    /**
     * @dataProvider providerEdgeCase
     * @param mixed $dir
     */
    public function testEdgeCase($dir): void
    {
        /** @var string $in */
        $in = \file_get_contents($dir . 'in.html');
        /** @var string $out */
        $out = \file_get_contents($dir . 'out.html');

        $result = Factory::constructSmallest()->compress($in);

        self::assertSame(\strlen($out), \strlen($result));
        self::assertSame($out, $result);
    }
}

Add the edgecase name to the test dataprovider


@extends('layouts.admin')

@section('content')

                    List of orders

                                ID
                                Order At
                                User
                                Quantity
                                Total Price
                                Actions

                            @foreach($orders as $order)

                                    {{ $order->id }}
                                    {{ $order->updated_at }}
                                    {{ $order->user->first_name }} {{ $order->user->last_name }}
                                    {{ $order->orderProducts->sum('quantity') }}
                                    {{ $order->orderProducts->sum('price') }}

                                         $order->id] ) }}"><button class="btn btn-xs btn-primary">Show</button>

                            @endforeach

@endsection

@extends('layouts.admin')

@section('content')

                    List of orders

                                ID
                                Order At
                                User
                                Quantity
                                Total Price
                                Status
                                Actions

                            @foreach($orders as $order)

                                    {{ $order->id }}
                                    {{ $order->updated_at }}
                                    {{ $order->user->first_name }} {{ $order->user->last_name }}
                                    {{ $order->orderProducts->sum('quantity') }}
                                    {{ $order->orderProducts->sum('price') }}
                                    {{ $order->statusText() }}

                                         $order->id] ) }}"><button class="btn btn-xs btn-primary">Show</button>

                            @endforeach

@endsection

Update admin order index page

feat(shop): Update admin order index page

Update admin order index page

see #369


<?php

namespace App\Console\Commands\Report;

use App\Library\Slug;
use App\Models\Collections\Artwork;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use PDO;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportNetx extends BaseCommand
{

    protected $signature = 'report:netx';

    protected $description = 'Show artworks that have NetX images';

    public function handle()
    {
        // https://github.com/laravel/framework/issues/14919
        DB::connection()->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

        $artworks = Artwork::query()
            ->whereHas('assets', function (Builder $query) {
                $query->whereNotNull('netx_uuid');
            })
            ->orderBy('pageviews', 'desc')
            ->limit(100);

        foreach ($artworks->cursor() as $artwork) {
            $this->info('https://nocache.staging.artic.edu/artworks/' . $artwork->citi_id . '/' . Slug::getUtf8Slug($artwork->title));
        }
    }
}

<?php

namespace App\Console\Commands\Report;

use App\Library\Slug;
use App\Models\Collections\Artwork;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use PDO;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportNetx extends BaseCommand
{

    protected $signature = 'report:netx';

    protected $description = 'Show artworks that have NetX images';

    public function handle()
    {
        // https://github.com/laravel/framework/issues/14919
        DB::connection()->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

        $artworks = Artwork::withoutGlobalScope('lastmod')
            ->whereHas('assets', function (Builder $query) {
                $query->whereNotNull('netx_uuid');
            })
            ->orderBy('pageviews', 'desc')
            ->limit(100);

        foreach ($artworks->cursor() as $artwork) {
            $this->info('https://nocache.staging.artic.edu/artworks/' . $artwork->citi_id . '/' . Slug::getUtf8Slug($artwork->title));
        }
    }
}

Disable `lastmod` scope in `report:netx` [WEB-1893]


<?php

namespace DataStream;

/**
 * Data source loader
 */
class Source
{

  protected $data = null;

  /**
  * @var boolean Whether the file should be read once or every time getData is called
  */
  public $loadOnce;

  /**
  * @var string Path to the last file loaded
  */
  public $filePath = null;

  /**
  * @var array Array of file paths to be read and concatenated
  */
  public $filePaths = null;

  function __construct($loadOnce = true)
  {
    $this->loadOnce = $loadOnce;
  }

  public function loadFromFile($filePath)
  {
    $this->filePath = $filePath;
    $this->data = file_get_contents($filePath);
  }

  public function loadFromFiles(array $filePaths)
  {
    foreach ($filePaths as $filePath) {
      $this->data .= file_get_contents($filePath);
    }
  }

  public function getData()
  {
    if (!$this->loadOnce && $this->filePath) {
      $this->loadFromFile($this->filePath);
    }elseif (!$this->loadOnce && is_array($this->filePaths)) {
      $this->loadFromFiles($this->filePaths);
    }

    return $this->data;
  }

  public function setData($data)
  {
    $this->data = $data;

    return $this;
  }
}

<?php

namespace DataStream;

/**
 * Data source loader
 */
class Source
{

  protected $data = null;

  /**
  * @var boolean Whether the file should be read once or every time getData is called
  */
  public $loadOnce;

  /**
  * @var string Path to the last file loaded
  */
  public $filePath = null;

  /**
  * @var array Array of file paths to be read and concatenated
  */
  public $filePaths = null;

  function __construct($loadOnce = true)
  {
    $this->loadOnce = $loadOnce;
  }

  public function loadFromFile($filePath)
  {
    $this->filePath = $filePath;
    $this->data = file_get_contents($filePath);
  }

  public function loadFromFiles(array $filePaths)
  {

    $this->data = '';

    foreach ($filePaths as $filePath) {
      $this->data .= file_get_contents($filePath);
    }
  }

  public function getData()
  {
    if (!$this->loadOnce && $this->filePath) {
      $this->loadFromFile($this->filePath);
    }elseif (!$this->loadOnce && is_array($this->filePaths)) {
      $this->loadFromFiles($this->filePaths);
    }

    return $this->data;
  }

  public function setData($data)
  {
    $this->data = $data;

    return $this;
  }
}

Reset data before reading file contents

Reset data before reading file contents


<?php
namespace Moxio\Sniffs\Tests\PHP;

use Moxio\Sniffs\PHP\DisallowImplicitLooseComparisonSniff;
use Moxio\Sniffs\Tests\AbstractSniffTest;

class DisallowImplicitLooseComparisonSniffTest extends AbstractSniffTest
{
    protected function getSniffClass()
    {
        return DisallowImplicitLooseComparisonSniff::class;
    }

    public function testSniff()
    {
        $file = __DIR__ . '/DisallowImplicitLooseComparisonSniffTest.inc';
        $this->assertFileHasErrorsOnLines($file, [
            2,
            3,
            4,
            14,
            17,
            20
        ]);
    }
}

<?php
namespace Moxio\Sniffs\Tests\PHP;

use Moxio\Sniffs\PHP\DisallowImplicitLooseComparisonSniff;
use Moxio\Sniffs\Tests\AbstractSniffTest;

class DisallowImplicitLooseComparisonSniffTest extends AbstractSniffTest
{
    protected function getSniffClass()
    {
        return DisallowImplicitLooseComparisonSniff::class;
    }

    public function testSniff()
    {
        $file = __DIR__ . '/DisallowImplicitLooseComparisonSniffTest.inc';
        $this->assertFileHasErrorsOnLines($file, [
            2,
            3,
            4,
            14,
            17,
            20,
        ]);
    }
}

Add comma to the last element of the array


<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array|null
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error(
                'GraphQL request failed. Query: '.$query
                .' Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
            );

            return null;
        }

        return $response ? $response->getData() : null;
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array|null
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
    }
}

<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array|null
     */
    public function query($query, $variables)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error('GraphQL request failed.', [
                'query' => $query,
                'variables' => $variables,
                'exception' => $exception->getMessage(),
            ]);

            return null;
        }

        return $response ? $response->getData() : null;
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array|null
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
    }
}

Use "meta" block for logging variables

Use "meta" block for logging variables


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Application Debug Mode
	|--------------------------------------------------------------------------
	|
	| When your application is in debug mode, detailed error messages with
	| stack traces will be shown on every error that occurs within your
	| application. If disabled, a simple generic error page is shown.
	|
	*/

	'debug' => true,

);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Application Debug Mode
	|--------------------------------------------------------------------------
	|
	| When your application is in debug mode, detailed error messages with
	| stack traces will be shown on every error that occurs within your
	| application. If disabled, a simple generic error page is shown.
	|
	*/

	'debug' => $_ENV['debug_mode'],

);

Read the debug_mode setting from the env file


<?php
/**
 * Messages for Registration
 *
 * @author     Ushahidi Team <team@ushahidi.com>
 * @package    Ushahidi\Application\Messages
 * @copyright  Ushahidi - http://www.ushahidi.com
 * @license    http://www.gnu.org/copyleft/gpl.html GNU General Public License Version 3 (GPLv3)
 */
return array
(
    'crowdmapid' => array(
        'email_collision' => 'That email address already has an account registered.',
        'username_collision' => 'That username is already in use. Pleae try another.',
        'password_collision' => 'You must use your existing CrowdmapID password.',
        'generic_error' => 'Pleae try again later.'
    ),
	'token' => array(
		'not_empty' => 'invalid submission',
		'Security::check' => 'invalid submission'
	)
);

<?php
/**
 * Messages for Registration
 *
 * @author     Ushahidi Team <team@ushahidi.com>
 * @package    Ushahidi\Application\Messages
 * @copyright  Ushahidi - http://www.ushahidi.com
 * @license    http://www.gnu.org/copyleft/gpl.html GNU General Public License Version 3 (GPLv3)
 */
return array
(
    'crowdmapid' => array(
        'email_collision' => 'That email address already has an account registered.',
        'username_collision' => 'That username is already in use. Pleae try another.',
        'password_collision' => 'You must use your existing CrowdmapID password.',
        'generic_error' => 'Please try again later.'
    ),
	'token' => array(
		'not_empty' => 'invalid submission',
		'Security::check' => 'invalid submission'
	)
);

Correct spelling mistake in 'generic_error'


<?php

namespace Tighten\Linters\Concerns;

trait LintsNonConfigFiles
{
    public static function appliesToPath(string $path): bool
    {
        return strpos($path, '/config/') === false;
    }
}

<?php

namespace Tighten\Linters\Concerns;

trait LintsNonConfigFiles
{
    public static function appliesToPath(string $path): bool
    {
        return strpos($path, DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR) === false;
    }
}

Use DIRECTORY_SEPARATOR in manually created string paths for comparison, so it will work on Windows platforms.


<?php

namespace BlizzardGalaxy\ApiSupervisor\Registry;

use BlizzardGalaxy\ApiSupervisor\Exception\ApiSupervisorException;

/**
 * Offers methods for easily reading in configuration values.
 *
 * @package BlizzardGalaxy\ApiSupervisor\Registry
 * @author  Petre Pătrașc <petre@dreamlabs.ro>
 */
class FileSystemRegistryManager extends AbstractRegistryManager
{
    const CONFIG_FILE_PATH = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR;

    /**
     * Retrieve the API key used to make calls
     * to Battle.NET endpoints.
     *
     * @return string
     * @throws ApiSupervisorException
     */
    public function getApiKey()
    {
        $apiKey = @file_get_contents(self::CONFIG_FILE_PATH . 'apikey.lock');

        if (false === $apiKey) {
            throw new ApiSupervisorException('Could not load API key.');
        }

        return trim($apiKey);
    }
}

<?php

namespace BlizzardGalaxy\ApiSupervisor\Registry;

use BlizzardGalaxy\ApiSupervisor\Exception\ApiSupervisorException;

/**
 * Offers methods for easily reading in configuration values.
 *
 * @package BlizzardGalaxy\ApiSupervisor\Registry
 * @author  Petre Pătrașc <petre@dreamlabs.ro>
 */
class FileSystemRegistryManager extends AbstractRegistryManager
{
    /**
     * Return the filepath to the config folder.
     *
     * @return string
     */
    private function getConfigFilePath()
    {
        return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR;
    }

    /**
     * Retrieve the API key used to make calls
     * to Battle.NET endpoints.
     *
     * @return string
     * @throws ApiSupervisorException
     */
    public function getApiKey()
    {
        $apiKey = @file_get_contents($this->getConfigFilePath() . 'apikey.lock');

        if (false === $apiKey) {
            throw new ApiSupervisorException('Could not load API key.');
        }

        return trim($apiKey);
    }
}

Fix minor issue with the FS registry

Fix minor issue with the FS registry


<?php

namespace PhpSpec\Formatter\Html;

use PhpSpec\Formatter\Presenter\StringPresenter;
use Exception;

class HtmlPresenter extends StringPresenter
{
    public function presentException(Exception $exception, $verbose = false)
    {
        if (method_exists($exception, 'getCause')) {
            list($file, $line) = $this->getExceptionExamplePosition($exception);
            return $this->presentFileCode($file, $line);
        }
    }

    protected function presentFileCode($file, $lineno, $context = 6)
    {
        $lines  = explode("\n", file_get_contents($file));
        $offset = max(0, $lineno - ceil($context / 2));
        $lines  = array_slice($lines, $offset, $context);

        $text = "\n";
        foreach ($lines as $line) {
            $offset++;

            if ($offset == $lineno) {
                $cssClass = "offending";
            } else {
                $cssClass = "normal";
            }
            $text .= ''.$offset.''.$line.'';

            $text .= "\n";
        }

        return $text;
    }
}

<?php

namespace PhpSpec\Formatter\Html;

use PhpSpec\Formatter\Presenter\StringPresenter;
use Exception;
use PhpSpec\Exception\Exception as PhpSpecException;

class HtmlPresenter extends StringPresenter
{
    public function presentException(Exception $exception, $verbose = false)
    {
        if ($exception instanceof PhpSpecException) {
            list($file, $line) = $this->getExceptionExamplePosition($exception);
            return $this->presentFileCode($file, $line);
        }
    }

    protected function presentFileCode($file, $lineno, $context = 6)
    {
        $lines  = explode("\n", file_get_contents($file));
        $offset = max(0, $lineno - ceil($context / 2));
        $lines  = array_slice($lines, $offset, $context);

        $text = "\n";
        foreach ($lines as $line) {
            $offset++;

            if ($offset == $lineno) {
                $cssClass = "offending";
            } else {
                $cssClass = "normal";
            }
            $text .= ''.$offset.''.$line.'';

            $text .= "\n";
        }

        return $text;
    }
}

Check on type rather than method exist

Check on type rather than method exist


<?php namespace Brave\Core\Providers;

use Brave\API;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class CoreApiServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap the application services.
	 *
	 * @return void
	 */
	public function boot()
	{
		// Specify GMP Requirements
		if (!defined('GMP')) {
			define('USE_EXT', 'GMP');
		}

		$this->publishes([
			__DIR__ . '/../Config/bravecore.php' => config_path('bravecore.php'),
		]);
	}

	/**
	 * Register the application services.
	 *
	 * @return void
	 */
	public function register()
	{
		// Use a singleton here, we only need one instance of the api object
		$this->app->bind('CoreApi', function($app){
			$config = $app['config']->get('bravecore');
			return new API(
				$config['application-endpoint'],
				$config['application-identifier'],
				$config['local-private-key'],
				$config['remote-public-key']
			);
		});

	}

	public function provides(){
		return ['CoreApi'];
	}

}

<?php namespace Brave\Core\Providers;

use Brave\API;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class CoreApiServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap the application services.
	 *
	 * @return void
	 */
	public function boot()
	{
		if (extension_loaded ('gmp')) {
			die('PHP Extension "GMP" must be installed with PHP to use BRAVE Core Auth.');
		}

		// Specify GMP Requirements
		if (!defined('USE_MATH_EXT')) {
			define('USE_MATH_EXT', 'GMP');
		}

		$this->publishes([
			__DIR__ . '/../Config/bravecore.php' => config_path('bravecore.php'),
		]);
	}

	/**
	 * Register the application services.
	 *
	 * @return void
	 */
	public function register()
	{
		// Use a singleton here, we only need one instance of the api object
		$this->app->bind('CoreApi', function($app){
			$config = $app['config']->get('bravecore');
			return new API(
				$config['application-endpoint'],
				$config['application-identifier'],
				$config['local-private-key'],
				$config['remote-public-key']
			);
		});

	}

	public function provides(){
		return ['CoreApi'];
	}

}

Add kill condition if php does not have GMP extension installed


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for true Mimic library function.
 *
 * @since 0.1.0
 *
 * @todo Need to use QuickTest library.
 */
class CompareFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(true, 1, 1, true),
			array(true, '1', 1, false),
			array(false, 0, 1, true),
			array(false, '1', 1, true),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\compare
	 */
	public function testResults($expected, $check, $value, $strict) {
		$callback = F\compare($value, $strict);
		$this->assertEquals($expected, $callback($check));
	}
}

<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for true Mimic library function.
 *
 * @since 0.1.0
 *
 * @todo Need to use QuickTest library.
 */
class CompareFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(true, 1, 1, true),
			array(false, 1, true, true),
			array(false, '1', 1, true),
			array(true, '1', 1, false),
			array(false, 0, 1, true),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\compare
	 */
	public function testResults($expected, $check, $value, $strict) {
		$callback = F\compare($value, $strict);
		$this->assertEquals($expected, $callback($check));
	}
}

Add more tests to see where fault is.

Add more tests to see where fault is.


<?php

require_once 'PHPUnit/Framework.php';
require_once 'FeedTests.php';
require_once 'ContentTests.php';
require_once 'Content/AllTests.php';

class Atom10_AllTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0');

        $suite->addTest(Atom10_FeedTests::suite());
        $suite->addTest(Atom10_ContentTests::suite());
        $suite->addTest(Atom10_Content_AllTests::suite());

		return $suite;
	}
}

?>

<?php

require_once 'PHPUnit/Framework.php';
require_once 'FeedTests.php';
require_once 'ContentTests.php';
require_once 'content/AllTests.php';

class Atom10_AllTests
{
	public static function suite()
	{
		$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0');

        $suite->addTest(Atom10_FeedTests::suite());
        $suite->addTest(Atom10_ContentTests::suite());
        $suite->addTest(Atom10_Content_AllTests::suite());

		return $suite;
	}
}

?>

Fix reliance on case-sensitive filesystem


<?php namespace JTGrimes\LaravelDB2;

use Illuminate\Support\ServiceProvider;

class DB2ServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app['db']->extend('db2', function ($config) {
            return new DB2Connection(
                $config['dbname'],
                $config['username'],
                $config['password'],
                $config['db2_options']
            );
        });
    }
}

<?php namespace JTGrimes\LaravelDB2;

use Illuminate\Support\ServiceProvider;

class DB2ServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app['db']->extend('db2', function ($config) {
            return new DB2Connection(
                $config['dbname'],
                $config['username'],
                $config['password'],
                $config['db2_options']
            );
        });
    }

    public function register()
    {
        // nothing to see here.
    }
}

Add missing function in service provider


<?php

namespace FlyingLuscas\BugNotifier\Drivers;

use Illuminate\Support\Facades\Mail;
use FlyingLuscas\BugNotifier\Message;

class MailDriver extends Driver implements DriverInterface
{
    /**
     * Send e-mail message.
     *
     * @param \FlyingLuscas\BugNotifier\Message $message
     *
     * @return void
     */
    public function handle(Message $message)
    {
        $view = $this->config('view');
        $addresses = $this->getEmailAddresses();
        $subject = $message->getTitle();
        $body = $message->getBody();

        Mail::send($view, [
            'body' => $body,
            'subject' => $subject,
        ], function ($mail) use ($subject, $addresses) {
            $mail->subject($subject)->to($addresses);
        });
    }

    /**
     * Get e-mail address list.
     *
     * @return array
     */
    private function getEmailAddresses()
    {
        $address = $this->config('to.address');

        if ($address) {
            return [$address];
        }

        return $this->config('to');
    }
}

<?php

namespace FlyingLuscas\BugNotifier\Drivers;

use Illuminate\Support\Facades\Mail;
use FlyingLuscas\BugNotifier\Message;

class MailDriver extends Driver implements DriverInterface
{
    /**
     * Send e-mail message.
     *
     * @param \FlyingLuscas\BugNotifier\Message $message
     *
     * @return void
     */
    public function handle(Message $message)
    {
        $view = $this->config('view');
        $addresses = $this->getEmailAddresses();
        $subject = $message->getTitle();
        $body = $message->getBody();

        Mail::queue($view, [
            'body' => $body,
            'subject' => $subject,
        ], function ($mail) use ($subject, $addresses) {
            $mail->subject($subject)->to($addresses);
        });
    }

    /**
     * Get e-mail address list.
     *
     * @return array
     */
    private function getEmailAddresses()
    {
        $address = $this->config('to.address');

        if ($address) {
            return [$address];
        }

        return $this->config('to');
    }
}

Make Mail Queueable by default

Make Mail Queueable by default


<?php

namespace CalendarReminder;

interface ReminderRepository
{
    /**
     * @param string $date
     * @param string $content
     * @return Reminder
     */
    public function createReminder(string $date, string $content): Reminder;

    /**
     * @param Reminder $reminder
     */
    public function save(Reminder $reminder);
}

<?php

namespace CalendarReminder;

interface ReminderRepository
{
    /**
     * @param string $date
     * @param string $content
     */
    public function createReminder(string $date, string $content);

    /**
     * @param Reminder $reminder
     */
    public function save(Reminder $reminder);
}

Remove return Reminder object from createReminder


<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DateTimeValidator extends ConstraintValidator
{
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

    public function isValid($value, Constraint $constraint)
    {
        if ($value === null) {
            return true;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string)$value;

        if (!preg_match(self::PATTERN, $value, $matches)) {
            $this->setMessage($constraint->message, array('value' => $value));

            return false;
        }

        return checkdate($matches[2], $matches[3], $matches[1]);
    }
}

<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DateTimeValidator extends ConstraintValidator
{
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

    public function isValid($value, Constraint $constraint)
    {
        if ($value === null) {
            return true;
        }

        if ($value instanceof \DateTime) {
            return true;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string)$value;

        if (!preg_match(self::PATTERN, $value, $matches)) {
            $this->setMessage($constraint->message, array('value' => $value));

            return false;
        }

        return checkdate($matches[2], $matches[3], $matches[1]);
    }
}

[Validator] Allow DateTime objects as valid DateTimes


<?php

class CM_Frontend_EnvironmentTest extends CMTest_TestCase {

    public function testGetters() {
        $site = CM_Site_Abstract::factory();
        $user = CM_Model_User::createStatic();
        $language = CM_Model_Language::create('English', 'en', true);
        $timezone = new DateTimeZone('Europe/London');
        $debug = true;
        $environment = new CM_Frontend_Environment($site, $user, $language, $timezone, $debug);

        $this->assertSame($site, $environment->getSite());
        $this->assertSame($user, $environment->getViewer(true));
        $this->assertSame($language, $environment->getLanguage());
        $this->assertSame($language->getAbbreviation(), $environment->getLocale());
        $this->assertSame($timezone, $environment->getTimeZone());
        $this->assertSame($debug, $environment->isDebug());
    }

    public function testHasViewer() {
        $environment = new CM_Frontend_Environment();
        $this->assertFalse($environment->hasViewer());
        $environment = new CM_Frontend_Environment(null, CM_Model_User::createStatic());
        $this->assertTrue($environment->hasViewer());
    }
}

<?php

class CM_Frontend_EnvironmentTest extends CMTest_TestCase {

    public function testGetters() {
        $site = CM_Site_Abstract::factory();
        $user = CM_Model_User::createStatic();
        $language = CM_Model_Language::create('English', 'en', true);
        $timezone = new DateTimeZone('Europe/London');
        $debug = true;
        $location = CM_Model_Location::createCountry('United Kingdom', 'UK');
        $environment = new CM_Frontend_Environment($site, $user, $language, $timezone, $debug, $location);

        $this->assertSame($site, $environment->getSite());
        $this->assertSame($user, $environment->getViewer(true));
        $this->assertSame($language, $environment->getLanguage());
        $this->assertSame($language->getAbbreviation(), $environment->getLocale());
        $this->assertSame($timezone, $environment->getTimeZone());
        $this->assertSame($debug, $environment->isDebug());
        $this->assertSame($location, $environment->getLocation());
    }

    public function testHasViewer() {
        $environment = new CM_Frontend_Environment();
        $this->assertFalse($environment->hasViewer());
        $environment = new CM_Frontend_Environment(null, CM_Model_User::createStatic());
        $this->assertTrue($environment->hasViewer());
    }
}

Add test for environment location

Add test for environment location


<?php
  require_once 'database.php';

  function rbacCheck($username, $url) {
    $params = [$username, $url];
    $rows = query(
      "SELECT sh_username FROM Shopper
        INNER JOIN AccessUserGroup ON shopper_id = AUG_Shopper_id
        INNER JOIN AccessGroup ON AG_id = AUG_AG_id
        INNER JOIN AccessGroupCommands ON AGC_AG_id = AG_id
        INNER JOIN Commands ON AGC_Cmd_id = Cmd_id
        WHERE sh_username = ?
        AND Cmd_URL = ?", $params);

    return $rows ? true : false;
  }

  function rbacEnforce() {
    if (!isset($_SESSION['username']) ||
        !rbacCheck($_SESSION['username'], basename($_SERVER["PHP_SELF"]))
    ) {
      header('Location: LoginShopper.php');
      exit();
    }
  }
?>

<?php
  require_once 'database.php';

  function rbacCheck($username, $url) {
    $params = [$username, $url];
    $rows = query(
      "SELECT sh_username FROM Shopper
        INNER JOIN AccessUserGroup ON shopper_id = AUG_Shopper_id
        INNER JOIN AccessGroup ON AG_id = AUG_AG_id
        INNER JOIN AccessGroupCommands ON AGC_AG_id = AG_id
        INNER JOIN Commands ON AGC_Cmd_id = Cmd_id
        WHERE sh_username = ?
        AND Cmd_URL = ?", $params);

    return $rows ? true : false;
  }

  function rbacEnforce() {
    if (!isset($_SESSION['username']) ||
        !rbacCheck($_SESSION['username'], basename($_SERVER["PHP_SELF"]))
    ) {
      header('Location: Forbidden.php');
      exit();
    }
  }
?>

Enforce directs non-permitted users to Forbidden.php instead of LoginShopper.php


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Event extends Model
{
    use SoftDeletes;

    protected $dates = [
        'created_at',
        'updated_at',
        'start_time',
        'end_time'
    ];

    /**
     * The attributes that are not mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id', 'created_at', 'updated_at'
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'organizer_name'
    ];

    public function organizer()
    {
        return $this->belongsTo('App\User', 'organizer_id');
    }

    public function rsvps()
    {
        return $this->hasMany('App\Rsvp');
    }

    /**
     * Get all of the event's attendance.
     */
    public function attendance()
    {
        return $this->morphMany('App\Attendance', 'attendable');
    }

    /**
     * Get the Payable amount
     */
    public function getPayableAmount()
    {
        return ($this->price) ?: null;
    }

    /**
     * Get the organizer_name attribute for the model
     */
    public function getOrganizerNameAttribute()
    {
        return $this->organizer->name;
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Event extends Model
{
    use SoftDeletes;

    protected $dates = [
        'created_at',
        'updated_at',
        'start_time',
        'end_time'
    ];

    /**
     * The attributes that are not mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id', 'created_at', 'updated_at', 'organizer_name', 'organizer'
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'organizer_name'
    ];

    public function organizer()
    {
        return $this->belongsTo('App\User', 'organizer_id');
    }

    public function rsvps()
    {
        return $this->hasMany('App\Rsvp');
    }

    /**
     * Get all of the event's attendance.
     */
    public function attendance()
    {
        return $this->morphMany('App\Attendance', 'attendable');
    }

    /**
     * Get the Payable amount
     */
    public function getPayableAmount()
    {
        return ($this->price) ?: null;
    }

    /**
     * Get the organizer_name attribute for the model
     */
    public function getOrganizerNameAttribute()
    {
        return $this->organizer->name;
    }
}

Add organizer_name and organizer to guarded since they're generated, not actually columns


<?php

$schema['feeds'] = array(
    'id' => array('type' => 'int(11)', 'Null'=>'NO', 'Key'=>'PRI', 'Extra'=>'auto_increment'),
    'name' => array('type' => 'text'),
    'userid' => array('type' => 'int(11)'),
    'tag' => array('type' => 'text'),
    'time' => array('type' => 'int(10)'),
    'value' => array('type' => 'float'), // use double for more precision, database space will double
    'datatype' => array('type' => 'int(11)', 'Null'=>'NO'),
    'public' => array('type' => 'tinyint(1)', 'default'=>0),
    'size' => array('type' => 'int(11)'),
    'engine' => array('type' => 'int(11)', 'Null'=>'NO', 'default'=>0),
    'processList' => array('type' => 'text')
);

<?php

$schema['feeds'] = array(
    'id' => array('type' => 'int(11)', 'Null'=>'NO', 'Key'=>'PRI', 'Extra'=>'auto_increment'),
    'name' => array('type' => 'text'),
    'userid' => array('type' => 'int(11)'),
    'tag' => array('type' => 'text'),
    'time' => array('type' => 'int(10)'),
    'value' => array('type' => 'double'),
    'datatype' => array('type' => 'int(11)', 'Null'=>'NO'),
    'public' => array('type' => 'tinyint(1)', 'default'=>0),
    'size' => array('type' => 'int(11)'),
    'engine' => array('type' => 'int(11)', 'Null'=>'NO', 'default'=>0),
    'processList' => array('type' => 'text')
);

Change from 'float' to 'double' to reduce rounding

See discussion http://openenergymonitor.org/emon/node/11774#comment-39508
The imprecision of the float value means that the small increments in the 'power to kWh' process continually get rounded, and therefore never increment.


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Inventory\Model;

class InventoryUnit implements InventoryUnitInterface
{
    /** @var mixed */
    protected $id;

    /** @var StockableInterface|null */
    protected $stockable;

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

    public function getStockable(): ?StockableInterface
    {
        return $this->stockable;
    }

    public function setStockable(StockableInterface $stockable): void
    {
        $this->stockable = $stockable;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Inventory\Model;

class InventoryUnit implements InventoryUnitInterface
{
    /** @var mixed */
    protected $id;

    protected ?StockableInterface $stockable = null;

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

    public function getStockable(): ?StockableInterface
    {
        return $this->stockable;
    }

    public function setStockable(StockableInterface $stockable): void
    {
        $this->stockable = $stockable;
    }
}

Use PHP 7.4 syntax in Sylius components

Use PHP 7.4 syntax in Sylius components


<?php

namespace Orbt\ResourceMirror\Resource;

/**
 * Generic resource containing just a relative path.
 */
class GenericResource implements Resource
{
    /**
     * Resource path.
     * @var string
     */
    protected $path;

    /**
     * Creates a generic resource with a path.
     */
    public function __construct($path)
    {
        $this->path = $path;
    }

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

<?php

namespace Orbt\ResourceMirror\Resource;

/**
 * Generic resource containing just a relative path.
 */
class GenericResource implements Resource
{
    /**
     * Resource path.
     * @var string
     */
    protected $path;

    /**
     * Creates a generic resource with a path.
     */
    public function __construct($path)
    {
        if (!strlen($path)) {
            throw new \InvalidArgumentException('Path must not be empty.');
        }
        if ($path[0] == '/') {
            throw new \InvalidArgumentException('Path must not be absolute.');
        }
        $this->path = rtrim($path, '/');
    }

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

Add checks and trim trailing slash.

Add checks and trim trailing slash.


<?php

namespace PHPCfg\Visitor;

use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;

class CallFinder implements Visitor {

    protected $calls = [];
    protected $funcStack = [];
    protected $func;

    public function getCallsForFunction($func) {
        return isset($this->calls[$func]) ? $this->calls[$func] : [];
    }

    public function enterBlock(Block $block, Block $prior = null) {}

    public function enterOp(Op $op, Block $block) {
        if ($op instanceof Op\CallableOp) {
            $this->funcStack[] = $this->func;
            $this->func = $op;
        }
        if ($op instanceof Op\Expr\FuncCall) {
            if ($op->name instanceof Operand\Literal) {
                $this->calls[$op->name->value][] = [
                    $op,
                    $this->func
                ];
            }
        }
    }

    public function leaveOp(Op $op, Block $block) {
        if ($op instanceof Op\CallableOp) {
            $this->func = array_pop($this->funcStack);
        }
    }

    public function leaveBlock(Block $block, Block $prior = null) {}

    public function skipBlock(Block $block, Block $prior = null) {}

}

<?php

namespace PHPCfg\Visitor;

use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;

class CallFinder implements Visitor {

    protected $calls = [];
    protected $funcStack = [];
    protected $func;

    public function getCallsForFunction($func) {
    	$func = strtolower($func);
        return isset($this->calls[$func]) ? $this->calls[$func] : [];
    }

    public function enterBlock(Block $block, Block $prior = null) {}

    public function enterOp(Op $op, Block $block) {
        if ($op instanceof Op\CallableOp) {
            $this->funcStack[] = $this->func;
            $this->func = $op;
        }
        if ($op instanceof Op\Expr\FuncCall) {
            if ($op->name instanceof Operand\Literal) {
                $this->calls[strtolower($op->name->value)][] = [
                    $op,
                    $this->func
                ];
            }
        }
    }

    public function leaveOp(Op $op, Block $block) {
        if ($op instanceof Op\CallableOp) {
            $this->func = array_pop($this->funcStack);
        }
    }

    public function leaveBlock(Block $block, Block $prior = null) {}

    public function skipBlock(Block $block, Block $prior = null) {}

}

Add support for resolving the types

Add support for resolving the types


<?php

namespace phpSmug\Tests;

/**
 * @class
 * Test properties of our codebase rather than the actual code.
 */
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function testPSR()
    {
        // If we can't find the command-line tool, we mark the test as skipped
        // so it shows as a warning to the developer rather than passing silently.
        if (!file_exists('vendor/bin/php-cs-fixer')) {
            $this->markTestSkipped(
                'Needs linter to check PSR compliance'
            );
        }

        // Let's check all PSR compliance for our code and tests.
        // Add any other pass you want to test to this array.
        foreach (array('lib/', 'examples/', 'test/') as $path) {
            // Run linter in dry-run mode so it changes nothing.
            exec(
                escapeshellcmd('vendor/bin/php-cs-fixer fix -v --dry-run '.$_SERVER['PWD']."/$path"),
                $output,
                $return_var
            );

            // If we've got output, pop its first item ("Fixed all files...")
            // and trim whitespace from the rest so the below makes sense.
            if ($output) {
                array_pop($output);
                $output = array_map('trim', $output);
            }

            // Check shell return code: if nonzero, report the output as a failure.
            $this->assertEquals(
                0,
                $return_var,
                "PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
            );
        }
    }
}

<?php

namespace phpSmug\Tests;

/**
 * @class
 * Test properties of our codebase rather than the actual code.
 */
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function testPSR()
    {
        // If we can't find the command-line tool, we mark the test as skipped
        // so it shows as a warning to the developer rather than passing silently.
        if (!file_exists('vendor/bin/php-cs-fixer')) {
            $this->markTestSkipped(
                'Needs linter to check PSR compliance'
            );
        }

        // Let's check all PSR compliance for our code and tests.
        // Add any other pass you want to test to this array.
        foreach (array('lib/', 'examples/', 'test/') as $path) {
            // Run linter in dry-run mode so it changes nothing.
            exec(
                escapeshellcmd('vendor/bin/php-cs-fixer fix --dry-run '.$_SERVER['PWD']."/$path"),
                $output,
                $return_var
            );

            // If we've got output, pop its first item ("Fixed all files...")
            // and trim whitespace from the rest so the below makes sense.
            if ($output) {
                array_pop($output);
                $output = array_map('trim', $output);
            }

            // Check shell return code: if nonzero, report the output as a failure.
            $this->assertEquals(
                0,
                $return_var,
                "PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
            );
        }
    }
}

Make less verbose as going to try running sep too


<?php

namespace Predis\Commands;

class InfoV24x extends Info {
    public function canBeHashed()  { return false; }
    public function getId() { return 'INFO'; }
    public function parseResponse($data) {
        $info      = array();
        $current   = null;
        $infoLines = explode("\r\n", $data, -1);
        foreach ($infoLines as $row) {
            if ($row === '') {
                continue;
            }
            if (preg_match('/^# (\w+)$/', $row, $matches)) {
                $info[$matches[1]] = array();
                $current = &$info[$matches[1]];
                continue;
            }
            list($k, $v) = explode(':', $row);
            if (!preg_match('/^db\d+$/', $k)) {
                if ($k === 'allocation_stats') {
                    $current[$k] = $this->parseAllocationStats($v);
                    continue;
                }
                $current[$k] = $v;
            }
            else {
                $current[$k] = $this->parseDatabaseStats($v);
            }
        }
        return $info;
    }
}

<?php

namespace Predis\Commands;

class InfoV24x extends Info {
    public function canBeHashed()  { return false; }
    public function parseResponse($data) {
        $info      = array();
        $current   = null;
        $infoLines = explode("\r\n", $data, -1);
        foreach ($infoLines as $row) {
            if ($row === '') {
                continue;
            }
            if (preg_match('/^# (\w+)$/', $row, $matches)) {
                $info[$matches[1]] = array();
                $current = &$info[$matches[1]];
                continue;
            }
            list($k, $v) = explode(':', $row);
            if (!preg_match('/^db\d+$/', $k)) {
                if ($k === 'allocation_stats') {
                    $current[$k] = $this->parseAllocationStats($v);
                    continue;
                }
                $current[$k] = $v;
            }
            else {
                $current[$k] = $this->parseDatabaseStats($v);
            }
        }
        return $info;
    }
}

Remove a useless method declaration.

Remove a useless method declaration.


<?php

namespace GrowthBeatUnOfficial\Tests\GrowthAnalytics;

class ClientTagsTest extends \PHPUnit_Framework_TestCase
{
    public function setup()
    {
    }

    public function testExecuteFail()
    {
        $clientTags    = new \GrowthBeatUnOfficial\GrowthAnalytics\ClientTags("", "", "", "");
        $executeResult = false;
        try {
            $executeResult = $clientTags->execute();
        } catch (\Exception $ex) {
            $executeResult = false;
        } finally {
            $this->assertFalse($executeResult);
        }
    }
}

<?php

namespace GrowthBeatUnOfficial\Tests\GrowthAnalytics;

class ClientTagsTest extends \PHPUnit_Framework_TestCase
{
    public function setup()
    {
    }

    public function testExecuteFail()
    {
        $executeResult = false;
        try {
            $clientTags    = new \GrowthBeatUnOfficial\GrowthAnalytics\ClientTags("", "", "", "");
            $executeResult = $clientTags->execute();
        } catch (\Exception $ex) {
        } finally {
            $this->assertFalse($executeResult);
            return;
        }
    }
}

Fix test case bug.return statement is necessary.


<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Class GoogleSearchMiddleware
 * @package App\Gitter\Middleware
 */
class GoogleSearchMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        $text = $message->escaped_text;

        if (preg_match('/^(@.*?\s)?погугли\s(.*?)$/isu', $text, $matches)) {
            if (!trim($matches[2])) {
                return $message;
            }

            $hasMentions = count($message->mentions) && $message->mentions[0]->login !== \Auth::user()->login;

            $answer = trim($matches[1]) && $hasMentions
                ? \Lang::get('google.personal', [
                    'user' => $message->mentions[0]->login,
                    'query' => urlencode($matches[2])
                  ])
                : \Lang::get('google.common', [
                    'query' => urlencode($matches[2])
                  ]);

            $message->answer($answer);
        }

        return $message;
    }
}

<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Class GoogleSearchMiddleware
 * @package App\Gitter\Middleware
 */
class GoogleSearchMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        $text = $message->escaped_text;

        if (preg_match('/^(@.*?\s)?(?:погугли|гугли)\s(.*?)$/isu', $text, $matches)) {
            if (!trim($matches[2])) {
                return $message;
            }

            $hasMentions = count($message->mentions) && $message->mentions[0]->login !== \Auth::user()->login;

            $answer = trim($matches[1]) && $hasMentions
                ? \Lang::get('google.personal', [
                    'user' => $message->mentions[0]->login,
                    'query' => urlencode($matches[2])
                ])
                : \Lang::get('google.common', [
                    'query' => urlencode($matches[2])
                ]);

            $message->answer($answer);
        }

        return $message;
    }
}

Add "гугли" google search query

Add "гугли" google search query


<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\TaxRate;
use App\ReprocessedMaterial;
use Illuminate\Support\Facades\Log;

class UpdateOreValues implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Grab all tax rate records, and all stored current values for materials (keyed by id).
        $tax_rates = TaxRate::all();
        $material_values = ReprocessedMaterial::select('materialTypeID', 'average_price')->get()->keyBy('materialTypeID');

        // Loop through the rates, calculating the total value per unit of ore.
        foreach ($tax_rates as $rate)
        {
            $total_unit_cost = 0;
            $materials = $rate->reprocessed_materials;

            foreach ($materials as $material)
            {
                $total_unit_cost += $material_values[$material->materialTypeID]->average_price * ($material->quantity * 0.9);
            }
            $rate->value = $total_unit_cost / 100;
            $rate->save();
            Log::info('UpdateOreValues: calculated and saved unit cost for ore ' . $rate->type_id);
        }
    }
}

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\TaxRate;
use App\ReprocessedMaterial;
use Illuminate\Support\Facades\Log;

class UpdateOreValues implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Grab all tax rate records, and all stored current values for materials (keyed by id).
        $tax_rates = TaxRate::all();
        $material_values = ReprocessedMaterial::select('materialTypeID', 'average_price')->get()->keyBy('materialTypeID');

        // Loop through the rates, calculating the total value per unit of ore.
        foreach ($tax_rates as $rate)
        {
            $total_unit_cost = 0;
            $materials = $rate->reprocessed_materials;

            foreach ($materials as $material)
            {
                $total_unit_cost += $material_values[$material->materialTypeID]->average_price * ($material->quantity * 0.86);
            }
            $rate->value = $total_unit_cost / 100;
            $rate->save();
            Log::info('UpdateOreValues: calculated and saved unit cost for ore ' . $rate->type_id);
        }
    }
}

Reduce reprocessing factor from 90% to 86%.


<?php
require_once(__DIR__.'/classes/task.class.php');

$tasks = [];

// Load tasks from json
$tasks_arr = json_decode(file_get_contents('tasks.json'), true);
foreach ($tasks_arr as $task_arr) {
	$task = new Task($task_arr);
	$tasks[] = $task;
}

// Run tasks
while (true) {
	foreach ($tasks as $task) {
		if (!$task->isRunning() && $task->shouldRun()) {
			$task->run();
		}
	}

	echo 'Mem: '.number_format(memory_get_usage())."\n";
	sleep(1);
}

<?php
require_once(__DIR__.'/classes/task.class.php');

$tasks = [];

// Load tasks from json
$tasks_arr = json_decode(file_get_contents(__DIR__.'/tasks.json'), true);
foreach ($tasks_arr as $task_arr) {
	$task = new Task($task_arr);
	$tasks[] = $task;
}

// Run tasks
while (true) {
	foreach ($tasks as $task) {
		if (!$task->isRunning() && $task->shouldRun()) {
			$task->run();
		}
	}

	echo 'Mem: '.number_format(memory_get_usage())."\n";
	sleep(1);
}

Read self dir for config

Read self dir for config


<?php
/*
	pwm Password Manager
	Copyright Owen Maule 2015
	o@owen-m.com
	https://github.com/owenmaule/pwm

	License: GNU Affero General Public License v3

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/agpl.html>.

	---
	Initially developed on PHP version: 5.3.3-7+squeeze
*/

try
{
	require_once 'pwm.php';

	$pwm = new pwm();

	if( $pwm->authentication() )
	{
		$pwm->passwordManager();
	}
}
catch ( Exception $e )
{
	$pwm->alert( $e->getMessage(), ALERT_ERROR );
	# die( 'Error: ' . $e->getMessage() );
}

$pwm->render();

<?php
/*
	pwm Password Manager
	Copyright Owen Maule 2015
	o@owen-m.com
	https://github.com/owenmaule/pwm

	License: GNU Affero General Public License v3

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/agpl.html>.

	---
	Initially developed on PHP version: 5.3.3-7+squeeze
*/

try
{
	require_once 'pwm.php';

	$pwm = new pwm();

	if( $pwm->authentication() )
	{
		$pwm->passwordManager();
	}
}
catch ( Exception $e )
{
	if( is_object( $pwm ) )
	{
		$pwm->alert( $e->getMessage(), ALERT_ERROR );
	} else {
		die( 'Error: ' . $e->getMessage() );
	}
}

$pwm->render();

Handle exceptions without app instantiated


<?php

namespace MinePlus\VoterBundle;

class VoteDispatcher
{

    protected $voters;

    public function hasVoters()
    {
        // An empty array cast's into false
        return (boolean) $this->voters;
    }

    public function addVoter($eventName, $voter, $multiplicator)
    {
        $this->voters[$eventName][$multiplicator][] = $voter;
    }

    public function decide($eventName, $event)
    {
        return ($this->getLevel($eventName, $event) <= 0) ? false : true;
    }

    public function getLevel($eventName, $event)
    {
        $level = 0;

        if (!array_key_exists($eventName, $this->voters))
            return $level;

        $voters = $this->voters[$eventName];

        foreach ($voters as $multiplicator => $votersArray) {
            foreach ($votersArray as $voter) {
                $returnedLevel = call_user_func($voter, $event);

                $level = $level + $returnedLevel * $multiplicator;
            }
        }
    }

}

?>

<?php

namespace MinePlus\VoterBundle;

class VoteDispatcher
{

    protected $voters;

    public function hasVoters()
    {
        // An empty array cast's into false
        return (boolean) $this->voters;
    }

    public function addVoter($eventName, $voter, $multiplicator)
    {
        $this->voters[$eventName][$multiplicator][] = $voter;
    }

    public function decide($eventName, $event)
    {
        return ($this->getLevel($eventName, $event) <= 0) ? false : true;
    }

    public function getLevel($eventName, $event)
    {
        $level = 0;

        if (!array_key_exists($eventName, $this->voters))
            return $level;

        $voters = $this->voters[$eventName];

        foreach ($voters as $multiplicator => $votersArray) {
            foreach ($votersArray as $voter) {
                $returnedLevel = call_user_func($voter, $event);

                $level = $level + $returnedLevel * $multiplicator;
            }
        }

        return $level;
    }

}

?>

Fix level not returned in getLevel().

Fix level not returned in getLevel().


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Dashboard;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->orderRepository = $orderRepository;
        $this->customerRepository = $customerRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
    {
        return new DashboardStatistics(
            $this->orderRepository->getTotalSalesForChannel($channel),
            $this->orderRepository->countFulfilledByChannel($channel),
            $this->customerRepository->count()
        );
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Dashboard;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->orderRepository = $orderRepository;
        $this->customerRepository = $customerRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
    {
        return new DashboardStatistics(
            $this->orderRepository->getTotalSalesForChannel($channel),
            $this->orderRepository->countFulfilledByChannel($channel),
            $this->customerRepository->countCustomers()
        );
    }
}

[Customer][Core] Rename DashboardStatistic customers count() method to countCustomers()


<?php namespace Dashboard;

use Illuminate\Support\ServiceProvider;

class DashboardServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }

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

}

<?php namespace Onderdelen\Dashboard;

use Illuminate\Support\ServiceProvider;

class DashboardServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }

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

}

Update ServiceProvider & build tools

Update ServiceProvider & build tools


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Extension;

use Flarum\Foundation\AbstractServiceProvider;
use Illuminate\Contracts\Container\Container;

class ExtensionServiceProvider extends AbstractServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register()
    {
        $this->app->singleton(ExtensionManager::class);
        $this->app->alias(ExtensionManager::class, 'flarum.extensions');

        $this->app->booting(function (Container $app) {
            $app->make('flarum.extensions')->extend($app);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $events = $this->app->make('events');

        $events->subscribe(DefaultLanguagePackGuard::class);
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Extension;

use Flarum\Foundation\AbstractServiceProvider;
use Illuminate\Contracts\Container\Container;

class ExtensionServiceProvider extends AbstractServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register()
    {
        $this->app->singleton(ExtensionManager::class);
        $this->app->alias(ExtensionManager::class, 'flarum.extensions');

        // Boot extensions when the app is booting. This must be done as a boot
        // listener on the app rather than in the service provider's boot method
        // below, so that extensions have a chance to register things on the
        // container before the core boot code runs.
        $this->app->booting(function (Container $app) {
            $app->make('flarum.extensions')->extend($app);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $events = $this->app->make('events');

        $events->subscribe(DefaultLanguagePackGuard::class);
    }
}

Add comment explaining extension boot process


<?php

namespace Surfnet\SamlBundle\Tests\SAML2;

use PHPUnit_Framework_TestCase as UnitTest;
use Surfnet\SamlBundle\SAML2\AuthnRequest;
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
use Symfony\Component\HttpFoundation\Request;

class AuthnRequestFactoryTest extends UnitTest
{
    /**
     * @test
     * @group saml2
     *
     * @expectedException \Surfnet\SamlBundle\Http\Exception\InvalidRequestException
     * @expectedExceptionMessage Failed decoding the request, did not receive a valid base64 string
     */
    public function an_exception_is_thrown_when_a_request_is_not_properly_base64_encoded()
    {
        // the $ is invalid since it is outside the base64 alphabet and we deserialize in strict mode.
        $request = new Request([AuthnRequest::PARAMETER_REQUEST => '$']);

        AuthnRequestFactory::createFromHttpRequest($request);
    }

    /**
     * @test
     * @group                    saml2
     *
     * @expectedException \Surfnet\SamlBundle\Http\Exception\InvalidRequestException
     * @expectedExceptionMessage Failed inflating the request;
     */
    public function an_exception_is_thrown_when_a_request_cannot_be_inflated()
    {
        // the $ is invalid since it is outside the base64 alphabet and we deserialize in strict mode.
        $request = new Request([AuthnRequest::PARAMETER_REQUEST => base64_encode('nope, not deflated')]);

        AuthnRequestFactory::createFromHttpRequest($request);
    }
}

<?php

namespace Surfnet\SamlBundle\Tests\SAML2;

use PHPUnit_Framework_TestCase as UnitTest;
use Surfnet\SamlBundle\SAML2\AuthnRequest;
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
use Symfony\Component\HttpFoundation\Request;

class AuthnRequestFactoryTest extends UnitTest
{
    /**
     * @test
     * @group saml2
     *
     * @expectedException \Surfnet\SamlBundle\Http\Exception\InvalidRequestException
     * @expectedExceptionMessage Failed decoding the request, did not receive a valid base64 string
     */
    public function an_exception_is_thrown_when_a_request_is_not_properly_base64_encoded()
    {
        // the $ is invalid since it is outside the base64 alphabet and we deserialize in strict mode.
        $request = new Request([AuthnRequest::PARAMETER_REQUEST => '$']);

        AuthnRequestFactory::createFromHttpRequest($request);
    }

    /**
     * @test
     * @group saml2
     *
     * @expectedException \Surfnet\SamlBundle\Http\Exception\InvalidRequestException
     * @expectedExceptionMessage Failed inflating the request;
     */
    public function an_exception_is_thrown_when_a_request_cannot_be_inflated()
    {
        $request = new Request([AuthnRequest::PARAMETER_REQUEST => base64_encode('nope, not deflated')]);

        AuthnRequestFactory::createFromHttpRequest($request);
    }
}

Align docblock, remove wrong comment

Align docblock, remove wrong comment


<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');

// Init owncloud

// Check if we are a user
OCP\User::checkLoggedIn();

$files = $_GET["files"];
$dir = $_GET["dir"];

$files_list = json_decode($files);

// in case we get only a single file
if ($files_list === NULL || $files_list === true || $files_list === false) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');

// Init owncloud

// Check if we are a user
OCP\User::checkLoggedIn();

$files = $_GET["files"];
$dir = $_GET["dir"];

$files_list = json_decode($files);
// in case we get only a single file
if ($files_list === NULL ) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

Revert "FIX: Download of files named "true" or "false" impossible"

This reverts commit d2d71c8797f7e7b51e55bec4217738faaf6a08ca.
which was accidentally commited