<?php

namespace Nwidart\Modules\Process;

class Updater extends Runner
{
    /**
     * Update the dependencies for the specified module by given the module name.
     *
     * @param string $module
     */
    public function update($module)
    {
        $module = $this->module->findOrFail($module);

        $packages = $module->getComposerAttr('require', []);

        chdir(base_path());

        foreach ($packages as $name => $version) {
            $package = "\"{$name}:{$version}\"";

            $this->run("composer require {$package}");
        }
    }
}

<?php

namespace Nwidart\Modules\Process;

class Updater extends Runner
{
    /**
     * Update the dependencies for the specified module by given the module name.
     *
     * @param string $module
     */
    public function update($module)
    {
        $module = $this->module->findOrFail($module);

        $packages = $module->getComposerAttr('require', []);

        chdir(base_path());

        foreach ($packages as $name => $version) {
            $package = "\"{$name}:{$version}\"";

            $this->run("composer require {$package}");
        }

        $devPackages = $module->getComposerAttr('require-dev', []);
        foreach ($devPackages as $name => $version) {
            $package = "\"{$name}:{$version}\"";
            $this->run("composer require --dev {$package}");
        }
    }
}

Allow ability to add require-dev packages from module to the main composer.json file


<?php

namespace FaizShukri\Quran\Supports;

class Config
{
    private $config;

    public function __construct(array $config = [])
    {
        $this->config = $this->buildConfig($config);
    }

    /**
     * Build a config array. Merge user defined config with our default config.
     *
     * @param array $config User defined config
     *
     * @return array New configuration array
     */
    private function buildConfig(array $config = [])
    {
        // Merge our config with user config
        $result = array_replace_recursive((include realpath(__DIR__.'/../../config/quran.php')), $config);

        // If function storage_path is exist (laravel), we update the path to laravel's storage path
        if (function_exists('storage_path') && php_sapi_name() !== 'cli') {
            $result['storage_path'] = storage_path('app'.DIRECTORY_SEPARATOR.$result['storage_path']);
        }

        return $result;
    }

    /**
     * Get the config variable.
     *
     * @param string $val Variable name
     *
     * @return array|string Variable value
     */
    public function get($val)
    {
        $configs = explode('.', $val);
        $first = $this->config[array_shift($configs)];

        foreach ($configs as $config) {
            $first = $first[$config];
        }

        return $first;
    }

    /**
     * Return all configurations.
     *
     * @return array
     */
    public function all()
    {
        return $this->config;
    }
}

<?php

namespace FaizShukri\Quran\Supports;

class Config
{
    private $config;

    public function __construct(array $config = [])
    {
        $this->config = $this->buildConfig($config);
    }

    /**
     * Build a config array. Merge user defined config with our default config.
     *
     * @param array $config User defined config
     *
     * @return array New configuration array
     */
    private function buildConfig(array $config = [])
    {
        // Merge our config with user config
        $result = array_replace_recursive((include realpath(__DIR__.'/../../config/quran.php')), $config);

        // If function storage_path is exist (laravel), we update the path to laravel's storage path
        if (function_exists('storage_path') && php_sapi_name() !== 'cli') {
            $result['storage_path'] = storage_path('app/' . $result['storage_path']);
        } else {
            $result['storage_path'] = realpath(__DIR__ . '/../..') . '/' . $result['storage_path'];
        }

        return $result;
    }

    /**
     * Get the config variable.
     *
     * @param string $val Variable name
     *
     * @return array|string Variable value
     */
    public function get($val)
    {
        $configs = explode('.', $val);
        $first = $this->config[array_shift($configs)];

        foreach ($configs as $config) {
            $first = $first[$config];
        }

        return $first;
    }

    /**
     * Return all configurations.
     *
     * @return array
     */
    public function all()
    {
        return $this->config;
    }
}

Fix destination be at current directory

Fix destination be at current directory


<?php

namespace Ncmb;

/**
 * Role - Representation of an access Role.
 */
class Role extends Object
{
    public static $ncmbClassName = 'role';
    public static $apiPath = 'roles';

    /**
     * Create a Role object with a given name and ACL.
     *
     * @param string $name
     * @param \Ncmb\Acl|null $acl
     *
     * @return \Ncmb\Role
     */
    public static function createRole($name, $acl = null)
    {
        $role = new self(self::$ncmbClassName);
        $role->setName($name);
        if ($acl) {
            $role->setAcl($acl);
        }

        return $role;
    }

    /**
     * Get path string
     * @return string path string
     */
    public function getApiPath()
    {
        return self::$apiPath;
    }

    /**
     * Returns the role name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->get('roleName');
    }

    /**
     * Sets the role name.
     *
     * @param string $name The role name
     * @throws \Ncmb\Exception
     */
    public function setName($name)
    {
        if ($this->getObjectId()) {
            throw new Exception(
                "A role's name can only be set before it has been saved.");
        }
        if (!is_string($name)) {
            throw new Exception("A role's name must be a string.");
        }
        return $this->set('roleName', $name);
    }
}

<?php

namespace Ncmb;

/**
 * Role - Representation of an access Role.
 */
class Role extends Object
{
    const NCMB_CLASS_NAME = 'role';
    const API_PATH = 'roles';

    /**
     * Create a Role object with a given name and ACL.
     *
     * @param string $name
     * @param \Ncmb\Acl|null $acl
     *
     * @return \Ncmb\Role
     */
    public static function createRole($name, $acl = null)
    {
        $role = new self(self::NCMB_CLASS_NAME);
        $role->setName($name);
        if ($acl) {
            $role->setAcl($acl);
        }

        return $role;
    }

    /**
     * Get path string
     * @return string path string
     */
    public function getApiPath()
    {
        return self::API_PATH;
    }

    /**
     * Returns the role name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->get('roleName');
    }

    /**
     * Sets the role name.
     *
     * @param string $name The role name
     * @throws \Ncmb\Exception
     */
    public function setName($name)
    {
        if ($this->getObjectId()) {
            throw new Exception(
                "A role's name can only be set before it has been saved.");
        }
        if (!is_string($name)) {
            throw new Exception("A role's name must be a string.");
        }
        return $this->set('roleName', $name);
    }
}

Change ncmbClassName,apiPath to class constants.


<?php
namespace Gt\Database\Query;

class QueryFactoryTest extends \PHPUnit_Framework_TestCase {

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
 */
public function testFindQueryFilePathExists(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
	$this->assertFileExists($queryFilePath);
}

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathNotExistsProvider
 * @expectedException \Gt\Database\Query\QueryNotFoundException
 */
public function testFindQueryFilePathNotExists(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathExtensionNotValidProvider
 * @expectedException \Gt\Database\Query\QueryNotFoundException
 */
public function testFindQueryFilePathWithInvalidExtension(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}

}#

<?php
namespace Gt\Database\Query;

class QueryFactoryTest extends \PHPUnit_Framework_TestCase {

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
 */
public function testFindQueryFilePathExists(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
	$this->assertFileExists($queryFilePath);
}

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathNotExistsProvider
 * @expectedException \Gt\Database\Query\QueryNotFoundException
 */
public function testFindQueryFilePathNotExists(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathExtensionNotValidProvider
 * @expectedException \Gt\Database\Query\QueryNotFoundException
 */
public function testFindQueryFilePathWithInvalidExtension(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$queryFilePath = $queryFactory->findQueryFilePath($queryName);
}

/**
 * @dataProvider \Gt\Database\Test\Helper::queryPathExistsProvider
 */
public function testQueryCreated(
string $queryName, string $directoryOfQueries) {
	$queryFactory = new QueryFactory($directoryOfQueries);
	$query = $queryFactory->create($queryName);
	$this->assertInstanceOf(
		"\Gt\Database\Query\QueryInterface",
		$query
	);
}

}#

Test query is actually created.

Test query is actually created.


has('image') ? 'has-error' : '' }}">
    {{ trans('general.image_upload') }}

            {{ trans('button.select_file')  }}
            <input type="file" name="image" id="uploadFile" data-maxsize="{{ \App\Helpers\Helper::file_upload_max_size() }}" accept="image/gif,image/jpeg,image/png,image/svg" style="display:none">

{{ trans('general.image_filetypes_help', ['size' => \App\Helpers\Helper::file_upload_max_size_readable()]) }}

        {!! $errors->first('image', ':message') !!}

Use full row width for image field

Use full row width for image field


<?php

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

use Flarum\Akismet\Listener;
use Flarum\Approval\Event\PostWasApproved;
use Flarum\Extend;
use Flarum\Post\Event\Hidden;
use Flarum\Post\Event\Saving;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use TijsVerkoyen\Akismet\Akismet;

return [
    (new Extend\Frontend('forum'))
        ->js(__DIR__.'/js/dist/forum.js'),

    (new Extend\Frontend('admin'))
        ->js(__DIR__.'/js/dist/admin.js'),

    new Extend\Locales(__DIR__.'/locale'),

    function (Dispatcher $events, Container $container) {
        $container->bind(Akismet::class, function ($app) {
            $settings = $app->make(SettingsRepositoryInterface::class);

            return new Akismet(
                $settings->get('flarum-akismet.api_key'),
                $app->url()
            );
        });

        $events->listen(Saving::class, Listener\ValidatePost::class);
        $events->listen(PostWasApproved::class, Listener\SubmitHam::class);
        $events->listen(Hidden::class, Listener\SubmitSpam::class);
    },
];

<?php

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

use Flarum\Akismet\Listener;
use Flarum\Approval\Event\PostWasApproved;
use Flarum\Extend;
use Flarum\Http\UrlGenerator;
use Flarum\Post\Event\Hidden;
use Flarum\Post\Event\Saving;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use TijsVerkoyen\Akismet\Akismet;

return [
    (new Extend\Frontend('forum'))
        ->js(__DIR__.'/js/dist/forum.js'),

    (new Extend\Frontend('admin'))
        ->js(__DIR__.'/js/dist/admin.js'),

    new Extend\Locales(__DIR__.'/locale'),

    function (Dispatcher $events, Container $container) {
        $container->bind(Akismet::class, function ($app) {
            /** @var SettingsRepositoryInterface $settings */
            $settings = $app->make(SettingsRepositoryInterface::class);
            /** @var UrlGenerator $url */
            $url = $app->make(UrlGenerator::class);

            return new Akismet(
                $settings->get('flarum-akismet.api_key'),
                $url->to('forum')->base()
            );
        });

        $events->listen(Saving::class, Listener\ValidatePost::class);
        $events->listen(PostWasApproved::class, Listener\SubmitHam::class);
        $events->listen(Hidden::class, Listener\SubmitSpam::class);
    },
];

Replace leftover app()->url() with UrlGenerator


<?php

namespace BisonLab\SakonninBundle\Lib\Sakonnin;

/*
 */

class MailForward
{

    protected $container;
    protected $router;

    public function __construct($container, $options = array())
    {
        $this->container = $container;
    }

    /* You may call this lazyness, jkust having an options array, but it's also
     * more future proof. */
    public function execute($options = array())
    {
        $message = $options['message'];

        $router = $this->getRouter();
        $url = $router->generate('message_show', array('id' => $message->getId()), true);
        // Not gonna do html, yet at least..
        // $body = 'Link to this message' . "\n\n";
        $body = "Link to this message: " . $url  . "\n\n";
        $body .= $message->getBody();

        $mail = \Swift_Message::newInstance()
        ->setSubject($message->getSubject())
        ->setFrom($message->getFrom())
        ->setTo(implode(",", $options['attributes']))
        ->setBody($body,
            'text/plain'
        ) ;
        $this->container->get('mailer')->send($mail);

        return true;
    }

    public function getRouter()
    {
        if (!$this->router) {
            $this->router = $this->container->get('router');
        }
        return $this->router;
    }

}

<?php

namespace BisonLab\SakonninBundle\Lib\Sakonnin;

/*
 */

class MailForward
{

    protected $container;
    protected $router;

    public function __construct($container, $options = array())
    {
        $this->container = $container;
    }

    /* You may call this lazyness, jkust having an options array, but it's also
     * more future proof. */
    public function execute($options = array())
    {
        $message = $options['message'];

        $router = $this->getRouter();
        $url = $router->generate('message_show', array('id' => $message->getId()), true);
        // Not gonna do html, yet at least..
        // $body = 'Link to this message' . "\n\n";
        $body = "Link to this message: " . $url  . "\n\n";
        $body .= $message->getBody();

        $mail = \Swift_Message::newInstance()
        ->setSubject($message->getSubject())
        ->setFrom($message->getFrom())
        ->setTo($options['attributes'])
        ->setBody($body,
            'text/plain'
        ) ;
        $this->container->get('mailer')->send($mail);

        return true;
    }

    public function getRouter()
    {
        if (!$this->router) {
            $this->router = $this->container->get('router');
        }
        return $this->router;
    }

}

Read the docs, setTo takes an array of addresses, which is the right way to do it, not implode it with commas.


<?php

namespace Swarrot\SwarrotBundle\Event;

use Swarrot\Broker\Message;

class MessagePublishedEvent extends SymfonyEvent
{
    const NAME = 'swarrot.message_published';

    private $messageType;
    private $message;
    private $connection;
    private $exchange;
    private $routingKey;

    public function __construct(string $messageType, Message $message, string $connection, string $exchange, string $routingKey)
    {
        $this->messageType = $messageType;
        $this->message = $message;
        $this->connection = $connection;
        $this->exchange = $exchange;
        $this->routingKey = $routingKey;
    }

    public function getMessageType(): string
    {
        return $this->messageType;
    }

    public function getMessage(): Message
    {
        return $this->message;
    }

    public function getConnection(): string
    {
        return $this->connection;
    }

    public function getExchange(): string
    {
        return $this->exchange;
    }

    public function getRoutingKey(): string
    {
        return $this->routingKey;
    }
}

<?php

namespace Swarrot\SwarrotBundle\Event;

use Swarrot\Broker\Message;

class MessagePublishedEvent extends SymfonyEvent
{
    const NAME = 'swarrot.message_published';

    private $messageType;
    private $message;
    private $connection;
    private $exchange;
    private $routingKey;

    public function __construct(string $messageType, Message $message, string $connection, string $exchange, ?string $routingKey)
    {
        $this->messageType = $messageType;
        $this->message = $message;
        $this->connection = $connection;
        $this->exchange = $exchange;
        $this->routingKey = $routingKey;
    }

    public function getMessageType(): string
    {
        return $this->messageType;
    }

    public function getMessage(): Message
    {
        return $this->message;
    }

    public function getConnection(): string
    {
        return $this->connection;
    }

    public function getExchange(): string
    {
        return $this->exchange;
    }

    public function getRoutingKey(): ?string
    {
        return $this->routingKey;
    }
}

Fix compatibility with null as routing key


<?php

require_once __DIR__.'/../../init.php';

//var_dump($_SERVER);exit;

$configPath = __DIR__.'/../../config/config.json';
$configService = new Ric_Server_Config($configPath);
$api = new Ric_Server_Api(
    new Ric_Server_Server($configService),
    new Ric_Server_Auth_Service($configService->getConfig()));
$api->handleRequest();

<?php

require_once __DIR__.'/../../../init.php';

//var_dump($_SERVER);exit;

$configPath = __DIR__.'/../../../config/config.json';
$configService = new Ric_Server_Config($configPath);
$api = new Ric_Server_Api(
    new Ric_Server_Server($configService),
    new Ric_Server_Auth_Service($configService->getConfig()));
$api->handleRequest();

Fix pathes to init and config file

Fix pathes to init and config file


<?php

require_once('../../../www/_include.php');

$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();

SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');

if (!$config->getValue('enable.saml20-idp', false)) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}

if (!isset($_GET['RelayState'])) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

$returnTo = $_GET['RelayState'];

/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'saml2/idp/SingleLogoutService.php',
	array('ReturnTo' => $returnTo));

?>

<?php

require_once('../../../www/_include.php');

$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();

SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout');

if (!$config->getValue('enable.saml20-idp', false)) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}

if (!isset($_GET['RelayState'])) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

$returnTo = $_GET['RelayState'];

$slo = $metadata->getGenerated('SingleLogoutService', 'saml20-idp-hosted');

/* We turn processing over to the SingleLogoutService script. */
SimpleSAML_Utilities::redirect($slo, array('ReturnTo' => $returnTo));

?>

SAML2: Support metadata overrides of SingleLogoutService for IdP initiated SLO.


<?php

namespace SSRadio\Common;

class Tracklist {

	public function __construct() {
	}

	public static function from_arp_json() {
		$tracklist = new Tracklist;

		// TODO: Process JSON

		return $tracklist;
	}
}

<?php

namespace SSRadio\Common;

class Tracklist {

	public function __construct() {
	}

	public static function from_arp_json( $json ) {

		$tracklist = new Tracklist;

		$arp_data = json_decode( $json );

		if ( is_object( $arp_data ) && isset( $arp_data->results ) && ! empty( $arp_data->results ) ) {

			foreach ( $arp_data->results as $result ) {
				// TODO: Process ARP results
			}
		}

		return $tracklist;
	}
}

Check JSON data is valid.

Check JSON data is valid.


<?php namespace TightenCo\Jigsaw\Collection;

use Symfony\Component\Yaml\Yaml;
use TightenCo\Jigsaw\Parsers\FrontMatterParser;

class CollectionRemoteItem
{
    private $item;
    private $index;
    private $prefix;

    public function __construct($item, $index, $collectionName = null)
    {
        $this->item = $item;
        $this->index = $index;
        $this->prefix = $collectionName . '_';
    }

    public function getContent()
    {
        return is_array($this->item) ?
            $this->getHeader() . array_get($this->item, 'content') :
            $this->item;
    }

    public function getFilename()
    {
        return array_get($this->item, 'filename', $this->prefix . ($this->index + 1)) . '.md';
    }

    protected function getHeader()
    {
        $yaml = Yaml::dump(collect($this->item)->except('content')->toArray());

        return $yaml ? "---\n" . $yaml . "---\n" : null;
    }
}

<?php namespace TightenCo\Jigsaw\Collection;

use Symfony\Component\Yaml\Yaml;
use TightenCo\Jigsaw\Parsers\FrontMatterParser;

class CollectionRemoteItem
{
    private $item;
    private $index;
    private $prefix;

    public function __construct($item, $index, $collectionName = null)
    {
        $this->item = $item;
        $this->index = $index;
        $this->prefix = $collectionName . '_';
    }

    public function getContent()
    {
        return is_array($this->item) ?
            $this->getHeader() . array_get($this->item, 'content') :
            $this->item;
    }

    public function getFilename()
    {
        return array_get($this->item, 'filename', $this->prefix . ($this->index + 1)) . '.md';
    }

    protected function getHeader()
    {
        $variables = collect($this->item)->except('content')->toArray();

        return count($variables) ? "---\n" . Yaml::dump($variables) . "---\n" : null;
    }
}

Fix output of remote collection items that lack YAML variables


<?php
class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract
{
    public function __construct()
    {
        $providers = array();
        $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_JsClassKwf();
        $providers[] = new Kwf_Assets_Provider_IniNoFiles();
        $providers[] = new Kwf_Assets_Provider_ExtTrl();
        $providers[] = new Kwf_Assets_Provider_DefaultAssets();
        $providers[] = new Kwf_Assets_Provider_ErrorHandler();
        $providers[] = new Kwf_Assets_TinyMce_Provider();
        $providers[] = new Kwf_Assets_Provider_BowerBuiltFile(VENDOR_PATH.'/bower_components/jquery');
        parent::__construct($providers);
    }
}

<?php
class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract
{
    public function __construct()
    {
        $providers = array();
        $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini');
        $providers[] = new Kwf_Assets_Provider_JsClassKwf();
        $providers[] = new Kwf_Assets_Provider_IniNoFiles();
        $providers[] = new Kwf_Assets_Provider_Dynamic();
        $providers[] = new Kwf_Assets_Provider_ExtTrl();
        $providers[] = new Kwf_Assets_Provider_DefaultAssets();
        $providers[] = new Kwf_Assets_Provider_ErrorHandler();
        $providers[] = new Kwf_Assets_TinyMce_Provider();
        $providers[] = new Kwf_Assets_Provider_BowerBuiltFile(VENDOR_PATH.'/bower_components/jquery');
        parent::__construct($providers);
    }
}

Add missing dependency provider for KwfDynamicAssetsVersion


<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class UserScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if (auth()->check()) {
            $builder->where('user_id', request()->user()->id);
        }
    }
}

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class UserScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if (auth()->check()) {
            $builder->where(
                'user_id',
                session()->has('imposter_id')
                    ? session()->get('imposter_id')
                    : request()->user()->id
            );
        }
    }
}

Fix user scope working when impersonating other users


<?php
/**
 *
 * @author newloki
 */
namespace Language\Languages\Indo\English;
use Language\Languages\Indo\IndoAbstract,
    Language\Languages\LanguagesException;

require_once realpath(__DIR__) . '/../IndoAbstract.php';

abstract class EnglishAbstract extends IndoAbstract
{
    /**
     * Name of this language
     * @var string
     */
    protected $_name = 'english_abstract';

    /**
     * constructor for english languages, not called in this class, but in his
     * childs
     * @return void
     */
    public function __construct()
    {
        //in english Y is almost an vocal
        try {
            $this->replaceInCVMapping('y', IndoAbstract::VOCAL);
        } catch(LanguagesException $e) {
            throw new LanguagesException('Can\'t create ' . $this->_name, $e);
        }
    }
}

<?php
/**
 *
 * @author newloki
 */
namespace Language\Languages\Indo\English;
use Language\Languages\Indo\IndoAbstract,
    Language\Languages\LanguagesException;

require_once realpath(__DIR__) . '/../IndoAbstract.php';

abstract class EnglishAbstract extends IndoAbstract
{
    /**
     * Name of this language
     * @var string
     */
    protected $_name = 'english_abstract';

    /**
     * constructor for english languages, not called in this class, but in his
     * childs
     * @return void
     */
    public final function __construct()
    {
        //in english Y is almost an vocal
        try {
            $this->replaceInCVMapping('y', IndoAbstract::VOCAL);
        } catch(LanguagesException $e) {
            throw new LanguagesException('Can\'t create ' . $this->_name, $e);
        }
    }
}

Make constructor final to prevent overriding in child class


<?php

declare(strict_types=1);

namespace Paraunit\Process;

use Paraunit\Configuration\EnvVariables;
use Paraunit\Configuration\PHPUnitConfig;
use Paraunit\Configuration\TempFilenameFactory;
use Symfony\Component\Process\Process;

/**
 * Class ProcessFactory
 * @package Paraunit\Process
 */
class ProcessFactory
{
    /** @var CommandLine */
    private $cliCommand;

    /** @var string[] */
    private $baseCommandLine;

    /** @var string[] */
    private $environmentVariables;

    /**
     * ProcessFactory constructor.
     * @param CommandLine $cliCommand
     * @param PHPUnitConfig $phpunitConfig
     * @param TempFilenameFactory $tempFilenameFactory
     */
    public function __construct(
        CommandLine $cliCommand,
        PHPUnitConfig $phpunitConfig,
        TempFilenameFactory $tempFilenameFactory
    ) {
        $this->cliCommand = $cliCommand;
        $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig));
        $this->environmentVariables = [
            EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(),
        ];
    }

    public function create(string $testFilePath): AbstractParaunitProcess
    {
        $process = new Process(
            array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)),
            null,
            $this->environmentVariables
        );
        $process->inheritEnvironmentVariables();

        return new SymfonyProcessWrapper($process, $testFilePath);
    }
}

<?php

declare(strict_types=1);

namespace Paraunit\Process;

use Paraunit\Configuration\EnvVariables;
use Paraunit\Configuration\PHPUnitConfig;
use Paraunit\Configuration\TempFilenameFactory;
use Symfony\Component\Process\Process;

/**
 * Class ProcessFactory
 * @package Paraunit\Process
 */
class ProcessFactory
{
    /** @var CommandLine */
    private $cliCommand;

    /** @var string[] */
    private $baseCommandLine;

    /** @var string[] */
    private $environmentVariables;

    /**
     * ProcessFactory constructor.
     * @param CommandLine $cliCommand
     * @param PHPUnitConfig $phpunitConfig
     * @param TempFilenameFactory $tempFilenameFactory
     */
    public function __construct(
        CommandLine $cliCommand,
        PHPUnitConfig $phpunitConfig,
        TempFilenameFactory $tempFilenameFactory
    ) {
        $this->cliCommand = $cliCommand;
        $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig));
        $this->environmentVariables = [
            EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(),
        ];
    }

    public function create(string $testFilePath): AbstractParaunitProcess
    {
        $process = new Process(
            array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)),
            null,
            $this->environmentVariables
        );

        if (method_exists($process, 'inheritEnvironmentVariables')) {
            // method added in 3.0
            $process->inheritEnvironmentVariables();
        }

        return new SymfonyProcessWrapper($process, $testFilePath);
    }
}

Fix failure with Symfony 2.8

Fix failure with Symfony 2.8


<?php

namespace NotificationChannels\ExpoPushNotifications\Repositories;

use ExponentPhpSDK\ExpoRepository;
use NotificationChannels\ExpoPushNotifications\Models\Interest;

class ExpoDatabaseDriver implements ExpoRepository
{
    /**
     * Stores an Expo token with a given identifier
     *
     * @param $key
     * @param $value
     *
     * @return bool
     */
    public function store($key, $value): bool
    {
        $interest = Interest::firstOrCreate([
            'key' => $key,
            'value' => $value
        ]);

        return $interest instanceof Interest;
    }

    /**
     * Retrieves an Expo token with a given identifier
     *
     * @param string $key
     *
     * @return string|null
     */
    public function retrieve(string $key)
    {
        $interest = Interest::where('key', $key)->first();

        if($interest instanceof Interest)
        {
            return (string) $interest->value;
        }

        return null;
    }

    /**
     * Removes an Expo token with a given identifier
     *
     * @param string $key
     *
     * @return bool
     */
    public function forget(string $key): bool
    {
        return Interest::where('key', $key)->delete();
    }
}

<?php

namespace NotificationChannels\ExpoPushNotifications\Repositories;

use ExponentPhpSDK\ExpoRepository;
use NotificationChannels\ExpoPushNotifications\Models\Interest;

class ExpoDatabaseDriver implements ExpoRepository
{
    /**
     * Stores an Expo token with a given identifier
     *
     * @param $key
     * @param $value
     *
     * @return bool
     */
    public function store($key, $value): bool
    {
        $interest = Interest::firstOrCreate([
            'key' => $key,
            'value' => $value
        ]);

        return $interest instanceof Interest;
    }

    /**
     * Retrieves an Expo token with a given identifier
     *
     * @param string $key
     *
     * @return string|null
     */
    public function retrieve(string $key)
    {
        return Interest::where('key', $key)->pluck('value')->toArray();
    }

    /**
     * Removes an Expo token with a given identifier
     *
     * @param string $key
     *
     * @return bool
     */
    public function forget(string $key): bool
    {
        return Interest::where('key', $key)->delete();
    }
}

Return array of retrieved values to support multiple tokens per user


<?php

namespace App\Http\Controllers;

use App\Mail\Contact;
use App\Ticket;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class AppController extends Controller
{

    public function index(){
        $places=Ticket::MAX_TICKETS-Ticket::all()->count();
        $canBuy=Ticket::canBuy();
        return view('index', compact('places', 'canBuy'));
    }

    public function contact(Request $r)
    {
        $r->validate([
            'email' => 'required|email',
            'name' => 'required',
            'message' => 'required'
        ]);
        Mail::to('lenaic@lenaic.me')->send(new Contact($r->name, $r->email, $r->message));
        return redirect('/');
    }

    public function isMember(Request $r){
        $r->validate([
            'email' => 'required|email'
        ]);
        return User::hasTheLowPrice($r->email);
    }
}

<?php

namespace App\Http\Controllers;

use App\Mail\Contact;
use App\Ticket;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class AppController extends Controller
{

    public function index()
    {
        $places = Ticket::MAX_TICKETS - Ticket::all()->count();
        $canBuy = Ticket::canBuy();
        return view('index', compact('places', 'canBuy'));
    }

    public function contact(Request $r)
    {
        $r->validate([
            'email' => 'required|email',
            'name' => 'required',
            'message' => 'required'
        ]);
        Mail::to('lenaic@lenaic.me')->send(new Contact($r->name, $r->email, $r->message));
        return redirect('/');
    }

    public function isMember(Request $r)
    {
        $r->validate([
            'email' => 'required|email'
        ]);
        $low = User::hasTheLowPrice($r->email);
        return $low === false ? 0 : $low;
    }
}

Correct bug with lowPrice method

Correct bug with lowPrice method


<?php

namespace App\Models;

trait Transformable
{

    public function transform(array $requestedFields = null)
    {
        $transformer = app('Resources')->getTransformerForModel(get_called_class());

        // WEB-1953: Set $isRestricted to false here; index all fields
        return (new $transformer(null, false, false))->transform($this);
    }

    /**
     * Jury-rig a connection to the transformer class.
     *
     * @return array
     */
    protected function transformMapping()
    {
        $transformerClass = app('Resources')->getTransformerForModel(get_called_class());

        $fields = (new $transformerClass())->getMappedFields();

        // TODO: Fix references to transformMapping to use keys instead of 'name'
        foreach ($fields as $fieldName => $fieldMapping) {
            $fields[$fieldName]['name'] = $fieldName;
        }

        return $fields;
    }
}

<?php

namespace App\Models;

trait Transformable
{

    public function transform(array $requestedFields = null)
    {
        $transformer = app('Resources')->getTransformerForModel(get_called_class());

        // WEB-1953: Set $isRestricted to false here; index all fields
        return (new $transformer(null, false, false))->transform($this);
    }

    /**
     * Jury-rig a connection to the transformer class.
     *
     * @return array
     */
    protected function transformMapping()
    {
        $transformerClass = app('Resources')->getTransformerForModel(get_called_class());

        // include `is_restricted` fields
        $fields = (new $transformerClass(null, null, false))->getMappedFields();

        // TODO: Fix references to transformMapping to use keys instead of 'name'
        foreach ($fields as $fieldName => $fieldMapping) {
            $fields[$fieldName]['name'] = $fieldName;
        }

        return $fields;
    }
}

Include restricted fields in Elasticsearch mapping [WEB-2399]


<?php
$count = 0;
$pool = new SplQueue();
$server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);

$server->on('Request', function($request, $response) use(&$count, $pool) {
    if (count($pool) == 0) {
        $redis = new Swoole\Coroutine\Redis();
        $res = $redis->connect('127.0.0.1', 6379);
        if ($res == false) {
            $response->end("redis connect fail!");
            return;
        }
        $pool->push($redis);
    }
    $redis = $pool->pop();
    $count ++;
    $ret = $redis->set('key', 'value');
    $response->end("swoole response is ok, count = $count, result=" . var_export($ret, true));
    $pool->push($redis);
});

$server->start();

<?php
$count = 0;
$pool = new SplQueue();
$server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);

$server->on('Request', function($request, $response) use(&$count, $pool) {
    if (count($pool) == 0) {
        $redis = new Swoole\Coroutine\Redis();
        $res = $redis->connect('127.0.0.1', 6379);
        if ($res == false) {
            $response->end("redis connect fail!");
            return;
        }
        $pool->enqueue($redis);
    }
    $redis = $pool->dequeue();
    $count ++;
    $ret = $redis->set('key', 'value');
    $response->end("swoole response is ok, count = $count, result=" . var_export($ret, true));
    $pool->enqueue($redis);
});

$server->start();

Fix unexpected swoole sever crash on high concurrency operation

`SplQueue` is operated using `enqueue()` and `dequeue()` not with `push()` and `pop()` which is for `Stack`.

`SplQueue` is a `FIFO`, but use of `push/pop` turns it into `Stack` which is `LIFO`, this has caused numerous disconnections that resulted into a swoole server crash.

By fixing this, disconnection from database server does not cause server crash anymore.

Ref.

[SplQueue dequeue](http://php.net/manual/en/splqueue.dequeue.php)
[SplQueue enqueue](http://php.net/manual/en/splqueue.enqueue.php)


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Calculator {

    function send($submitText, $calcType) {
        // prepare for a curl call
        $fields = array(
            'requesting_ip' => getRealIp(),
            'mlmfile' => 'al_be_' . $calcType . '_many_v22',
            'text_block' => $submitText,
        );

        $options = array(
            CURLOPT_POST => count($fields),
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_POSTFIELDS => http_build_query($fields),
            CURLOPT_CONNECTTIMEOUT => 90,
            CURLOPT_TIMEOUT => 200,
        );

        // send the request with curl
        $ch = curl_init(CRONUS_URI);
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        if (!$result) {
            die('Error retrieving calculator result:<br>' . curl_error($ch));
        }

        curl_close($ch);
        $rep = '<head><base href="' . CRONUS_BASE . '" />';
        $html = str_replace('<head>', $rep, $result);
        return $html;
    }

}

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

define('CRONUS_BASE', 'http://hess.ess.washington.edu/');
define('CRONUS_URI', CRONUS_BASE . 'cgi-bin/matweb');

class Calculator {

    function send($submitText, $calcType) {
        // prepare for a curl call
        $fields = array(
            'requesting_ip' => getRealIp(),
            'mlmfile' => 'al_be_' . $calcType . '_many_v22',
            'text_block' => $submitText,
        );

        $options = array(
            CURLOPT_POST => count($fields),
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_POSTFIELDS => http_build_query($fields),
            CURLOPT_CONNECTTIMEOUT => 90,
            CURLOPT_TIMEOUT => 200,
        );

        // send the request with curl
        $ch = curl_init(CRONUS_URI);
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        if (!$result) {
            die('Error retrieving calculator result:<br>' . curl_error($ch));
        }

        curl_close($ch);
        $rep = '<head><base href="' . CRONUS_BASE . '" />';
        $html = str_replace('<head>', $rep, $result);
        return $html;
    }

}

Fix missing constants for CRONUS calculator


<?php

namespace Jstewmc\Rtf\Element\Control\Symbol;

/**
 * The apostrophe control symbol ("\'hh") is used to represent a non-ASCII
 * character from a Windows Code Page. The two digits "hh" are a hexadecimal
 * value for the given character on the given code page.
 *
 * The current code page is specified by the "\ansicpg" control word.
 */
class Apostrophe extends Symbol
{
    public function __construct(string $parameter)
    {
        parent::__construct('\'', $parameter);
    }

    protected function toHtml(): string
    {
        // parameter is hexadecimal number
        return "&#x{$this->parameter};";
    }

    protected function toText(): string
    {
        return html_entity_decode($this->toHtml());
    }
}

Remove whitespace at end of line

Remove whitespace at end of line


<?php
namespace Ayeo\Parser\Utils;

class Camelizer
{
    function camelize($scored)
    {
        return lcfirst(implode('',array_map('ucfirst', array_map('strtolower', explode('_', $scored)))));
    }
}

<?php
namespace Ayeo\Parser\Utils;

class Camelizer
{
    public function camelize($scored)
    {
        return lcfirst(implode('',array_map('ucfirst', array_map('strtolower', explode('_', $scored)))));
    }
}

Make camalize method explictily public

Make camalize method explictily public


<?php do_action( 'it_exchange_content_licenses_before_wrap' ); ?>

	<?php do_action( 'it_exchange_content_licenses_begin_wrap' ); ?>
	<?php it_exchange_get_template_part( 'messages' ); ?>
	<?php it_exchange( 'customer', 'menu' ); ?>

	<?php if ( it_exchange( 'licenses', 'has-licenses' ) ) : ?>

				<?php it_exchange_get_template_part( 'content-licenses/elements/licenses-list-header' ); ?>

				<?php it_exchange_get_template_part( 'content-licenses/loops/licenses' ); ?>

	<?php else : ?>
		<?php it_exchange_get_template_part( 'content-licenses/elements/no-licenses-found' ); ?>
	<?php endif; ?>
	<?php do_action( 'it_exchange_content_licenses_end_wrap' ); ?>

<?php do_action( 'it_exchange_content_licenses_after_wrap' ); ?>

Add wrapper element to licenses acct page


<?php namespace Blindern\UKA\Billett;

class Ticketgroup extends \Eloquent {
    protected $model_suffix = '';
    protected $table = 'ticketgroups';

    protected $apiAllowedFields = array('id', 'event_id', 'is_active', 'is_published', 'is_normal', 'title', 'ticket_text', 'price', 'fee', 'limit');
    protected $apiAllowedRelations = array('event', 'tickets');

    public function getPriceAttribute($val) {
        return (float) $val;
    }

    public function getFeeAttribute($val) {
        return (float) $val;
    }

    public function tickets()
    {
        return $this->hasMany('\\Blindern\\UKA\\Billett\\Ticket'.$this->model_suffix, 'ticketgroup_id');
    }

    public function event()
    {
        return $this->belongsTo('\\Blindern\\UKA\\Billett\\Event'.$this->model_suffix, 'event_id');
    }

    /**
     * Check if there tickets associated that are not expired
     */
    public function getHasTicketsAttribute()
    {
        $res = $this->tickets()->where(function($query) {
            $query->whereNull('expire')->orWhere('expire', '>=', time());
        })->first();

        return (bool) $res;
    }

    /**
     * Get fields we can search in
     */
    public function getApiAllowedFields() {
        return $this->apiAllowedFields;
    }

    /**
     * Get fields we can use as relations
     */
    public function getApiAllowedRelations() {
        return $this->apiAllowedRelations;
    }
}

<?php namespace Blindern\UKA\Billett;

class Ticketgroup extends \Eloquent {
    protected $model_suffix = '';
    protected $table = 'ticketgroups';

    protected $apiAllowedFields = array('id', 'event_id', 'is_active', 'is_published', 'is_normal', 'title', 'ticket_text', 'price', 'fee', 'limit', 'order');
    protected $apiAllowedRelations = array('event', 'tickets');

    public function getPriceAttribute($val) {
        return (float) $val;
    }

    public function getFeeAttribute($val) {
        return (float) $val;
    }

    public function tickets()
    {
        return $this->hasMany('\\Blindern\\UKA\\Billett\\Ticket'.$this->model_suffix, 'ticketgroup_id');
    }

    public function event()
    {
        return $this->belongsTo('\\Blindern\\UKA\\Billett\\Event'.$this->model_suffix, 'event_id');
    }

    /**
     * Check if there tickets associated that are not expired
     */
    public function getHasTicketsAttribute()
    {
        $res = $this->tickets()->where(function($query) {
            $query->whereNull('expire')->orWhere('expire', '>=', time());
        })->first();

        return (bool) $res;
    }

    /**
     * Get fields we can search in
     */
    public function getApiAllowedFields() {
        return $this->apiAllowedFields;
    }

    /**
     * Get fields we can use as relations
     */
    public function getApiAllowedRelations() {
        return $this->apiAllowedRelations;
    }
}

Add 'order' to allowed API-fields for ticketgroups


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

function verifyCredentials()
{
    Log::info('Verifying credentials');
    $user = DB::table('users')->where('name', 'John')->first();
    throw new Exception('No credentials passed!');
}

function authenticateUser()
{
    Log::info('Authenticating the current user');
    verifyCredentials();
}

Route::get('/', function () {
    Log::info('Rendering a page thats about to error');
    authenticateUser();
})->name('index');

Route::get('/welcome/{id}', 'HomeController@showWelcome')->name('welcome');

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

function verifyCredentials($username, $password)
{
    Log::info('Verifying credentials');
    $user = DB::table('users')->where('name', $username)->first();
    // in the real world, we'd have some logic here
    throw new Exception('Invalid password!');
}

function authenticateUser()
{
    Log::info('Authenticating the current user');
    verifyCredentials('jane_doe99', 'fizzbuzz');
}

Route::get('/', function () {
    Log::info('Rendering a page thats about to error');
    authenticateUser();
})->name('index');

Route::get('/welcome/{id}', 'HomeController@showWelcome')->name('welcome');

Improve 5.4 example error path

Improve 5.4 example error path


<?php

class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {

    public function getHtml($zoneData, array $variables) {
        $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
        $variables = $this->_variableKeysToUnderscore($variables);
        $variables['key'] = '2ea5b261f06ca771033a5fa9e22493f1';

        $html = '

';
        return $html;
    }

    private function _variableKeysToUnderscore($variables) {
        foreach ($variables as $key => $value) {
            unset ($variables[$key]);
            $underscoreKey = str_replace('-', '_', $key);
            $variables[$underscoreKey] = $value;
        }
        return $variables;
    }
}

<?php

class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {

    /**
     * @return string
     */
    private function _getAccessKey() {
        return self::_getConfig()->accessKey;
    }

    public function getHtml($zoneData, array $variables) {
        $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
        $variables = $this->_variableKeysToUnderscore($variables);
        $variables['key'] = $this->_getAccessKey();

        $html = '

';
        return $html;
    }

    private function _variableKeysToUnderscore($variables) {
        foreach ($variables as $key => $value) {
            unset ($variables[$key]);
            $underscoreKey = str_replace('-', '_', $key);
            $variables[$underscoreKey] = $value;
        }
        return $variables;
    }
}

Move epom key to config.

Move epom key to config.


<?php

use ToniPeric\Oib;

class OibTest extends PHPUnit_Framework_TestCase
 {
     /**
      * @test
      */
     function it_validates_a_single_oib()
     {
         $this->assertEquals(true, Oib::validate(71481280786));
     }

    /**
     * @test
     */
    function it_invalidates_a_single_oib()
    {
        $this->assertEquals(false, Oib::validate('foo'));
    }

    /**
     * @test
     */
    public function it_validates_an_array_of_oibs()
    {
        $oibs = [71481280786, 64217529143, 'foo'];

        $this->assertEquals([$oibs[0] => true, $oibs[1] => true, $oibs[2] => false], Oib::validate($oibs));
    }
 }

<?php

use ToniPeric\Oib;

class OibTest extends PHPUnit_Framework_TestCase
 {
     /**
      * @test
      */
     function it_validates_a_single_oib()
     {
         $this->assertEquals(true, Oib::validate(71481280786));
     }

    /**
     * @test
     */
    function it_invalidates_a_single_oib()
    {
        $this->assertEquals(false, Oib::validate('foo'));
    }

    /**
     * @test
     */
    public function it_validates_an_array_of_oibs()
    {
        $oibs = array(71481280786, 64217529143, 'foo');

        $this->assertEquals(array($oibs[0] => true, $oibs[1] => true, $oibs[2] => false), Oib::validate($oibs));
    }
 }

Change shorthand array syntax to pre-5.4


<?php
namespace Helmich\MongoMock\Assert;

use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;

class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{

    /** @var array */
    private $filter;

    /** @var array */
    private $options;

    public function __construct($filter, $options = [])
    {
        parent::__construct();
        $this->filter = $filter;
        $this->options = $options;
    }

    protected function matches($other)
    {
        if (!$other instanceof MockCollection) {
            return false;
        }

        $ref = new Query($this->filter, $this->options);
        foreach ($other->queries as $query) {
            if ($query == $ref) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'executed query by ' . json_encode($this->filter);
    }
}

<?php
namespace Helmich\MongoMock\Assert;

use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;

class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{

    /** @var array */
    private $filter;

    /** @var array */
    private $options;

    public function __construct($filter, $options = [])
    {
        parent::__construct();
        $this->filter = $filter;
        $this->options = $options;
    }

    protected function matches($other)
    {
        if (!$other instanceof MockCollection) {
            return false;
        }

        $constraint = \PHPUnit_Framework_Assert::equalTo(new Query($this->filter, $this->options));

        foreach ($other->queries as $query) {
            if ($constraint->evaluate($query, '', true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'executed query by ' . json_encode($this->filter);
    }
}

Use PHPUnit's equality constraint for query assertion


<?php namespace Gchaincl\LaravelFragmentCaching;

class ViewServiceProvider extends \Illuminate\View\ViewServiceProvider
{
    protected $defered = false;

    public function register()
    {
        parent::register();
        $this->registerEnvironment();
        $this->registerBladeExtensions();
    }

    public function registerEnvironment()
    {
        $this->app->bindShared('view', function($app) {
            $resolver = $app['view.engine.resolver'];
            $finder = $app['view.finder'];
            $env = new Factory($resolver, $finder, $app['events']);

            $env->setContainer($app);
            $env->share('app', $app);

            return $env;
        });
    }

    protected function registerBladeExtensions()
    {
        $blade = $this->app['view']
            ->getEngineResolver()
            ->resolve('blade')
            ->getCompiler();

        $blade->extend(function($view, $compiler) {
            $pattern = $compiler->createMatcher('cache');
            return preg_replace($pattern, '$1' . $this->cacheTemplate(), $view);
        });

        $blade->extend(function($view, $compiler) {
            $pattern = $compiler->createPlainMatcher('endcache');
            return preg_replace($pattern, '$1<?php }); ?>', $view);
        });

    }

    private function cacheTemplate()
    {
        return <<<'EOF'
<?php
$__fc_vars = get_defined_vars();
echo $__env->cache($2, function() use($__fc_vars) {
    extract($__fc_vars);

    // Cached Content goes below this

?>
EOF;
    }
}

<?php namespace Gchaincl\LaravelFragmentCaching;

class ViewServiceProvider extends \Illuminate\View\ViewServiceProvider
{
    protected $defered = false;

    public function register()
    {
        parent::register();
        $this->registerEnvironment();
        $this->registerBladeExtensions();
    }

    public function registerEnvironment()
    {
        $this->app->bindShared('view', function($app) {
            $resolver = $app['view.engine.resolver'];
            $finder = $app['view.finder'];
            $env = new Factory($resolver, $finder, $app['events']);

            $env->setContainer($app);
            $env->share('app', $app);

            return $env;
        });
    }

    protected function registerBladeExtensions()
    {
        $blade = $this->app['view']
            ->getEngineResolver()
            ->resolve('blade')
            ->getCompiler();

        $blade->extend(function($view, $compiler) {
            $pattern = $compiler->createMatcher('cache');
            return preg_replace($pattern, '$1' . $this->cacheTemplate(), $view);
        });

        $blade->extend(function($view, $compiler) {
            $pattern = $compiler->createPlainMatcher('endcache');
            return preg_replace($pattern, '$1<?php }); ?>', $view);
        });

    }

    private function cacheTemplate()
    {
        return <<<'EOF'
<?php
$__fc_vars = get_defined_vars();
echo $__env->cache($2, $3, function() use($__fc_vars) {
    extract($__fc_vars);

    // Cached Content goes below this

?>
EOF;
    }
}

Add an optional second parameter to cache, used to conditionaly enable/disable caching


<?php

namespace Raffle;

final class RandomServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var RandomService
     */
    private $service;

    public function setUp()
    {
        $this->service = new RandomService();
    }

    public function test_amount_of_random_numbers_returned()
    {
        $numbers = $this->service->getRandomNumbers(10);
        $this->assertCount(10, $numbers);
    }

    public function test_list_of_random_numbers_are_unique()
    {
        $numbers = $this->service->getRandomNumbers(10);
        $uniqueNumbers = array_unique($numbers);
        $this->assertSame($numbers, $uniqueNumbers);
    }
}

<?php

namespace Raffle;

final class RandomServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var RandomService
     */
    private $service;

    public function setUp()
    {
        $this->service = new RandomService();
    }

    public function test_amount_of_random_numbers_returned()
    {
        $numbers = $this->service->getRandomNumbers(10);
        $this->assertCount(10, $numbers);
    }

    public function test_list_of_random_numbers_are_unique()
    {
        $numbers = $this->service->getRandomNumbers(10);
        $uniqueNumbers = array_unique($numbers);
        $this->assertSame($numbers, $uniqueNumbers);
    }

    public function test_list_is_empty_when_amount_zero()
    {
        // The service should not return any numbers if the amount is zero
        $this->assertEmpty($this->service->getRandomNumbers(0));
    }

    public function test_list_includes_zero()
    {
        // The service should return _all_ numbers for $amount in random order
        $this->assertContains(0, $this->service->getRandomNumbers(1));
        $this->assertContains(0, $this->service->getRandomNumbers(2));
    }
}

Add more tests for RandomService

Add more tests for RandomService


<?php

namespace Ornamental\Sender;

class Phpmailer implements \Ornamental\Sender
{
    public $smtpHost;
    public $smtpUsername;
    public $smtpPassword;
    public $smtpSecure;
    public $smtpPort = 25;

    public function send($message)
    {
        $mail = new \PHPMailer();

        if ($this->smtpHost) {
            $mail->isSMTP();
            $mail->Host = $this->smtpHost;
            $mail->Port = $this->smtpPort;
            $mail->SMTPAuth = true;
            $mail->Username = $this->smtpUsername;
            $mail->Password = $this->smtpPassword;
            $mail->SMTPSecure = $this->smtpSecure;
        }

        $mail->From = $message->from;
        $mail->FromName = $message->fromName;
        $mail->AddAddress($message->to);

        $mail->isHTML(true);
        $mail->Subject = $message->subject;
        $mail->Body    = $message->renderHtml();
        $mail->AltBody = $message->renderText();
        $mail->send();
    }
}

<?php

namespace Ornamental\Sender;

class Phpmailer implements \Ornamental\Sender
{
    public $smtpHost;
    public $smtpUsername;
    public $smtpPassword;
    public $smtpSecure;
    public $smtpPort = 25;

    public function send($message)
    {
        $mail = new \PHPMailer();

        if ($this->smtpHost) {
            $mail->isSMTP();
            $mail->Host = $this->smtpHost;
            $mail->Port = $this->smtpPort;
            $mail->SMTPAuth = true;
            $mail->Username = $this->smtpUsername;
            $mail->Password = $this->smtpPassword;
            $mail->SMTPSecure = $this->smtpSecure;
        }

        $mail->From = $message->from;
        $mail->FromName = $message->fromName;
        foreach (explode(',', $message->to) as $email) {
            $mail->AddAddress($email);
        }

        $mail->isHTML(true);
        $mail->Subject = $message->subject;
        $mail->Body    = $message->renderHtml();
        $mail->AltBody = $message->renderText();
        $mail->send();
    }
}

Allow a string of multiple emails in message `to` field.


<?php

namespace HbgEventImporter;

class Location extends \HbgEventImporter\Entity\PostManager
{
    public $post_type = 'location';

    public function afterSave()
    {
        $res = Helper\Address::gmapsGetAddressComponents($this->postalAddress . ' ' . $this->postcode . ' ' . $this->city . ' ' . $this->country);

        if (!isset($res->geometry->location)) {
            return;
        }

        update_post_meta($this->ID, 'map', array(
            'address' => $res->formatted_address,
            'lat' => $res->geometry->location->lat,
            'lng' => $res->geometry->location->lng
        ));

        update_post_meta($this->ID, 'formatted_address', $res->formatted_address);
    }
}

<?php

namespace HbgEventImporter;

class Location extends \HbgEventImporter\Entity\PostManager
{
    public $post_type = 'location';

    public function afterSave()
    {
        $res = Helper\Address::gmapsGetAddressComponents($this->postal_address . ' ' . $this->postal_code . ' ' . $this->city . ' ' . $this->country);

        if (!isset($res->geometry->location)) {
            return;
        }

        update_post_meta($this->ID, 'map', array(
            'address' => $res->formatted_address,
            'lat' => $res->geometry->location->lat,
            'lng' => $res->geometry->location->lng
        ));

        update_post_meta($this->ID, 'formatted_address', $res->formatted_address);
    }
}

Use correct fields for address formatting


<?php
namespace tomlib\object;

function try_get_property($object, $name, $default = null) {
		if(property_exists($object, $name))
				return $object->$name;
		else
				return $default;
}

function to_indexed_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[$property] =& try_get_property($object, $property);
				}
		} else {
				foreach($properties as $property) {
						$result[$property] = try_get_property($object, $property);
				}
		}

		return $result;
}

function to_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[] =& try_get_property($object, $property);
				}
		} else {
				foreach($properties as $property) {
						$result[] = try_get_property($object, $property);
				}
		}

		return $result;
}

<?php
namespace tomlib\object;

function try_get_property($object, $name, $default = null) {
		if(property_exists($object, $name))
				return $object->$name;
		else
				return $default;
}

function to_indexed_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[$property] = $object->$property;
				}
		} else {
				foreach($properties as $property) {
						$result[$property] = $object->$property;
				}
		}

		return $result;
}

function to_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[] =& $object->$property;
				}
		} else {
				foreach($properties as $property) {
						$result[] = $object->$property;
				}
		}

		return $result;
}

Replace try_get_property with property access


<?php
namespace Lio\Exceptions;

use Auth;
use Bugsnag;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Bugsnag\BugsnagLaravel\BugsnagExceptionHandler as ExceptionHandler;

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

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        // If a user is logged in, we'll set him as the target user for which the errors will occur.
        if (Auth::check()) {
            Bugsnag::setUser([
                'name' => Auth::user()->name,
                'email' => Auth::user()->email,
            ]);
        }

        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

<?php
namespace Lio\Exceptions;

use Bugsnag;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Bugsnag\BugsnagLaravel\BugsnagExceptionHandler as ExceptionHandler;

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

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        // If a user is logged in, we'll set him as the target user for which the errors will occur.
        if (auth()->check()) {
            Bugsnag::setUser([
                'name' => auth()->user()->name,
                'email' => auth()->user()->email,
            ]);
        }

        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

Use helpers instead of facade

Use helpers instead of facade


<?php

namespace Kohana\Sentinel;

use Cartalyst\Sentinel\Native\SentinelBootstrapper;
use Kohana;

class SentinelFactory
{
    /**
     * @var SentinelBootstrapper
     */
    private $bootstrapper;

    public function __construct()
    {
        $config = Kohana::$config->load('sentinel')->get('config');

        $this->bootstrapper = new SentinelBootstrapper($config);
    }

    /**
     * @return \Cartalyst\Sentinel\Sentinel
     */
    public function create()
    {
        return $this->bootstrapper->createSentinel();
    }
}

<?php

namespace Kohana\Sentinel;

use Cartalyst\Sentinel\Native\SentinelBootstrapper;
use Kohana;

class SentinelFactory
{
    /**
     * @var null|array
     */
    private $config;

    public function __construct()
    {
        $this->config = Kohana::$config->load('sentinel')->get('config');
    }

    /**
     * @return \Cartalyst\Sentinel\Sentinel
     */
    public function create()
    {
        return (new SentinelBootstrapper($this->config))->createSentinel();
    }
}

Enable users to bootstrap sentinel after kohana initialization


<?php

/*
Plugin Name: Allow Forward Slashes in Short URLs
Plugin URI: http://williambargent.co.uk
Description: Allow Forward Slashes in Short URLs
Version: 1.0
Author: William Bargent
*/

if( !defined( 'YOURLS_ABSPATH' ) ) die();

yourls_add_filter( 'get_shorturl_charset', 'slash_in_charset' );
function slash_in_charset( $in ) {
        return $in.'/';
}

//This plugin will not work with URL forwarding plugins active

<?php

/*
Plugin Name: Allow Forward Slashes in Short URLs
Plugin URI: http://williambargent.co.uk
Description: Allow Forward Slashes in Short URLs
Version: 1.0
Author: William Bargent
Author URI: http://williambargent.co.uk
*/

if( !defined( 'YOURLS_ABSPATH' ) ) die();

yourls_add_filter( 'get_shorturl_charset', 'slash_in_charset' );
function slash_in_charset( $in ) {
        return $in.'/';
}

//This plugin will not work with URL forwarding plugins active

Add Author URI instead HTML

Add Author URI instead HTML

HTML code in Plugin info block, breaks the markup.


<?php
/**
 * PlumSearch plugin for CakePHP Rapid Development Framework
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Evgeny Tomenko
 * @since         PlumSearch 0.1
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace PlumSearch\Test\App\Model\Filter;

use Cake\Database\Expression\UnaryExpression;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use PlumSearch\Model\Filter\AbstractFilter;

class TagsFilter extends AbstractFilter
{
    /**
     * Returns query with applied filter
     *
     * @param \Cake\ORM\Query $query Query.
     * @param string $field Field name.
     * @param string $value Field value.
     * @param array $data Filters values.
     * @return \Cake\ORM\Query
     */
    protected function _buildQuery(Query $query, $field, $value, array $data = [])
    {
        // @todo bind to parent Articles.id using initialization parameter
        $alias = $query->repository()->alias();

        $tags = TableRegistry::get('ArticlesTags')->find('all')
        ->matching('Tags', function ($q) use ($value, $alias) {
            return $q->where([
                'Tags.name' => $value,
                "ArticlesTags.article_id = $alias.id",
            ]);
        });

        return $query
        ->where([new UnaryExpression('EXISTS', $tags)]);
    }
}

<?php
/**
 * PlumSearch plugin for CakePHP Rapid Development Framework
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Evgeny Tomenko
 * @since         PlumSearch 0.1
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace PlumSearch\Test\App\Model\Filter;

use Cake\Database\Expression\UnaryExpression;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use PlumSearch\Model\Filter\AbstractFilter;

class TagsFilter extends AbstractFilter
{
    /**
     * Returns query with applied filter
     *
     * @param \Cake\ORM\Query $query Query.
     * @param string $field Field name.
     * @param string $value Field value.
     * @param array $data Filters values.
     * @return \Cake\ORM\Query
     */
    protected function _buildQuery(Query $query, $field, $value, array $data = [])
    {
        // @todo bind to parent Articles.id using initialization parameter
        $alias = $query->repository()->alias();

        $tags = TableRegistry::get('ArticlesTags')->find('all')
        ->matching('Tags', function ($q) use ($value, $alias) {
            return $q->where([
                'Tags.name' => $value,
            ]);
        })
        ->where([
            "ArticlesTags.article_id = $alias.id"
        ]);

        return $query
        ->where([new UnaryExpression('EXISTS', $tags)]);
    }
}

Rework condition on cutom filter example


<?php

namespace App\Console\Commands;

use Elasticsearch;

use App\Console\Helpers\Indexer;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class SearchReindex extends BaseCommand
{

    use Indexer;

    protected $signature = 'search:reindex
                            {dest : The prefix of the indexes to copy documents to}
                            {source? : The prefix of the indexes to copy documents from}';

    protected $description = 'Copy documents from one set of indices to another';

    public function handle()
    {

        $dest = $this->argument('dest');
        $source = $this->argument('source') ?? env('ELASTICSEARCH_INDEX');

        $models = app('Search')->getSearchableModels();

        foreach ($models as $model)
        {

            $endpoint = app('Resources')->getEndpointForModel($model);
            $index = $source . '-' . $endpoint;

            $params = [
                'wait_for_completion' => false,
                'body' => [
                    'source' => [
                        'index' => $index,
                        'size' => 100,
                    ],
                    'dest' => [
                        'index' => $dest . '-' . $endpoint,
                    ],
                ],
            ];

            $return = Elasticsearch::reindex($params);

            $this->info('Reindex from ' . $index . 'has started. You can monitor the process here: ' . $this->baseUrl() . '/_tasks/' . $return['task']);

        }

    }

}

<?php

namespace App\Console\Commands;

use Elasticsearch;

use App\Console\Helpers\Indexer;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class SearchReindex extends BaseCommand
{

    use Indexer;

    protected $signature = 'search:reindex
                            {dest : The prefix of the indexes to copy documents to}
                            {source? : The prefix of the indexes to copy documents from}';

    protected $description = 'Copy documents from one set of indices to another';

    public function handle()
    {

        $dest = $this->argument('dest');
        $source = $this->argument('source') ?? env('ELASTICSEARCH_INDEX');

        $models = app('Search')->getSearchableModels();

        foreach ($models as $model)
        {

            $endpoint = app('Resources')->getEndpointForModel($model);
            $index = $source . '-' . $endpoint;

            $params = [
                'wait_for_completion' => false,
                'body' => [
                    'source' => [
                        'index' => $index,
                        'size' => 100,
                    ],
                    'dest' => [
                        'index' => $dest . '-' . $endpoint,
                        'type' => 'doc',
                    ],
                ],
            ];

            $return = Elasticsearch::reindex($params);

            $this->info('Reindex from ' . $index . 'has started. You can monitor the process here: ' . $this->baseUrl() . '/_tasks/' . $return['task']);

        }

    }

}

Fix search:reindex to work with "doc"

Fix search:reindex to work with "doc"


<?

defined('C5_EXECUTE') or die("Access Denied.");
if (!ini_get('safe_mode')) {
	@set_time_limit(0);
}

$json = Loader::helper('json');
if (Job::authenticateRequest($_REQUEST['auth'])) {

	$list = Job::getList();
	foreach($list as $job) {
		if ($job->supportsQueue()) {
			$q = $job->getQueueObject();
			$obj = new stdClass;
			$js = Loader::helper('json');
			try {
				$messages = $q->receive($job->getJobQueueBatchSize());
				foreach($messages as $key => $p) {
					$job->processQueueItem($p);
					$q->deleteMessage($p);
				}
				$totalItems = $q->count();
				$obj->totalItems = $totalItems;
				if ($q->count() == 0) {
					$result = $job->finish($q);
					$obj = $job->markCompleted(0, $result);
					$obj->totalItems = $totalItems;
				}
			} catch(Exception $e) {
				$obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage());
				$obj->message = $obj->result; // needed for progressive library.
			}
			print $js->encode($obj);
		}
	}
}

<?

defined('C5_EXECUTE') or die("Access Denied.");
if (!ini_get('safe_mode')) {
	@set_time_limit(0);
}

$json = Loader::helper('json');
if (Job::authenticateRequest($_REQUEST['auth'])) {

	$list = Job::getList();
	foreach($list as $job) {
		if ($job->supportsQueue()) {
			$q = $job->getQueueObject();
			// don't process queues that are empty
			if($q->count() <1){
				continue;
			}
			$obj = new stdClass;
			$js = Loader::helper('json');
			try {
				$messages = $q->receive($job->getJobQueueBatchSize());
				foreach($messages as $key => $p) {
					$job->processQueueItem($p);
					$q->deleteMessage($p);
				}
				$totalItems = $q->count();
				$obj->totalItems = $totalItems;
				if ($q->count() == 0) {
					$result = $job->finish($q);
					$obj = $job->markCompleted(0, $result);
					$obj->totalItems = $totalItems;
				}
			} catch(Exception $e) {
				$obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage());
				$obj->message = $obj->result; // needed for progressive library.
			}
			print $js->encode($obj);
			// End when one queue has processed a batch step
			break;
		}
	}
}

Fix Ghost execution bug and multiple execution bug

http://www.concrete5.org/developers/bugs/5-6-2-1/ghost-execution-of-queuable-jobs/
http://www.concrete5.org/developers/bugs/5-6-2-1/slices-of-many-queable-jobs-could-be-executed-together/


<?php

class Utility {

  public function __construct() {

    //
  }

  public static function displayError($message) {

    // Clear the buffer.
    ob_end_clean();

    // Terminate with an error message.
    exit("Error: {$message}.");
  }

  public static function getRootAddress() {

    $host = $_SERVER["HTTP_HOST"];

    $protocol;

    if (!empty($_SERVER["HTTP_X_FORWARDED_PROTO"])) {

      $protocol = $_SERVER["HTTP_X_FORWARDED_PROTO"] . "://";
    }
    else {

      if (!empty($_SERVER["HTTPS"])) {

        $protocol = "https://";
      }
      else {

        $protocol = "http://";
      }
    }

    $sub_directory = substr(

      dirname(dirname(__DIR__)),

      strlen($_SERVER["DOCUMENT_ROOT"])
    );

    // Return absolute URL of where Kaku is installed.
    return $protocol . $host . $sub_directory;
  }
}

?>

<?php

if (!defined("KAKU_ACCESS")) {

  // Deny direct access to this file.
  exit();
}

class Utility {

  public function displayError($message) {

    if (ob_get_status()["level"] > 0) {

      // Clear the buffer.
      ob_end_clean();
    }

    // Terminate with an error message.
    exit("Error: {$message}.");
  }
}

?>

Check for buffer before calling ob_end_clean()

If ob_end_clean() is called before ob_start() has been called, PHP will
throw an error. This ensures that the buffer is only terminated if it
exists in the first place.

In addition, getRootAddress() has been removed.


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Service extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('service', function (Blueprint $table) {
            $table->increments('id');
            $table->string('serial_number')->nullable();
            $table->string('service_name');
            $table->string('service_state');
            $table->bigInteger('timestamp');
        });

    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('service');
    }
}

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Service extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('service', function (Blueprint $table) {
            $table->increments('id');
            $table->string('serial_number')->nullable();
            $table->string('service_name');
            $table->string('service_state');
            $table->bigInteger('timestamp');

            $table->index('serial_number');
            $table->index('service_name');
            $table->index('service_state');
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('service');
    }
}

Add indexes to service migration

Add indexes to service migration


<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists and
// the Container class isn't loaded.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) &&
	! class_exists( '\\Frozzare\\Tank\\Container' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

Load composer only if container class dont exists


<?php

namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\API';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        //

        parent::boot($router);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $directories = array_splice(scandir(app_path('API')), 0, 2);
        foreach ($directories as $directory) {
            if (is_dir(app_path('API/'.$directory))) {
                $router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Http', 'prefix' => $directory.'/api'], function ($router) use ($directory) {
                    require app_path('API/'.$directory.'/routes.php');
                });
            }
        }
    }
}

<?php

namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\API';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        //

        parent::boot($router);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $scan = scandir(app_path('API'));
        $directories = array_splice($scan, 0, 2);
        foreach ($directories as $directory) {
            if (is_dir(app_path('API/'.$directory)) && substr($directory, 0, 1) != '.') {
                $router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Http', 'prefix' => $directory.'/api'], function ($router) use ($directory) {
                    require app_path('API/'.$directory.'/routes.php');
                });
            }
        }
    }
}

Fix a pass by reference, and don't create APIs for hidden directories


<?php

namespace Korko\SecretSanta\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

<?php

namespace Korko\SecretSanta\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/',
    ];
}

Disable CSRF token validation, Recaptcha is redundant and can be revalidated if expired


<?php

class UsersTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    User::truncate();

    User::create([
      'first_name' => 'Dave',
      'email' => 'dfurnes@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Andrea',
      'email' => 'agaither@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'email' => $faker->unique()->safeEmail,
        'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
      ]);
    }
    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'phone' => $faker->unique()->phoneNumber,
        'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
      ]);
    }
  }
}

<?php

class UsersTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    User::truncate();

    User::create([
      'first_name' => 'Dave',
      'email' => 'dfurnes@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Andrea',
      'email' => 'agaither@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Calvin',
      'email' => 'cstowell@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Naomi',
      'email' => 'nhirabayashi@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    if (App::environment('local')) {
      foreach(range(1,25) as $index) {
        User::create([
          'first_name' => $faker->firstName,
          'email' => $faker->unique()->safeEmail,
          'birthdate' => $faker->dateTime('now'),
        ]);
      }
      foreach(range(1,25) as $index) {
        User::create([
          'first_name' => $faker->firstName,
          'phone' => $faker->unique()->phoneNumber,
          'birthdate' => $faker->dateTime('now'),
        ]);
      }
    }
  }
}

Add content peeps to the db.

Add content peeps to the db.


<?php
if(php_sapi_name() !== 'cli') die();

$chars = 'aąbcćdeęfghijklłmnńoóprsśtuvwxyzżź0123456789';
$len = mb_strlen($chars, 'UTF-8');

$replacements = [
	'Ó' => 'Ó',
	'ó' => 'ó',
	'É' => 'É',
	'é' => 'é',
];

$stops = [];
for($i = 0; $i < $len; $i++) {
	for($j = 0; $j < $len; $j++) {
		$char = mb_substr($chars, $i, 1, 'UTF-8').mb_substr($chars, $j, 1, 'UTF-8');
		$json = file_get_contents('http://www.ttss.krakow.pl/internetservice/services/lookup/autocomplete/json?query='.urlencode($char));
		$elements = json_decode($json, 1);
		foreach($elements as $element) {
			if($element['type'] == 'divider') continue;
			if($element['type'] == 'route') continue;
			if($element['type'] != 'stop') {
				throw new Exception('Unknown element: '.var_export($element, 1));
			}

			$stops[$element['id']] = strtr($element['name'], $replacements);
		}
	}
}

asort($stops);
var_export($stops);

<?php
if(php_sapi_name() !== 'cli') die();

$json = file_get_contents('http://www.ttss.krakow.pl/internetservice/geoserviceDispatcher/services/stopinfo/stops?left=-648000000&bottom=-324000000&right=648000000&top=324000000');
$elements = json_decode($json, 1);
foreach($elements['stops'] as $element) {
	$stops[$element['shortName']] = $element['name'];
}

asort($stops);
var_export($stops);

Simplify stops download using stopinfo/stops API method


<?php

namespace System\Traits;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;

trait SendsMailTemplate
{
    public function mailGetRecipients($type)
    {
        return [];
    }

    public function mailGetData()
    {
        return [];
    }

    public function mailSend($view, $recipientType = null)
    {
        $extraData = [];
        Event::fire('model.mail.beforeSend', [$this, &$extraData]);

        Mail::queue(
            $view,
            array_merge($extraData, $this->mailGetData()),
            is_callable($recipientType)
                ? $recipientType
                : $this->mailBuildMessage($recipientType)
        );
    }

    protected function mailBuildMessage($recipientType = null)
    {
        $recipients = $this->mailGetRecipients($recipientType);

        return function ($message) use ($recipients) {
            foreach ($recipients as $recipient) {
                [$email, $name] = $recipient;
                $message->to($email, $name);
            }
        };
    }
}

<?php

namespace System\Traits;

use Illuminate\Support\Facades\Mail;

trait SendsMailTemplate
{
    public function mailGetRecipients($type)
    {
        return [];
    }

    public function mailGetData()
    {
        return [];
    }

    public function mailSend($view, $recipientType = null)
    {
        $vars = $this->mailGetData();

        $result = $this->fireEvent('model.mailGetData', [$view, $recipientType]);
        if ($result AND is_array($result))
            $vars = array_merge(...$result) + $vars;

        Mail::queue($view, $vars, $this->mailBuildMessage($recipientType));
    }

    protected function mailBuildMessage($recipientType = null)
    {
        if (is_callable($recipientType))
            return $recipientType;

        $recipients = $this->mailGetRecipients($recipientType);

        return function ($message) use ($recipients) {
            foreach ($recipients as $recipient) {
                [$email, $name] = $recipient;
                $message->to($email, $name);
            }
        };
    }
}

[BC] Replace model.mail.beforeSend event with model.mailGetData local event


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class SsnLastFourModel extends My_Model {

    function __construct() {
      parent::_construct();
      $this->table = 'ssnLastFour';
      $this->id    = 'ssnLastFourId';

    }

  }

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class SsnLastFourModel extends MY_Model {

    function __construct() {
      parent::__construct();
      $this->table = 'ssnLastFour';
      $this->id    = 'ssnLastFourId';

    }
  }

Fix ssn last four model

Fix ssn last four model


<?php
if(is_user_logged_in())
    return;

$wordpress_login_enabled = WP_Auth0_Options::get('wordpress_login_enabled') == 1;
if (!$wordpress_login_enabled || !isset($_GET['wle'])) {
    include ('auth0-login-form.php');
}else{
    add_action('login_footer', array(WP_Auth0::class, 'render_back_to_auth0'));
}
?>

<?php
if(is_user_logged_in())
    return;

$wordpress_login_enabled = WP_Auth0_Options::get('wordpress_login_enabled') == 1;
if (!$wordpress_login_enabled || !isset($_GET['wle'])) {
    include ('auth0-login-form.php');
}else{
    add_action('login_footer', array('WP_Auth0', 'render_back_to_auth0'));
}
?>

Fix for legacy php versions

Fix for legacy php versions


<?php
/**
 * 2016_06_16_000001_create_users_table.php
 * Copyright (C) 2016 thegrumpydictator@gmail.com
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */
declare(strict_types = 1);

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

/**
 * Class CreateUsersTable
 */
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('users')) {
            Schema::create(
                'users', function (Blueprint $table) {
                $table->increments('id');
                $table->timestamps();
                $table->string('email', 255);
                $table->string('password', 60);
                $table->string('remember_token', 100);
                $table->string('reset', 32)->nullable();
                $table->tinyInteger('blocked', false, true)->default('0');
                $table->string('blocked_code', 25)->nullable();
            }
            );
        }
    }

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

<?php
/**
 * 2016_06_16_000001_create_users_table.php
 * Copyright (C) 2016 thegrumpydictator@gmail.com
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */
declare(strict_types = 1);

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

/**
 * Class CreateUsersTable
 */
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('users')) {
            Schema::create(
                'users', function (Blueprint $table) {
                $table->increments('id');
                $table->timestamps();
                $table->string('email', 255);
                $table->string('password', 60);
                $table->string('remember_token', 100)->nullable();
                $table->string('reset', 32)->nullable();
                $table->tinyInteger('blocked', false, true)->default('0');
                $table->string('blocked_code', 25)->nullable();
            }
            );
        }
    }

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

Fix future query problems (current users not affected either way) [skip ci]


<?php
declare(strict_types=1);

namespace phln\relation;

use function phln\fn\curry;
use const phln\fn\nil;

const equals = '\\phln\\relation\\𝑓equals';

/**
 * Returns `true` if its arguments are equivalent, `false` otherwise.
 *
 * @phlnSignature a -> b -> Boolean
 * @phlnCategory relation
 * @param string $a
 * @param string $b
 * @return \Closure|bool
 * @example
 *      \phln\relation\equals(1, 1); // true
 *      \phln\relation\equals(1, '1'); // false
 *      \phln\relation\equals(1, 2); // false
 */
function equals($a = nil, $b = nil)
{
    return curry(equals, $a, $b);
}

function 𝑓equals($a, $b): bool
{
    return $a === $b;
}

<?php
declare(strict_types=1);

namespace phln\relation;

use function phln\fn\curry;
use const phln\fn\nil;

const equals = '\\phln\\relation\\equals';
const 𝑓equals = '\\phln\\relation\\𝑓equals';

/**
 * Returns `true` if its arguments are equivalent, `false` otherwise.
 *
 * @phlnSignature a -> b -> Boolean
 * @phlnCategory relation
 * @param mixed $a
 * @param mixed $b
 * @return \Closure|bool
 * @example
 *      \phln\relation\equals(1, 1); // true
 *      \phln\relation\equals(1, '1'); // false
 *      \phln\relation\equals(1, 2); // false
 */
function equals($a = nil, $b = nil)
{
    return curry(𝑓equals, $a, $b);
}

function 𝑓equals($a, $b): bool
{
    return $a === $b;
}

Update functions in `relation` ns

Update functions in `relation` ns


<?php

class SV_NoticeTime_Listener
{
    public static function notices_prepare(array &$noticeList, array &$noticeTokens, XenForo_Template_Abstract $template, array $containerData)
    {

    }
}

<?php

class SV_NoticeTime_Listener
{
    public static function getRelativeDate(DateTime $now, DateTime $other)
    {
        $interval = $other->diff($now);
        $format = array();
        if ($interval->y)
        {
            $format[] = '%y years';
        }
        if ($interval->m)
        {
            $format[] = '%m months';
        }
        if ($interval->d)
        {
            $format[] = '%d days';
        }
        if ($interval->h)
        {
            $format[] = '%h hours';
        }
        if ($interval->i)
        {
            $format[] = '%i minutes';
        }
        $format[] = '%s seconds';
        return $interval->format(join(', ', $format));
    }

    public static function notices_prepare(array &$noticeList, array &$noticeTokens, XenForo_Template_Abstract $template, array $containerData)
    {
        $now = new DateTime();
        $user = XenForo_Visitor::getInstance()->toArray();
        foreach ($noticeList AS $noticeId => &$notice)
        {
            $tokens = array();
            foreach ($notice['user_criteria'] AS &$criteria)
            {
                switch($criteria['rule'])
                {
                    case 'before':
                        $data = $criteria['data'];
                        $datetime = new DateTime("$data[ymd] $data[hh]:$data[mm]",new DateTimeZone(($data['user_tz'] ? $user['timezone'] : $data['timezone'])));
                        $time = XenForo_Locale::dateTime($datetime->getTimestamp(), 'separate');
                        $tokens['{time_end:absolute}'] = $time['date'] . ' ' . $time['time'];
                        $tokens['{time_end:relative}'] = self::getRelativeDate($now, $datetime);
                        $tokens['{time_end}'] = $tokens['{time_end:relative}'];
                        break;
                    case 'after':
                        $data = $criteria['data'];
                        $datetime = new DateTime("$data[ymd] $data[hh]:$data[mm]",new DateTimeZone(($data['user_tz'] ? $user['timezone'] : $data['timezone'])));
                        $time = XenForo_Locale::dateTime($datetime->getTimestamp(), 'separate');
                        $tokens['{time_start:absolute}'] = $time['date'] . ' ' . $time['time'];
                        $tokens['{time_start:relative}'] = self::getRelativeDate($now, $datetime);
                        $tokens['{time_start}'] = $tokens['{time_start:relative}'];
                        break;
                }
            }

            if ($tokens)
            {
                $notice['message'] = str_replace(array_keys($tokens), $tokens, $notice['message']);
            }
        }
    }
}

Implement replacables: {time_end:absolute}, {time_end:relative}, {time_start:absolute} and {time_start:relative}.