<?php

namespace Fixtures;

use DateTime;
use Scato\Serializer\Core\Type;
use Scato\Serializer\Navigation\DeserializationFilterInterface;
use Scato\Serializer\Navigation\ObjectFactoryInterface;

class CustomDateDeserializationFilter implements DeserializationFilterInterface
{
    public function filter(Type $type, $value, ObjectFactoryInterface $next)
    {
        if ($type->toString() === 'DateTime') {
            // unfortunately, you cannot use 'c' as a format
            return DateTime::createFromFormat('Y-m-d\\TH:i:sP', $value);
        }

        return $next->createObject($type, $value);
    }
}

<?php

namespace Fixtures;

use DateTime;
use Scato\Serializer\Core\Type;
use Scato\Serializer\Navigation\DeserializationFilterInterface;
use Scato\Serializer\Navigation\ObjectFactoryInterface;

class CustomDateDeserializationFilter implements DeserializationFilterInterface
{
    /**
     * @param Type                   $type
     * @param mixed                  $value
     * @param ObjectFactoryInterface $next
     * @return mixed
     */
    public function filter(Type $type, $value, ObjectFactoryInterface $next)
    {
        if ($type->toString() === 'DateTime') {
            // unfortunately, you cannot use 'c' as a format
            return DateTime::createFromFormat('Y-m-d\\TH:i:sP', $value);
        }

        return $next->createObject($type, $value);
    }
}

Add DocBlock to DeserializationFilter in Fixtures


#!/usr/bin/php
<?php

/*

Copyright:: 2013, Sebastian Grewe

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

// Change to working directory
chdir(dirname(__FILE__));

// Include all settings and classes
require_once('shared.inc.php');

// If we don't keep archives, delete some now to release disk space
if (!$share->purgeArchive()) {
  $log->logError("Failed to delete archived shares, not critical but should be checked: " . $share->getCronError());
  $monitoring->endCronjob($cron_name, 'E0008', 1, true);
}

// Cron cleanup and monitoring
require_once('cron_end.inc.php');
?>

#!/usr/bin/php
<?php

/*

Copyright:: 2013, Sebastian Grewe

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

// Change to working directory
chdir(dirname(__FILE__));

// Include all settings and classes
require_once('shared.inc.php');

// If we don't keep archives, delete some now to release disk space
if (!$affected_rows = $share->purgeArchive()) {
  $log->logError("Failed to delete archived shares, not critical but should be checked: " . $share->getCronError());
  $monitoring->endCronjob($cron_name, 'E0008', 1, true);
} else {
  $log->logDebug("Deleted $affected_rows archived shares this run");
}

// Cron cleanup and monitoring
require_once('cron_end.inc.php');
?>

Debug logging for purgeArchive calls

[IMPROVED] Debug logging for purgeArchive calls


<?php

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

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$container = Yolo\Factory::createContainer();
$builder = $container->get('route_builder');

$builder->get('hello', '/', function (Request $request) {
    return new Response("Hallo welt, got swag yo!\n");
});

$front = $container->get('front_controller');
$front->run();

<?php

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

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$container = Yolo\Factory::createContainer();
$builder = $container->get('route_builder');

$builder->get('hello', '/', function (Request $request) {
    return new Response("Hallo welt, got swag yo!\n");
});

$builder->get('error', '/error', function (Request $request) {
    throw new \Exception('Holy crap, explosion!');
});

$front = $container->get('front_controller');
$front->run();

Add error page to test exceptions

Add error page to test exceptions


<?php

/**
 * LICENSE: This source code is subject to the license that is available
 * in the LICENSE file distributed along with this package.
 *
 * @package    Penelope
 * @author     Matthew Caruana Galizia <mcg@karwana.com>
 * @copyright  Karwana Ltd
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

namespace Karwana\Penelope\Controllers;

use Karwana\Penelope\Exceptions;

class EdgeController extends ObjectController {

	private function getByParamsArray($params) {
		return call_user_func_array(array($this, 'getEdgeByParams'), $params);
	}

	public function read($node_schema_slug, $node_id, $edge_schema_slug, $edge_id) {
		$edge = $this->getByParamsArray(func_get_args());
		$edge->delete();
		$this->app->render('edge', array('title' => $edge->getTitle()));
	}

	public function delete($node_schema_slug, $node_id, $edge_schema_slug, $edge_id) {
		$edge = $this->getByParamsArray(func_get_args());
		$edge->delete();
		$this->app->render('edge_deleted', array('title' => 'Deleted ' . $edge->getTitle()));
	}
}

<?php

/**
 * LICENSE: This source code is subject to the license that is available
 * in the LICENSE file distributed along with this package.
 *
 * @package    Penelope
 * @author     Matthew Caruana Galizia <mcg@karwana.com>
 * @copyright  Karwana Ltd
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

namespace Karwana\Penelope\Controllers;

use Karwana\Penelope\Exceptions;

class EdgeController extends ObjectController {

	private function getByParamsArray($params) {
		return call_user_func_array(array($this, 'getEdgeByParams'), $params);
	}

	public function read($node_schema_slug, $node_id, $edge_schema_slug, $edge_id) {
		$edge = $this->getByParamsArray(func_get_args());
		$edge->delete();
		$this->app->render('edge', array('title' => $edge->getTitle(), 'edge' => $edge));
	}

	public function delete($node_schema_slug, $node_id, $edge_schema_slug, $edge_id) {
		$edge = $this->getByParamsArray(func_get_args());
		$edge->delete();
		$this->app->render('edge_deleted', array('title' => 'Deleted ' . $edge->getTitle()));
	}
}

Add edge to view data

Add edge to view data


<?php

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

namespace Sylius\Component\Payment\Model;

use Doctrine\Common\Collections\Collection;

interface PaymentsSubjectInterface
{
    /**
     * Get all payments associated with the payment subject.
     *
     * @return Collection|PaymentInterface[]
     */
    public function getPayments();

    /**
     * Check if order has any payments
     *
     * @return bool
     */
    public function hasPayments();

    /**
     * Add a payment.
     *
     * @param PaymentInterface $payment
     */
    public function addPayment(PaymentInterface $payment);

    /**
     * Remove a payment.
     *
     * @param PaymentInterface $payment
     */
    public function removePayment(PaymentInterface $payment);

    /**
     * Check if the payment subject has certain payment.
     *
     * @param PaymentInterface $payment
     *
     * @return bool
     */
    public function hasPayment(PaymentInterface $payment);
}

Fix broken spec, add new for CoreBundle state machine callbacks Some additional CS fixes


<?php

namespace BinSoul\Net\Mqtt\Packet;

/**
 * Provides methods for packets with an identifier.
 */
trait IdentifiablePacket
{
    /** @var int */
    private static $nextIdentifier = 0;
    /** @var int */
    protected $identifier = 0;

    /**
     * Returns the identifier or generates a new one.
     *
     * @return int
     */
    protected function generateIdentifier()
    {
        if ($this->identifier <= 0) {
            ++self::$nextIdentifier;
            self::$nextIdentifier &= 0xFFFF;

            $this->identifier = self::$nextIdentifier;
        }

        return $this->identifier;
    }

    /**
     * Returns the identifier.
     *
     * @return int
     */
    public function getIdentifier()
    {
        return $this->generateIdentifier();
    }

    /**
     * Sets the identifier.
     *
     * @param int $value
     *
     * @throws \InvalidArgumentException
     */
    public function setIdentifier($value)
    {
        if ($value < 0 || $value > 0xFFFF) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Expected an identifier between 0x0000 and 0xFFFF but got %x',
                    $value
                )
            );
        }

        $this->identifier = $value;
    }
}

<?php

namespace BinSoul\Net\Mqtt\Packet;

/**
 * Provides methods for packets with an identifier.
 */
trait IdentifiablePacket
{
    /** @var int */
    private static $nextIdentifier = 0;
    /** @var int|null */
    protected $identifier;

    /**
     * Returns the identifier or generates a new one.
     *
     * @return int
     */
    protected function generateIdentifier()
    {
        if ($this->identifier === null) {
            ++self::$nextIdentifier;
            self::$nextIdentifier &= 0xFFFF;

            $this->identifier = self::$nextIdentifier;
        }

        return $this->identifier;
    }

    /**
     * Returns the identifier.
     *
     * @return int|null
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * Sets the identifier.
     *
     * @param int|null $value
     *
     * @throws \InvalidArgumentException
     */
    public function setIdentifier($value)
    {
        if ($value !== null && ($value < 0 || $value > 0xFFFF)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Expected an identifier between 0x0000 and 0xFFFF but got %x',
                    $value
                )
            );
        }

        $this->identifier = $value;
    }
}

Set the default identifier to null

Set the default identifier to null


<?php

$REGISTER_LTI2 = array(
"name" => "Peer-Graded Dropbox",
"short_name" => "Peer Grader",
"description" => "This tool provides a structured dropbox that can take images, URLs, text and code.  These tools can be peer-graded, instructor graded, or a blend of peer and instructor graded assignments."
);

<?php

$REGISTER_LTI2 = array(
"name" => "Peer-Graded Dropbox",
"FontAwesome" => "fa-code-fork",
"short_name" => "Peer Grader",
"description" => "This tool provides a structured dropbox that can take images, URLs, text and code.  These tools can be peer-graded, instructor graded, or a blend of peer and instructor graded assignments."
);

Add FontAwesome icons to the tool registration.


            {{ trans('cachet.incidents.scheduled') }}

            @foreach($scheduled_maintenance as $schedule)

id }}">
                {{ $schedule->name }} scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}">

                    {!! $schedule->formatted_message !!}

                @if($schedule->components->count() > 0)

                @foreach($schedule->components as $affected_component)
                {{ $affected_component->component->name }}
                @endforeach
                @endif

            @endforeach

            {{ trans('cachet.incidents.scheduled') }}

            @foreach($scheduled_maintenance as $schedule)

id }}">
                {{ $schedule->name }} scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}">

id }}">

                    {!! $schedule->formatted_message !!}

                @if($schedule->components->count() > 0)

                @foreach($schedule->components as $affected_component)
                {{ $affected_component->component->name }}
                @endforeach
                @endif

            @endforeach

Add perma-link to each scheduled maintenance

PR #2912 adds scheduled maintenance ID to overview HTML.
This patch introduces permanent link and icon image by the ID.


<?php

/*
 * This file is part of the Fxp Composer Asset Plugin package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Fxp\Composer\AssetPlugin\Repository\Vcs;

use Composer\Cache;
use Composer\Repository\Vcs\GitBitbucketDriver as BaseGitBitbucketDriver;

/**
 * Git Bitbucket vcs driver.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class GitBitbucketDriver extends BaseGitBitbucketDriver
{
    /**
     * @var Cache
     */
    protected $cache;

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

        $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
    }

    /**
     * {@inheritdoc}
     */
    public function getComposerInformation($identifier)
    {
        return BitbucketUtil::getComposerInformation($this->cache, $this->infoCache, $this->getScheme(), $this->repoConfig, $identifier, $this->owner, $this->repository, $this, 'getContents');
    }
}

<?php

/*
 * This file is part of the Fxp Composer Asset Plugin package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Fxp\Composer\AssetPlugin\Repository\Vcs;

use Composer\Cache;
use Composer\Repository\Vcs\GitBitbucketDriver as BaseGitBitbucketDriver;

/**
 * Git Bitbucket vcs driver.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class GitBitbucketDriver extends BaseGitBitbucketDriver
{
    /**
     * @var Cache
     */
    protected $cache;

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

        $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
    }

    /**
     * {@inheritdoc}
     */
    public function getComposerInformation($identifier)
    {
        $method = method_exists($this, 'getContentsWithOAuthCredentials') ? 'getContentsWithOAuthCredentials' : 'getContents';
        return BitbucketUtil::getComposerInformation($this->cache, $this->infoCache, $this->getScheme(), $this->repoConfig, $identifier, $this->owner, $this->repository, $this, $method);
    }
}

Implement bitbucket OAuth support (implemented in composer 1.2)

In composer 1.2 support for OAuth authentication for bitbucket.org has been expanded.
This fix brings the same support to the composer asset plugin.

It's completely backwards compatible with composer versions before 1.2.


<?php
namespace Aedart\Scaffold\Cache;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Builders\IndexBuilder;
use Illuminate\Contracts\Cache\Repository;

/**
 * Cache Helper
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Cache
 */
class CacheHelper
{
    /**
     * Default cache directory
     */
    const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . 'cache/';

    /**
     * @var Repository
     */
    static protected $cache;

    /**
     * Register the cache directory
     *
     * @param string $directory
     */
    static public function setCacheDirectory($directory)
    {
        $ioc = IoC::getInstance();

        $config = $ioc->make('config');
        $config->set('cacheDir', $directory);

        $ioc->container()['config'] = $config;
    }

    /**
     * Returns a cache repository instance
     *
     * @return Repository
     */
    static public function make()
    {
        if(!isset(self::$cache)){
            $ioc = IoC::getInstance();
            $repository = $ioc->make(Repository::class);
            self::$cache = $repository;
        }

        return self::$cache;
    }

    /**
     * Destroy the cache instance inside this helper
     */
    static public function destroy()
    {
        unset(self::$cache);
    }
}

<?php
namespace Aedart\Scaffold\Cache;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Builders\IndexBuilder;
use Illuminate\Contracts\Cache\Repository;

/**
 * Cache Helper
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Cache
 */
class CacheHelper
{
    /**
     * Default cache directory
     */
    const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . 'cache/';

    /**
     * @var Repository
     */
    static protected $cache;

    /**
     * Register the cache directory
     *
     * @param string $directory
     */
    static public function setCacheDirectory($directory)
    {
        $ioc = IoC::getInstance();

        $config = $ioc->make('config');
        $config->set('cacheDir', $directory);

        $ioc->container()['config'] = $config;
    }

    /**
     * Returns a cache repository instance
     *
     * @return Repository
     */
    static public function make()
    {
        if(!isset(self::$cache)){
            $ioc = IoC::getInstance();
            $repository = $ioc->make(Repository::class);
            self::$cache = $repository;
        }

        return self::$cache;
    }

    /**
     * Destroy the cache instance inside this helper
     */
    static public function destroy()
    {
        self::$cache = null;
    }
}

Fix attempt to unset static property

Fix attempt to unset static property


<?php

namespace Optimus\Castle\Integration\Laravel;

use Illuminate\Support\ServiceProvider as BaseProvider;
use Optimus\Castle\Castle;

class ServiceProvider extends BaseProvider {

    const packageKey = 'castle';

    public function register()
    {
        $this->registerAssets();
        $this->loadConfig();
        $this->bindInstance();
    }

    private function bindInstance()
    {
        $this->app->bindShared('castle', function(){
            $config = $this->app['config']->get(self::packageKey);

            return new Castle($config);
        });
    }

    private function registerAssets()
    {
        $this->publishes([
            __DIR__.'/../../config/' . self::packageKey . '.php' => config_path(self::packageKey . '.php')
        ]);
    }

    private function loadConfig()
    {
        if ($this->app['config']->get(self::packageKey) === null) {
            $this->app['config']->set(self::packageKey, require __DIR__.'/../../config/' . self::packageKey . '.php');
        }
    }

}

<?php

namespace Optimus\Castle\Integration\Laravel;

use Illuminate\Support\ServiceProvider as BaseProvider;
use Optimus\Castle\Castle;

class ServiceProvider extends BaseProvider {

    const packageKey = 'castle';

    public function register()
    {
        $this->registerAssets();
        $this->loadConfig();
        $this->bindInstance();
    }

    private function bindInstance()
    {
        $this->app->singleton('castle', function(){
            $config = $this->app['config']->get(self::packageKey);

            return new Castle($config);
        });
    }

    private function registerAssets()
    {
        $this->publishes([
            __DIR__.'/../../config/' . self::packageKey . '.php' => config_path(self::packageKey . '.php')
        ]);
    }

    private function loadConfig()
    {
        if ($this->app['config']->get(self::packageKey) === null) {
            $this->app['config']->set(self::packageKey, require __DIR__.'/../../config/' . self::packageKey . '.php');
        }
    }

}

Chore: Update for compatability with Laravel 5.2


<?php
/**
 * The template for displaying search form
 *
 * @package FoundationPress
 * @since FoundationPress 1.0.0
 */

?>

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">

		<input type="text" class="input-group-field" value="" name="s" id="s" placeholder="<?php esc_attr_e( 'Search', 'foundationpress' ); ?>">

			<input type="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search', 'foundationpress' ); ?>" class="button">

</form>

<?php
/**
 * The template for displaying search form
 *
 * @package FoundationPress
 * @since FoundationPress 1.0.0
 */

?>

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">

		<input type="text" class="input-group-field" value="" name="s" id="s" aria-label="Search" placeholder="<?php
		esc_attr_e( 'Search', 'foundationpress' ); ?>">

			<input type="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search', 'foundationpress' ); ?>" class="button">

</form>

Add aria label to the search form to assist in accessibility

- Pass accessibility audits
- Aid in assistive technologies

https://github.com/olefredrik/FoundationPress/issues/1307


<?php
/** Production */
ini_set('display_errors', 0);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', false);
/** Disable all file modifications including updates and update notifications */
define('DISALLOW_FILE_MODS', true);

<?php
/** Production */
ini_set('display_errors', 0);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', false);
/** Disable all file modifications including updates and update notifications */
// define('DISALLOW_FILE_MODS', false);

Allow file mods in prod

Allow file mods in prod


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AffiliationController extends Controller
{

    public function __construct()
    {
        $this->middleware('jwt.auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return \App\Affiliation::all();
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AffiliationController extends Controller
{

    public function __construct()
    {
//        $this->middleware('jwt.auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return \App\Affiliation::all();
    }
}

Remove middleware from Affiliation index


<?php

namespace AppBundle\API\Edit;

use AppBundle\API\Webservice;
use AppBundle\AppBundle;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class UpdateProject
{
    private $manager;

    /**
     * UpdateProject constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute(FennecUser $user = null)
    {
        $project_id = $_REQUEST['project_id'];
        $biom = $_REQUEST['biom'];
        if($biom === null || $project_id === null){
            return array('error' => 'Missing parameter "biom" or "project_id"');
        }
        if($user == null){
            return array('error' => 'User not logged in');
        }
        if($user === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $project_id));
        if($project === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project->setProject(json_decode($biom, true));
        $this->manager->persist($project);
        $this->manager->flush();
        return array('error' => null);
    }
}

<?php

namespace AppBundle\API\Edit;

use AppBundle\API\Webservice;
use AppBundle\AppBundle;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\WebuserData;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class UpdateProject
{
    private $manager;

    /**
     * UpdateProject constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute($projectId, $biom, FennecUser $user = null)
    {
        if($biom === null || $project_id === null){
            return array('error' => 'Missing parameter "biom" or "project_id"');
        }
        if($user == null){
            return array('error' => 'User not logged in');
        }
        if($user === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId));
        if($project === null){
            return array('error' => 'Could not update project. Not found for user.');
        }
        $project->setProject(json_decode($biom, true));
        $this->manager->persist($project);
        $this->manager->flush();
        return array('error' => null);
    }
}

Change parameters of updateProjects service


<?php
use BryanCrowe\Growl\Growl;
use BryanCrowe\Growl\Builder\GrowlNotifyBuilder;
use \PHPUnit_Framework_TestCase;

class GrowlTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->Growl = new Growl(new GrowlNotifyBuilder());
    }

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

    public function testGrowl()
    {
        $this->assertTrue(true);
    }
}

<?php
use BryanCrowe\Growl\Growl;
use BryanCrowe\Growl\Builder\GrowlNotifyBuilder;
use \PHPUnit_Framework_TestCase;

class GrowlTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->Growl = new Growl(new GrowlNotifyBuilder());
    }

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

    public function testSet()
    {
        $expected = array(
            'hello' => 'world',
            'title' => 'Hey',
            'message' => 'Whatsup?'
        );
        $result = $this->Growl->set('hello', 'world')
            ->set('title', 'Hey')
            ->set('message', 'Whatsup?');

        $this->assertEquals($expected, PHPUnit_Framework_Assert::readAttribute($result, 'options'));
    }

    public function testEscape()
    {
        $expected = array(
            'hello' => '\'world\''
        );

        $growl = new Growl(new GrowlNotifyBuilder());
        $growlReflection = new ReflectionClass($growl);
        $method = $growlReflection->getMethod('escape');
        $method->setAccessible(true);

        $this->assertEquals($expected, $method->invokeArgs($growl, array(array('hello' => 'world'))));
    }
}

Test Growl set and escape methods

Test Growl set and escape methods


<?php

declare(strict_types=1);

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

\VCR\VCR::configure()
    ->enableRequestMatchers(array('method', 'url', 'host'));

Configure php-vcr to allow replays with different form post data


<?php

use App\Menu;
use Illuminate\Database\Seeder;

class MenuTableSeeder extends Seeder
{
    public function run()
    {
        Menu::truncate();

        Menu::create([
            'name'        => 'Home',
            'url'         => route('home'),
            'weight'      => '1',
            'emplacement' => 'left',
        ]);

        Menu::create([
            'name'        => 'Blog',
            'url'         => route('post.index'),
            'weight'      => '2',
            'emplacement' => 'left',
        ]);
    }
}

<?php

use App\Menu;
use Illuminate\Database\Seeder;

class MenuTableSeeder extends Seeder
{
    public function run()
    {
        Menu::truncate();

        Menu::create([
            'name'        => 'Home',
            'url'         => route('home'),
            'weight'      => '1',
            'emplacement' => 'left',
        ]);

        Menu::create([
            'name'        => 'Blog',
            'url'         => route('post.index'),
            'weight'      => '2',
            'emplacement' => 'left',
        ]);

        Menu::create([
            'name'          => 'Login',
            'url'           => url('auth/login'),
            'is_login_link' => true,
            'weight'        => '0',
            'emplacement'   => 'right',
        ]);
    }
}

Add Login Link to menu at installation

Add Login Link to menu at installation


<?php namespace Phaza\NorwegianAddressData\Parser;

use Closure;
use Phaza\NorwegianAddressData\Objects\Address;

class SOSIParser implements SosiParserInterface {
	/**
	 * @var Closure
	 */
	private $callback;
	/**
	 * @var resource
	 */
	private $handle;

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

	public function parse( $handle )
	{
		$this->handle = $handle;
		stream_filter_append( $this->handle, 'convert.iconv.ISO-8859-15/UTF-8', STREAM_FILTER_READ );

		$callback = $this->callback;

		while( ( $line = $this->seekTo( '.PUNKT' ) ) !== false ) {
			$buffer = [$line];
			$this->seekTo( '..NØ', $buffer );
			$buffer[] = fgets( $this->handle ); // coordinates

			$adr = Address::makeFromBuffer( $buffer );

			$callback( $adr );
		}

	}

	protected function seekTo( $string, array &$buffer = null )
	{
		do {
			$line = fgets( $this->handle );

			if($buffer) {
				$buffer[] = trim($line);
			}

		} while( $line !== false && strpos( $line, $string ) === false );

		return $line ? trim($line) : false;
	}
}

<?php namespace Phaza\NorwegianAddressData\Parser;

use Closure;
use Phaza\NorwegianAddressData\Objects\Address;

class SOSIParser implements SOSIParserInterface {
	/**
	 * @var Closure
	 */
	private $callback;
	/**
	 * @var resource
	 */
	private $handle;

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

	public function parse( $handle )
	{
		$this->handle = $handle;
		stream_filter_append( $this->handle, 'convert.iconv.ISO-8859-15/UTF-8', STREAM_FILTER_READ );

		$callback = $this->callback;

		while( ( $line = $this->seekTo( '.PUNKT' ) ) !== false ) {
			$buffer = [$line];
			$this->seekTo( '..NØ', $buffer );
			$buffer[] = fgets( $this->handle ); // coordinates

			$adr = Address::makeFromBuffer( $buffer );

			$callback( $adr );
		}

	}

	protected function seekTo( $string, array &$buffer = null )
	{
		do {
			$line = fgets( $this->handle );

			if($buffer) {
				$buffer[] = trim($line);
			}

		} while( $line !== false && strpos( $line, $string ) === false );

		return $line ? trim($line) : false;
	}
}

Fix correct capitalisation of interface

Fix correct capitalisation of interface


<?php

class MyClassA {
}

class MyClassB {
    public $otherObject;
    public $otherObject2;
}

class MyClassC {
}

$objectA = new MyClassA();
$objectAref2 =& $objectA;
$objectB = new MyClassB();
$objectB->otherObject = $objectA;
$objectB->otherObject2 = $objectA;

meminfo_objects_list(fopen('php://stdout', 'w'));

<?php

class MyClassA {
}

class MyClassB {
}

class MyClassC {
}

$objectA = new MyClassA();
$objectB = new MyClassB();
$objectA2 = $objectA;
$objectA3 = $objectA;

echo " * zval references have been copied\n";
meminfo_objects_list(fopen('php://stdout', 'w'));

$objectARef1 = &$objectA;
$objectARef2 = $objectA;

echo " * objectA turned into object reference\n";
meminfo_objects_list(fopen('php://stdout', 'w'));

Add better examples on object ref and non-ref (zval ref)


<?php
class EmailValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if (!empty($this->model->$property)) {
			if (preg_match('/^\A[a-z0-9_+\-]+(\.[a-z0-9_+\-]+)*@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/ui',
					$this->model->$property) != 1) {
				return array('email' => $rules['name']);
			}
		}

		return ValidationHelper::validateLength(mb_strlen($this->model->$property), $rules);
	}
}
?>

<?php
class EmailValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if (!empty($this->model->$property)) {
			if (preg_match('/^\A[^@]+@[^.@][^@]*\.[^@]+$/ui', $this->model->$property) != 1) {
				return array('email' => $rules['name']);
			}
		}

		return ValidationHelper::validateLength(mb_strlen($this->model->$property), $rules);
	}
}
?>

Make email validation more permissive

Make email validation more permissive

In order to support new gTLDs and non-ASCII characters in email
addresses, we make the email validation more permissive.


<?php

namespace Devophp\Component\Agent\Plugin;

use Devophp\Component\Nagios\Checker;
use Monolog\Logger;

class NagiosPlugin extends BasePlugin
{
    private $checker;
    private $logger;
    public function __construct()
    {
        $this->checker = new Checker();
        $this->checker->autoDetectPluginPath();
    }

    public function check($parameters)
    {
        $check = $parameters['check'];
        $arguments = $parameters['arguments'];

        $this->info("NagiosCheck:" . $check . "/" . $arguments);

        $response = $this->checker->check($check, $arguments);

        $this->info("ServiceOutput: " . $response->getServiceOutput() . " (code: " . $response->getStatusCode() . ")");

        $res = array();
        $res['statuscode'] = $response->getStatusCode();
        $res['statuslabel'] = $response->getStatusText();

        $res['serviceoutput'] = $response->getServiceOutput();
        $res['serviceperfdata'] = $response->getServicePerfData();

        $this->sendMessage($res);
    }
}

<?php

namespace Devophp\Component\Agent\Plugin;

use Devophp\Component\Nagios\Checker;
use Monolog\Logger;

class NagiosPlugin extends BasePlugin
{
    private $checker;
    private $logger;
    public function __construct()
    {
        $this->checker = new Checker();
        $this->checker->autoDetectPluginPath();
    }

    public function check($parameters)
    {
        $check = $parameters['check'];
        $arguments = $parameters['arguments'];
        $checkdefinitionname = $parameters['checkdefinitionname'];

        $this->info("NagiosCheck:" . $check . "/" . $arguments);

        $response = $this->checker->check($check, $arguments);

        $this->info("ServiceOutput: " . $response->getServiceOutput() . " (code: " . $response->getStatusCode() . ")");

        $parameters = array();
        $parameters['statuscode'] = $response->getStatusCode();
        $parameters['statuslabel'] = $response->getStatusText();

        $parameters['serviceoutput'] = $response->getServiceOutput();
        $parameters['serviceperfdata'] = $response->getServicePerfData();
        $parameters['hostname'] = gethostname();
        $parameters['checkdefinitionname'] = $checkdefinitionname;

        $message = array();
        $message['command'] = "monitor:checkreport";
        $message['from'] = gethostname();
        $message['parameters'] = $parameters;

        $this->sendMessage($message, '/queue/devophp/monitor');
    }
}

Send 'monitor:checkreport' message in response to 'nagios:check' messages


<?php
$this->extend('setup/layout.html');
?>

<?php echo $Form->form(); ?>

<?php echo tr('%1 could not save the configuration to the following file:', $app['name']); ?>

<?php echo $file; ?>

<?php if ($exists): ?>

<?php echo tr('The file exists, but %1 does not have permission to write to it.', $app['name']); ?>

<?php echo tr('You should change the access permission or ownership of the file to allow %1 to write to it. ', $app['name']); ?>

<?php echo $Html->link(tr('Click here to get more help.', 'http://apakoh.dk')); ?>

<?php echo tr('Alternatively, you can manually edit the file.')?>

<?php else: ?>

<?php echo tr('The file does not exists, and %1 does not have permission to create it.', $app['name']); ?>

<?php echo tr('Please create the file with the permissions necessary for %1 to write to it, then refresh this page.', $app['name']); ?>
<?php endif; ?>

<?php echo tr('Unsaved data'); ?>

<textarea style="height:150px;"><?php echo h($data); ?></textarea>

<?php echo $Form->submit(tr('Cancel'), array('class' => 'primary')); ?>

<?php echo $Form->end(); ?>

Fix layout on save config page.

Fix layout on save config page.


 <?php
class MySQL {

    private $conn;

    public function __construct($HOST, $USER, $PASS, $DB) {
        global $conn;
        $conn = new mysqli($HOST, $USER, $PASS, $DB);
        $conn->ping();
    }

    public function getArray($query) {
        global $conn;
        $conn->ping();
        $res = $conn->query($query);
        if ($res->num_rows >= 1) {
            $arr = array();
            while ($row = $res->fetch_assoc()) {
                $arr[] = $row;
            }
            return $arr;
        }
        else {
            return;
        }
    }

    public function query($query) {
        global $conn;
        $conn->ping();
        return $conn->query($query);
    }

    public function getMySQLi() {
        global $conn;
        return $conn;
    }
}
?>

Fix white spaces causing header issues

Fix white spaces causing header issues


<?php

namespace PhpGitHooks\Infrastructure\Tool;

class ToolPathFinder
{
    const COMPOSER_VENDOR_DIR = '/../../../';
    const COMPOSER_INSTALLED_FILE = 'composer/installed.json';

    /** @var array */
    private $tools = array(
        'phpcs' => 'squizlabs/php_codesniffer',
        'php-cs-fixer' => 'friendsofphp/php-cs-fixer',
        'phpmd' => 'phpmd/phpmd',
        'phpunit' => 'phpunit/phpunit',
        'phpunit-randomizer' => 'fiunchinho/phpunit-randomizer',
        'jsonlint' => 'seld/jsonlint',
    );
    /** @var array */
    private $installedPackages = array();

    /**
     * @param string $tool
     *
     * @return string
     */
    public function find($tool)
    {
        if (isset($this->installedPackages[$this->tools[$tool]])) {
            $package = $this->installedPackages[$this->tools[$tool]];
            foreach ($package['bin'] as $bin) {
                if (preg_match("#${tool}$#", $bin)) {
                    return dirname(__FILE__).self::COMPOSER_VENDOR_DIR.$package['name'].DIRECTORY_SEPARATOR.$bin;
                }
            }
        }

        return 'bin'.DIRECTORY_SEPARATOR.$tool;
    }
}

<?php

namespace PhpGitHooks\Infrastructure\Tool;

class ToolPathFinder
{
    const COMPOSER_VENDOR_DIR = '/../../../';
    const COMPOSER_INSTALLED_FILE = 'composer/installed.json';

    /** @var array */
    private $tools = array(
        'phpcs' => 'squizlabs/php_codesniffer',
        'php-cs-fixer' => 'friendsofphp/php-cs-fixer',
        'phpmd' => 'phpmd/phpmd',
        'phpunit' => 'phpunit/phpunit',
        'phpunit-randomizer' => 'fiunchinho/phpunit-randomizer',
        'jsonlint' => 'seld/jsonlint',
    );
    /** @var array */
    private $installedPackages = array();

    /**
     * @param string $tool
     *
     * @return string
     */
    public function find($tool)
    {
        if (isset($this->installedPackages[$this->tools[$tool]])) {
            $package = $this->installedPackages[$this->tools[$tool]];
            foreach ($package['bin'] as $bin) {
                if (preg_match("#${tool}$#", $bin)) {
                    return dirname(__FILE__).self::COMPOSER_VENDOR_DIR.$package['name'].DIRECTORY_SEPARATOR.$bin;
                }
            }
        }

        $binToolPath = 'bin'.DIRECTORY_SEPARATOR.$tool;
        if (file_exists($binToolPath) && is_file($binToolPath)) {
            return $binToolPath;
        }

        return 'vendor'.DIRECTORY_SEPARATOR.$binToolPath;
    }
}

Fix error due to path not found

Fix error due to path not found

When the project does not have the /bin directory in the root this error appears:
  [PhpGitHooks\Module\JsonLint\Contract\Exception\JsonLintViolationsException]
  Could not open input file: bin/jsonlint

But it does exist in /vendor/bin. This fix tries to find it in both paths.


<?php

namespace Che\BuildGuild;

use Che\BuildGuild\Installer\GuildInstaller;
use Che\BuildGuild\Installer\ScriptRunner;
use Che\BuildGuild\Util\Environment;
use Composer\Config;
use Composer\Downloader\DownloadManager;
use Composer\Downloader;
use Composer\Json\JsonFile;
use Composer\Repository\ComposerRepository;
use Composer\Repository\InstalledFilesystemRepository;

/**
 * Class BuildFactory
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class GuildFactory
{
    private $config;
    private $env;

    public function __construct(GuildConfig $config, Environment $env)
    {
        $this->config = $config;
        $this->env = $env;
    }

    public function build()
    {
        $remoteRepository = new ComposerRepository(
            ['url' => $this->config->getRepository()],
            $this->env->getIo(),
            $this->config->getComposer()
        );

        $localRepository = new InstalledFilesystemRepository(new JsonFile($this->config->getLocalRepository()));

        $installer = new GuildInstaller(
            $this->config->getInstallDir(), $this->createDownloadManager(),
            $this->env->getProcess(), $this->env->getFilesystem()
        );

        return new Guild($remoteRepository, $localRepository, $installer);
    }

    private function createDownloadManager()
    {
        $dm = new DownloadManager(false, $this->env->getFilesystem());

        $dm->setDownloader('tar', new Downloader\TarDownloader($this->env->getIo(), $this->config->getComposer()));

        return $dm;
    }
}

<?php

namespace Che\BuildGuild;

use Che\BuildGuild\Installer\GuildInstaller;
use Che\BuildGuild\Installer\ScriptRunner;
use Che\BuildGuild\Util\Environment;
use Composer\Config;
use Composer\Downloader\DownloadManager;
use Composer\Downloader;
use Composer\Json\JsonFile;
use Composer\Repository\ComposerRepository;
use Composer\Repository\InstalledFilesystemRepository;

/**
 * Class BuildFactory
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class GuildFactory
{
    private $config;
    private $env;

    public function __construct(GuildConfig $config, Environment $env)
    {
        $this->config = $config;
        $this->env = $env;
    }

    public function build()
    {
        $remoteRepository = new ComposerRepository(
            ['url' => $this->config->getRepository()],
            $this->env->getIo(),
            $this->config->getComposer()
        );

        $localRepository = new InstalledFilesystemRepository(new JsonFile($this->config->getLocalRepository()));

        $installer = new GuildInstaller(
            $this->config->getInstallDir(), $this->createDownloadManager(),
            $this->env->getProcess(), $this->env->getFilesystem()
        );

        return new Guild($remoteRepository, $localRepository, $installer, $this->config->getStability());
    }

    private function createDownloadManager()
    {
        $dm = new DownloadManager(false, $this->env->getFilesystem());

        $dm->setDownloader('tar', new Downloader\TarDownloader($this->env->getIo(), $this->config->getComposer()));

        return $dm;
    }
}

Fix stability option in config

Fix stability option in config


<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;

class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface
{
    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @param Configuration $config
     */
    public function setConfig(Configuration $config)
    {
        $this->config = $config;
    }

    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $tag = $element->getTagName();
        $value = $element->getValue();

        if ($tag === 'i' || $tag === 'em') {
            $style = $this->config->getOption('italic_style');
        } else {
            $style = $this->config->getOption('bold_style');
        }

        return $style . $value . $style;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('em', 'i', 'strong', 'b');
    }
}

<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;

class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface
{
    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @param Configuration $config
     */
    public function setConfig(Configuration $config)
    {
        $this->config = $config;
    }

    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $tag = $element->getTagName();
        $value = $element->getValue();

        if ($tag === 'i' || $tag === 'em') {
            $style = $this->config->getOption('italic_style');
        } else {
            $style = $this->config->getOption('bold_style');
        }

        $prefix = ltrim($value) !== $value ? ' ' : '';
        $suffix = rtrim($value) !== $value ? ' ' : '';

        return $prefix . $style . trim($value) . $style . $suffix;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('em', 'i', 'strong', 'b');
    }
}

Fix issue with spaces inside emphasis tags

If value starts or ends with a space, remove space and re-add it outside
markdown tags


<?php
    /**
     * A base implementation for exceptions thrown by the framework.
     *
     * @author Jorgen Evens <jorgen@wlab.be>
     * @package WebLab
     * @subpackage Exception
     *
     */
    abstract class WebLab_Exception extends Exception {

    	protected $_trace;

        public static function reporting() {
            $error_reporting = WebLab_Config::getApplicationConfig()->get( 'Application.Error.reporting' );
            error_reporting( $error_reporting );
        }

    	protected function _updateTrace() {
    		if( empty( $this->_trace ) )
    			$this->_trace = $this->getTrace();
    	}

    	public function getClass() {
    		$this->_updateTrace();
    		return $this->_trace[0]['class'];
    	}

    	public function getMethod() {
    		$this->_updateTrace();
    		return $this->_trace[0]['function'];
    	}

    }

<?php
    /**
     * A base implementation for exceptions thrown by the framework.
     *
     * @author Jorgen Evens <jorgen@wlab.be>
     * @package WebLab
     * @subpackage Exception
     *
     */
    abstract class WebLab_Exception extends Exception {

    	protected $_trace;

        public static function reporting() {
            $error_reporting = WebLab_Config::getApplicationConfig()->get( 'Application.Error.reporting' );
            if( is_string( $error_reporting ) ) {
                $error_reporting = constant( $error_reporting );
            }
            error_reporting( $error_reporting );
        }

    	protected function _updateTrace() {
    		if( empty( $this->_trace ) )
    			$this->_trace = $this->getTrace();
    	}

    	public function getClass() {
    		$this->_updateTrace();
    		return $this->_trace[0]['class'];
    	}

    	public function getMethod() {
    		$this->_updateTrace();
    		return $this->_trace[0]['function'];
    	}

    }

Allow error_reporting config to contain constants


<?php

namespace Colorium\Stateful;

abstract class Auth
{

    /** @var Provider */
    protected static $provider;

    /** @var string */
    protected static $root = '__AUTH__';

    /**
     * Load session provider
     *
     * @param Provider $provider
     * @return Provider
     */
    public static function provider(Provider $provider = null)
    {
        if($provider) {
            static::$provider = $provider;
        }
        elseif(!static::$provider) {
            static::$provider = new Provider\Native(static::$root);
        }

        return static::$provider;
    }

    /**
     * Get user rank
     *
     * @return int
     */
    public static function rank()
    {
        return static::provider()->get('rank', 0);
    }

    /**
     * Get user object
     *
     * @return object
     */
    public static function user()
    {
        return static::provider()->get('user');
    }

    /**
     * Log user in session
     *
     * @param int $rank
     * @param object $user
     */
    public static function login($rank = 1, $user = null)
    {
        static::provider()->set('rank', $rank);
        static::provider()->set('user', $user);
    }

    /**
     * Log user out of session
     */
    public static function logout()
    {
        static::provider()->drop('rank');
        static::provider()->drop('user');
    }

}

<?php

namespace Colorium\Stateful;

abstract class Auth
{

    /** @var provider */
    protected static $provider;

    /** @var \Closure */
    protected static $factory;

    /** @var object */
    protected static $user;

    /** @var string */
    protected static $root = '__AUTH__';

    /**
     * Load session provider
     *
     * @param provider $provider
     * @return provider
     */
    public static function provider(provider $provider = null)
    {
        if($provider) {
            static::$provider = $provider;
        }
        elseif(!static::$provider) {
            static::$provider = new provider\Native(static::$root);
        }

        return static::$provider;
    }

    /**
     * Set user factory
     *
     * @param \Closure $factory
     */
    public static function factory(\Closure $factory)
    {
        static::$factory = $factory;
    }

    /**
     * Get user rank
     *
     * @return int
     */
    public static function rank()
    {
        return static::provider()->get('rank', 0);
    }

    /**
     * Get user ref
     *
     * @return string
     */
    public static function ref()
    {
        return static::provider()->get('ref');
    }

    /**
     * Get user object
     *
     * @return object
     */
    public static function user()
    {
        if(!static::$user and static::$factory) {
            static::$user = call_user_func(static::$factory, static::ref());
        }

        return static::$user;
    }

    /**
     * Log user in session
     *
     * @param int $rank
     * @param string $ref
     */
    public static function login($rank = 1, $ref = null)
    {
        static::provider()->set('rank', $rank);
        static::provider()->set('ref', $ref);
    }

    /**
     * Log user out of session
     */
    public static function logout()
    {
        static::provider()->drop('rank');
        static::provider()->drop('ref');
    }

}

Add user factory to auth handler

Add user factory to auth handler


<?php

namespace React\Http;

use Evenement\EventEmitter;
use React\Stream\ReadableStream;
use React\Stream\WritableStream;
use React\Stream\Util;

class Request extends EventEmitter implements ReadableStream
{
    private $method;
    private $path;
    private $query;
    private $httpVersion;
    private $headers;

    public function __construct($method, $path, $query = array(), $httpVersion = '1.1', $headers = array())
    {
        $this->method = $method;
        $this->path = $path;
        $this->query = $query;
        $this->httpVersion = $httpVersion;
        $this->headers = $headers;
    }

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

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

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

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

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

    public function pause()
    {
        $this->emit('pause');
    }

    public function resume()
    {
        $this->emit('resume');
    }

    public function close()
    {
        $this->emit('end');
        $this->removeAllListeners();
    }

    public function pipe(WritableStream $dest, array $options = array())
    {
        Util::pipe($this, $dest, $options);

        return $this;
    }
}

<?php

namespace React\Http;

use Evenement\EventEmitter;
use React\Stream\ReadableStream;
use React\Stream\WritableStream;
use React\Stream\Util;

class Request extends EventEmitter implements ReadableStream
{
    private $method;
    private $path;
    private $query;
    private $httpVersion;
    private $headers;

    public function __construct($method, $path, $query = array(), $httpVersion = '1.1', $headers = array())
    {
        $this->method = $method;
        $this->path = $path;
        $this->query = $query;
        $this->httpVersion = $httpVersion;
        $this->headers = $headers;
    }

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

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

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

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

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

    public function pause()
    {
        $this->emit('pause');
    }

    public function resume()
    {
        $this->emit('resume');
    }

    public function close()
    {
        $this->emit('end');
        $this->removeAllListeners();
    }

    public function pipe(WritableStream $dest, array $options = array())
    {
        Util::pipe($this, $dest, $options);

        return $dest;
    }
}

[Stream] Return destination stream from pipe() instead of source stream


<?php

namespace Aviator\Helpdesk\Models;

use Illuminate\Database\Eloquent\Model;

class Pool extends Model
{
    protected $guarded = [];

    /**
     * Set the table name from the Helpdesk config
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setTable(config('helpdesk.tables.pool'));
    }

    public function agents() {
        return $this->belongsToMany(Agent::class)->withPivot('is_team_lead')->withTimestamps();
    }

    public function teamLeads() {
        return $this->belongsToMany(Agent::class, config('helpdesk.tables.agent_pool'))
            ->withPivot('is_team_lead')
            ->withTimestamps()
            ->wherePivot('is_team_lead', 1);
    }

}

<?php

namespace Aviator\Helpdesk\Models;

use Illuminate\Database\Eloquent\Model;

class Pool extends Model
{
    protected $guarded = [];

    /**
     * Set the table name from the Helpdesk config
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setTable(config('helpdesk.tables.pools'));
    }

    public function agents() {
        return $this->belongsToMany(Agent::class)->withPivot('is_team_lead')->withTimestamps();
    }

    public function teamLeads() {
        return $this->belongsToMany(Agent::class, config('helpdesk.tables.agent_pool'))
            ->withPivot('is_team_lead')
            ->withTimestamps()
            ->wherePivot('is_team_lead', 1);
    }

}

Fix calling nonexistent config value

Fix calling nonexistent config value


<?php

namespace Gregoriohc\Preview;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->handleConfigs();

        if (!$this->app->routesAreCached() && $this->isEnabled()) {
            $middleware = [];
            if (request()->has('_middleware')) {
                $middleware = array_merge(config('preview.middleware'), explode(',', request('_middleware')));
            }

            Route::group(['middleware' => $middleware], function () {
                $route = trim(config('preview.route'), '\\');
                Route::get($route.'/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
            });
        }
    }

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

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

    private function handleConfigs()
    {
        $configPath = __DIR__.'/../config/preview.php';

        $this->publishes([$configPath => config_path('preview.php')]);

        $this->mergeConfigFrom($configPath, 'preview');
    }

    public static function isEnabled()
    {
        return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
    }
}

<?php

namespace Gregoriohc\Preview;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->handleConfigs();

        if (!$this->app->routesAreCached()) {
            $middleware = [];
            if (request()->has('_middleware')) {
                $middleware = array_merge(config('preview.middleware'), explode(',', request('_middleware')));
            }

            Route::group(['middleware' => $middleware], function () {
                $route = trim(config('preview.route'), '\\');
                Route::get($route.'/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
            });
        }
    }

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

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

    private function handleConfigs()
    {
        $configPath = __DIR__.'/../config/preview.php';

        $this->publishes([$configPath => config_path('preview.php')]);

        $this->mergeConfigFrom($configPath, 'preview');
    }

    public static function isEnabled()
    {
        return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
    }
}

Remove route ignore adding if not enabled


<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars/';
$router['validator'] = 'validator/';
$router['submit'] = 'submit/';
$router['bounce'] = 'bounce/';

/*
 * Identify which method is being requested.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{
	$method = substr($url_components['path'], 1, strpos($method, '/'));
}
if ( ($method === FALSE) || !isset($router[$method]) )
{
	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
}

include $router[$method] . '.php';
/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';

/*
 * Identify which method is being requested.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{
	$method = substr($url_components['path'], 1, strpos($method, '/'));
}
if ( ($method === FALSE) || !isset($router[$method]) )
{
	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
}

include $router[$method] . '.php';
/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

Drop trailing slashes from routing paths


<?php if (have_posts()): while (have_posts()) : the_post(); ?>
  <article id="post-<?php the_ID(); ?>" <?php post_class('loop-item loop-item--tema'); ?>>
    <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
      <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
        <?php echo get_the_label(); ?>
        <?php the_post_thumbnail('loop-image-large'); ?>

    <?php endif; ?>
      <?php $tema_image = get_field('tema_image'); ?>

        <img src="<?php echo $tema_image['sizes']["tema-image-large"]; ?>" alt="">

          <a class="post-label" href="<?php echo get_permalink(); ?>">Tema <?php the_title(); ?>

<a href="<?php echo get_permalink(); ?>"><?php echo get_field('tema_header'); ?>

<?php echo get_field('tema_description'); ?>

<?php the_time('F j, Y'); ?>

<?php endwhile; ?>
<?php else: ?>

<?php _e( 'Det finns inga teman ännu.', 'pedagog' ); ?>

<?php endif; ?>

<?php if (have_posts()): while (have_posts()) : the_post(); ?>
  <article id="post-<?php the_ID(); ?>" <?php post_class('loop-item loop-item--tema'); ?>>
      <?php $tema_image = get_field('tema_image'); ?>

        <img src="<?php echo $tema_image['sizes']["tema-image-large"]; ?>" alt="">

          <a class="post-label" href="<?php echo get_permalink(); ?>">Tema <?php the_title(); ?>

<a href="<?php echo get_permalink(); ?>"><?php echo get_field('tema_header'); ?>

<?php echo get_field('tema_description'); ?>

<?php the_time('F j, Y'); ?>

<?php endwhile; ?>
<?php else: ?>

<?php _e( 'Det finns inga teman ännu.', 'pedagog' ); ?>

<?php endif; ?>

Remove featured image from the ”Teman” loop


<?php

namespace Isbn;

class Validation {

    public static function isbn($isbn)
    {
        if (strlen($isbn) == 13)
            return Validation::isbn13($isbn);
        if (strlen($isbn) == 10)
            return Validation::isbn10($isbn);
        return false;
    }

    public static function isbn10($isbn)
    {
        if (strlen($isbn) != 10)
            return false;
        $check = 0;
        for ($i = 0; $i < 10; $i++)
            if ($isbn[$i] == "X")
                $check += 10 * intval(10 - $i);
            else
                $check += intval($isbn[$i]) * intval(10 - $i);
        return $check % 11 == 0;
    }

    public static function isbn13($isbn)
    {
        if (strlen($isbn) != 13)
            return false;
        $check = 0;
        for ($i = 0; $i < 13; $i+=2)
            $check += substr($isbn, $i, 1);
        for ($i = 1; $i < 12; $i+=2)
            $check += 3 * substr($isbn, $i, 1);
        return $check % 10 == 0;
    }
}

<?php

namespace Isbn;

class Validation {

    public static function isbn($isbn)
    {
        if (Check::is13($isbn))
            return Validation::isbn13($isbn);
        if (Check::is10($isbn))
            return Validation::isbn10($isbn);
        return false;
    }

    public static function isbn10($isbn)
    {
        if (strlen($isbn) != 10)
            return false;
        $check = 0;
        for ($i = 0; $i < 10; $i++)
            if ($isbn[$i] == "X")
                $check += 10 * intval(10 - $i);
            else
                $check += intval($isbn[$i]) * intval(10 - $i);
        return $check % 11 == 0;
    }

    public static function isbn13($isbn)
    {
        if (strlen($isbn) != 13)
            return false;
        $check = 0;
        for ($i = 0; $i < 13; $i+=2)
            $check += substr($isbn, $i, 1);
        for ($i = 1; $i < 12; $i+=2)
            $check += 3 * substr($isbn, $i, 1);
        return $check % 10 == 0;
    }
}

Use more widely the new Check class

Use more widely the new Check class


<?php

namespace App\Console\Commands\Admin;

use App\Console\Commands\Traits\AskForPassword;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Contracts\Hashing\Hasher as Hash;

class ChangePasswordCommand extends Command
{
    use AskForPassword;

    protected $name = 'koel:admin:change-password';
    protected $description = "Change the default admin's password";

    private $hash;

    public function __construct(Hash $hash)
    {
        parent::__construct();
        $this->hash = $hash;
    }

    public function handle(): void
    {
        /** @var User|null $user */
        $user = User::where('is_admin', true)->first();

        if (!$user) {
            $this->error('An admin account cannot be found. Have you set up Koel yet?');

            return;
        }

        $this->comment("Changing the default admin's password (ID: {$user->id}, email: {$user->email})");

        $user->password = $this->hash->make($this->askForPassword());
        $user->save();

        $this->comment('Alrighty, your new password has been saved. Enjoy! 👌');
    }
}

<?php

namespace App\Console\Commands\Admin;

use App\Console\Commands\Traits\AskForPassword;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Contracts\Hashing\Hasher as Hash;

class ChangePasswordCommand extends Command
{
    use AskForPassword;

    protected $signature = "koel:admin:change-password
                            {email? : The user's email. If empty, will get the default admin user.}";
    protected $description = "Change a user's password";

    private $hash;

    public function __construct(Hash $hash)
    {
        parent::__construct();
        $this->hash = $hash;
    }

    public function handle(): void
    {
        $email = $this->argument('email');

        /** @var User|null $user */
        $user = $email ? User::where('email', $email)->first() : User::where('is_admin', true)->first();

        if (!$user) {
            $this->error('The user account cannot be found.');

            return;
        }

        $this->comment("Changing the user's password (ID: {$user->id}, email: {$user->email})");

        $user->password = $this->hash->make($this->askForPassword());
        $user->save();

        $this->comment('Alrighty, the new password has been saved. Enjoy! 👌');
    }
}

feat: Allow changing password of any user from command line


<?php
class Kwc_Form_Dynamic_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
    public static function getSettings($masterComponentClass)
    {
        $ret = parent::getSettings($masterComponentClass);

        //form nicht übersetzen, sondern die exakt gleiche wie im master verwenden
        $g = Kwc_Abstract::getSetting($masterComponentClass, 'generators');
        $ret['generators']['child']['component']['form'] = $g['child']['component']['form'];
        $ret['generators']['child']['masterComponentsMap'][$g['child']['component']['form']] = $g['child']['component']['form'];

        $ret['ownModel'] = 'Kwf_Component_FieldModel';

        return $ret;
    }

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

        $ret['data'] = $data;
        $ret['chained'] = $data->chained;
        $ret['template'] = self::getTemplateFile($data->chained->componentClass);

        $ret['form'] = $this->getData()->getChildComponent('-form');

        return $ret;
    }

    public function getMailSettings()
    {
        $ret = $this->getData()->chained->getComponent()->getMailSettings();
        $row = $this->getData()->getComponent()->getRow();
        if ($row->subject) $ret['subject'] = $row->subject;
        if ($ret['send_confirm_mail'] && $row->confirm_subject) $ret['confirm_subject'] = $row->confirm_subject;
        return $ret;
    }
}

<?php
class Kwc_Form_Dynamic_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
    public static function getSettings($masterComponentClass)
    {
        $ret = parent::getSettings($masterComponentClass);

        //form nicht übersetzen, sondern die exakt gleiche wie im master verwenden
        $g = Kwc_Abstract::getSetting($masterComponentClass, 'generators');
        $ret['generators']['child']['component']['form'] = $g['child']['component']['form'];
        $ret['generators']['child']['masterComponentsMap'][$g['child']['component']['form']] = $g['child']['component']['form'];

        $ret['ownModel'] = 'Kwf_Component_FieldModel';

        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $data = $this->getData();
        $ret['data'] = $data;
        $ret['chained'] = $data->chained;
        $ret['template'] = self::getTemplateFile($data->chained->componentClass);

        $ret['form'] = $this->getData()->getChildComponent('-form');

        return $ret;
    }

    public function getMailSettings()
    {
        $ret = $this->getData()->chained->getComponent()->getMailSettings();
        $row = $this->getData()->getComponent()->getRow();
        if ($row->subject) $ret['subject'] = $row->subject;
        if ($ret['send_confirm_mail'] && $row->confirm_subject) $ret['confirm_subject'] = $row->confirm_subject;
        return $ret;
    }
}

Fix Trl Form_Dynamic: add missing parent call to getTemplateVars

cssClass was missing


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Remove --dev from composer install.

Remove --dev from composer install.

--dev is the default.


<?php
namespace MicroFW\Routing;

use MicroFW\Http\Response;
use MicroFW\Http\IResponse;
use MicroFW\Core\Exceptions\NotValidResponseException;

class Router
{
    /** @var array */
    private $routes;

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

    /**
     * Return response for request based on URL.
     *
     * @param $request MicroFW\Http\Request
     * @return MicroFW\Http\Response
     */
    public function getResponse($request)
    {
        $path = $request->getPath();
        $response = new Response('
404
', 404);
        foreach ($this->routes as $url => $controller) {
            $matches = [];
            if (preg_match('/^[\/]{0,1}' . $url . '/', $path, $matches)) {
                $matches = $this->cleanRoutesParameters($matches);
                $response = $controller($request, $matches);
                break;
            }
        }
        if ($response instanceof IResponse) {
            return $response;
        } else {
            throw new NotValidResponseException(
                gettype($response) ." is not a response object."
            );
        }
    }

    private function cleanRoutesParameters($parameters)
    {
        $cleanedParameters = [];
        foreach ($parameters as $name => $value) {
            if (is_string($name)) {
                $cleanedParameters[$name] = $value;
            }
        }

        return $cleanedParameters;
    }
}

<?php
namespace MicroFW\Routing;

use MicroFW\Http\Response;
use MicroFW\Http\IResponse;
use MicroFW\Core\Exceptions\NotValidResponseException;

class Router
{
    /** @var array */
    private $routes;

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

    /**
     * Return response for request based on URL.
     *
     * @param $request MicroFW\Http\Request
     * @return MicroFW\Http\Response
     */
    public function getResponse($request)
    {
        $path = $request->getPath();
        $response = new Response('
404
', 404);
        foreach ($this->routes as $url => $controller) {
            $matches = [];
            if (preg_match('/^[\/]{0,1}' . $url . '/', $path, $matches)) {
                $matches = $this->cleanRoutesParameters($matches);
                $response = call_user_func($controller, $request, $matches);
                break;
            }
        }
        if ($response instanceof IResponse) {
            return $response;
        } else {
            throw new NotValidResponseException(
                gettype($response) ." is not a response object."
            );
        }
    }

    private function cleanRoutesParameters($parameters)
    {
        $cleanedParameters = [];
        foreach ($parameters as $name => $value) {
            if (is_string($name)) {
                $cleanedParameters[$name] = $value;
            }
        }

        return $cleanedParameters;
    }
}

Fix controller call for static methods

Fix controller call for static methods


<?php

namespace AppBundle\API\Details;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Organism;
use AppBundle\Service\DBVersion;
use \PDO as PDO;
use Symfony\Component\HttpFoundation\ParameterBag;

/**
 * Web Service.
 * Returns Organisms that posess a given trait
 */
class OrganismsWithTrait
{
    const DEFAULT_LIMIT = 100;

    private $manager;

    /**
     * OrganismsWithTrait constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    public function execute($trait_type_id)
    {
        return $this->manager->getRepository(Organism::class)->getOrganismByTrait($trait_type_id);
    }
}

<?php

namespace AppBundle\API\Details;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Entity\Organism;
use AppBundle\Service\DBVersion;
use \PDO as PDO;
use Symfony\Component\HttpFoundation\ParameterBag;

/**
 * Web Service.
 * Returns Organisms that posess a given trait
 */
class OrganismsWithTrait
{

    private $manager;

    /**
     * OrganismsWithTrait constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    public function execute($trait_type_id, $limit)
    {
        return $this->manager->getRepository(Organism::class)->getOrganismByTrait($trait_type_id, $limit);
    }
}

Remove limit as constant and add it as parameter


<?php

namespace Superhelio\Commands\Commands;

use Illuminate\Console\Command;

class Reload extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'superhelio:reload';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete database tables, migrate and run seeds';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if ($this->confirm('Rollback all your database tables, recreate them and seed?')) {
            $this->call(
                'migrate:reset',
                [
                    '--no-interaction' => true,
                    '--env' => 'development',
                    '--verbose' => 3
                ]
            );
            $this->call(
                'migrate',
                [
                    '--seed' => true,
                    '--no-interaction' => true,
                    '--env' => 'development',
                    '--verbose' => 3
                ]
            );
        }
    }
}

<?php

namespace Superhelio\Commands\Commands;

use Illuminate\Console\Command;

class Reload extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'superhelio:reload';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback migrations, migrate and run seeds';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if ($this->confirm('Rollback all your database tables, recreate them and seed?')) {
            $this->call(
                'migrate:reset',
                [
                    '--no-interaction' => true,
                    '--env' => 'development',
                    '--verbose' => 3
                ]
            );
            $this->call(
                'migrate',
                [
                    '--seed' => true,
                    '--no-interaction' => true,
                    '--env' => 'development',
                    '--verbose' => 3
                ]
            );
        }
    }
}

Set better description to superhelio:reload


<?php

namespace Michaeljennings\Feed\Contracts;

interface Store
{

}

<?php

namespace Michaeljennings\Feed\Contracts;

interface Store
{
    /**
     * Get all of the unread notifications where their notifiable type
     * is in the array of types, and their notifiable id is in the
     * array of ids.
     *
     * @param array $types
     * @param array $ids
     * @return Notification[]
     */
    public function getNotifications(array $types, array $ids);

    /**
     * Get all of the read notifications where their notifiable type
     * is in the array of types, and their notifiable id is in the
     * array of ids.
     *
     * @param array $types
     * @param array $ids
     * @return Notification[]
     */
    public function getReadNotifications(array $types, array $ids);

    /**
     * Add a limit to the query.
     *
     * @param int $limit
     * @return Store
     */
    public function limit($limit);

    /**
     * Add an offset to the query.
     *
     * @param int $offset
     * @return Store
     */
    public function offset($offset);

    /**
     * Mark the provided notification as read.
     *
     * @param Notification|int $notification
     * @return mixed
     */
    public function markAsRead($notification);

    /**
     * Mark the provided notification as unread.
     *
     * @param Notification|int $notification
     * @return mixed
     */
    public function markAsUnread($notification);
}

Add stubs to the store contract

Add stubs to the store contract


<?php

// BaseTool & Localization
require_once( __DIR__ . '/lib/basetool/InitTool.php' );
require_once( KR_TSINT_START_INC );

// Class for this tool
require_once( __DIR__ . '/class.php' );
$kgTool = new KrMwSnapshots();

$I18N = new TsIntuition( 'Mwsnapshots' );

$toolConfig = array(
	'displayTitle' => 'mwSnapshots',
	'krinklePrefix' => false,
	'remoteBasePath' => dirname( $kgConf->getRemoteBase() ). '/',
	'revisionId' => '0.1.2',
	'styles' => array(
		'main.css',
	),
	'scripts' => array(
		'main.js',
	),
);

// Local settings
require_once( __DIR__ . '/local.php' );

$kgBaseTool = BaseTool::newFromArray( $toolConfig );
$kgBaseTool->setSourceInfoGithub( 'Krinkle', 'ts-krinkle-mwSnapshots', __DIR__ );

<?php

// BaseTool & Localization
require_once( __DIR__ . '/lib/basetool/InitTool.php' );
require_once( KR_TSINT_START_INC );

// Class for this tool
require_once( __DIR__ . '/class.php' );
$kgTool = new KrMwSnapshots();

$I18N = new TsIntuition( 'Mwsnapshots' );

$toolConfig = array(
	'displayTitle' => 'Snapshots',
	'krinklePrefix' => false,
	'remoteBasePath' => dirname( $kgConf->getRemoteBase() ). '/',
	'revisionId' => '0.1.2',
	'styles' => array(
		'main.css',
	),
	'scripts' => array(
		'main.js',
	),
);

// Local settings
require_once( __DIR__ . '/local.php' );

$kgBaseTool = BaseTool::newFromArray( $toolConfig );
$kgBaseTool->setSourceInfoGithub( 'Krinkle', 'ts-krinkle-mwSnapshots', __DIR__ );

Change title from mwSnapshots to Snapshots


<?php
class trackingFilter extends sfFilter
{
  public function execute ($filterChain)
  {
    if ($this->isFirstCall())
    {
      $user = $this->getContext()->getUser();

      if($user->isAuthenticated())
      {

        //Check if the user still exists
        $q = Doctrine_Query::create()
          ->useResultCache(new Doctrine_Cache_Apc())
          ->setResultCacheLifeSpan(60 * 5) //5 minutes
          ->from('Users')
          ->andWhere('id = ?',$user->getId());
        $usr=$q->fetchOne();

        if(!$usr)
        {
          $user->clearCredentials();
          $user->setAuthenticated(false);

          return $this->getContext()->getController()->redirect('homepage');
        }
        $user->setAttribute('db_user_type', $usr->getDbUserType());
      }
      if($user->isAuthenticated() && sfConfig::get('dw_tracking_enabled',null))
      {
        $conn = Doctrine_Manager::connection();
        $conn->exec("select fct_set_user(".$user->getId().");");
      }
    }

    $filterChain->execute();
  }
}

<?php
class trackingFilter extends sfFilter
{
  public function execute ($filterChain)
  {
    if ($this->isFirstCall())
    {
      $user = $this->getContext()->getUser();

      if($user->isAuthenticated())
      {

        //Check if the user still exists
        $q = Doctrine_Query::create()
          ->useResultCache(new Doctrine_Cache_Apc())
          ->setResultCacheLifeSpan(60 * 5) //5 minutes
          ->from('Users')
          ->andWhere('id = ?',$user->getId());
        $usr=$q->fetchOne();

        if(!$usr)
        {
          $user->clearCredentials();
          $user->setAuthenticated(false);

          return $this->getContext()->getController()->redirect('homepage');
        }
        $user->setAttribute('db_user_type', $usr->getDbUserType());
      }
      if($user->isAuthenticated() && sfConfig::get('dw_tracking_enabled',null))
      {
        $conn = Doctrine_Manager::connection();
        $conn->exec("select fct_set_user(".$user->getId().");");
      }

      if($user->isAuthenticated() && function_exists('apache_note')) {
        apache_note('username', $user->getId() );
        apache_note('sessionID', session_id());
      }
    }

    $filterChain->execute();
  }
}

Add apache note with userid and session id


@extends('emails.template')

@section('content')
    Here's your weekly report for {{ $space->name }}.

    This week (#{{ $week }}) you've

Spent {!! $space->currency->symbol !!} {{ number_format($totalSpent / 100, 2) }}

        @if (count($largestSpendingWithTag))

Most of which you've spent on {{ $largestSpendingWithTag[0]->tag_name }} ({!! $space->currency->symbol !!} {{ number_format($largestSpendingWithTag[0]->amount / 100, 2) }})

        @endif

    If you don't want to receive a weekly report, head over to settings and let us know.
@endsection

@extends('emails.template')

@section('content')
    Here's your weekly report for {{ $space->name }}.

    This week (#{{ $week }}) you've

Spent {!! $space->currency->symbol !!} {{ number_format($totalSpent / 100, 2) }}

        @if (count($largestSpendingWithTag))

Most of which you've spent on {{ $largestSpendingWithTag[0]->tag_name }} ({!! $space->currency->symbol !!} {{ number_format($largestSpendingWithTag[0]->amount / 100, 2) }})

        @endif

    Tired of these reports? Change your preferences.
@endsection

Rephrase sentence at bottom of weekly report for changing e-mail preferences


<?php

namespace Controller\Page;

class PrivatePage extends \Controller\AbstractPageController
{

    public function get()
    {
        if (PUBLIC_PAGE) {
            $this->response->redirect('/');
        }

        $parameters['path']     = $this->router->path();
        $parameters['template'] = $this->template->get();

        return $this->response->render('_private', $parameters);
    }

    public function post()
    {
        $post                   = $this->request->post();
        $parameters['path']     = $this->router->path();
        $parameters['template'] = $this->template->get();

        if (DEMO) {
            $this->session->set('authenticated', true);
            return $this->response->redirect('/dashboard/components');
        }

        if (PRIVATE_PAGE_PASSWORD == $post['password']) {
            $this->session->set('authenticated', true);
            return $this->response->redirect('/');
        }

        $parameters['error'] = 'Incorrect password';
        return $this->response->render('_private', $parameters);
    }
}

<?php

namespace Controller\Page;

class PrivatePage extends \Controller\AbstractPageController
{

    public function get()
    {
        if (PUBLIC_PAGE) {
            $this->response->redirect('/');
        }

        $parameters['path']     = $this->router->path();
        $parameters['template'] = $this->template->get();

        return $this->response->render('_private', $parameters);
    }

    public function post()
    {
        $post                   = $this->request->post();
        $parameters['path']     = $this->router->path();
        $parameters['template'] = $this->template->get();

        if (DEMO) {
            $this->session->set('authenticated', true);
        }

        if (PRIVATE_PAGE_PASSWORD == $post['password']) {
            $this->session->set('authenticated', true);
            return $this->response->redirect('/');
        }

        $parameters['error'] = 'Incorrect password';
        return $this->response->render('_private', $parameters);
    }
}

Fix a demo mode bug

Fix a demo mode bug


<?php

namespace NicolasMahe\SlackOutput;

use Illuminate\Support\ServiceProvider as ServiceProviderParent;

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

  /**
   * Bootstrap any application services.
   *
   * @return void
   */
  public function boot()
  {
    //config
    $this->publishes([__DIR__ . '/config.php' => config_path('slack-output.php')]);

    //command
    $this->commands(
      Command\SlackPost::class
    );
  }

  /**
   * Register the application services.
   *
   * @return void
   */
  public function register()
  {
    $this->mergeConfigFrom(__DIR__ . '/config.php', 'slack-output');

    $this->app->singleton(Service::class, function () {
      return new Service(config('slack-output'));
    });
  }

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

}

<?php

namespace NicolasMahe\SlackOutput;

use Illuminate\Support\ServiceProvider as ServiceProviderParent;

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

  /**
   * Bootstrap any application services.
   *
   * @return void
   */
  public function boot()
  {
    //config
    if (class_exists('Illuminate\Foundation\Application', false)) {
      $this->publishes([__DIR__ . '/config.php' => config_path('slack-output.php')]);
    }

    //command
    $this->commands(
      Command\SlackPost::class
    );
  }

  /**
   * Register the application services.
   *
   * @return void
   */
  public function register()
  {
    $this->mergeConfigFrom(__DIR__ . '/config.php', 'slack-output');

    $this->app->singleton(Service::class, function () {
      return new Service(config('slack-output'));
    });
  }

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

}

Check if its Laravel, avoid publishing the configuration file if its Lumen


<?php

namespace app\modules\rest\versions\v1\controllers;

use Yii;
use app\models\Poll;
use app\models\Code;
use app\components\controllers\VotingRestController;
use yii\helpers\ArrayHelper;

class PollController extends VotingRestController
{
    public $modelClass = 'app\models\Poll';

    public function actionTest()
    {

        $items = Poll::find()->asArray()->all();
        //\Yii::$app->response->format = 'csv';
        $test=[
            'error'=> false,
            'result'=>$items,
        ];
        //return $items;
        return $test;
    }

    public function actionGet() {
        $token = Yii::$app->request->get('token'); // Better way to get this?
        $code = Code::findCodeByToken($token);
        if(!$code || !$code->isValid() || $code->isUsed()) {
            return ['success' => false, 'error' => 'Invalid voting code'];
        }
        $poll = $code->getPoll()->with(['options' => function($q) {
            $q->select(['id', 'text']);
        }])->select(['title', 'question', 'select_min', 'select_max', 'start_time', 'end_time'])->asArray()->one();
        return $poll;
    }
}

<?php

namespace app\modules\rest\versions\v1\controllers;

use Yii;
use app\models\Poll;
use app\models\Code;
use app\components\controllers\VotingRestController;
use yii\helpers\ArrayHelper;

class PollController extends VotingRestController
{
    public $modelClass = 'app\models\Poll';

    public function actionTest()
    {

        $items = Poll::find()->asArray()->all();
        //\Yii::$app->response->format = 'csv';
        $test=[
            'error'=> false,
            'result'=>$items,
        ];
        //return $items;
        return $test;
    }

    public function actionGet() {
        $token = Yii::$app->request->get('token'); // Better way to get this?
        $code = Code::findCodeByToken($token);
        if(!$code || !$code->isValid() || $code->isUsed()) {
            return ['success' => false, 'error' => 'Invalid voting code'];
        }

        $poll = $code->getPoll()->with(['options', 'organizer'])->one();
        $options = $poll->getOptions()->all();
        $organizer = $poll->getOrganizer()->one();
        $pollFields = ['title', 'question', 'select_min', 'select_max', 'start_time', 'end_time'];

        $json = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function($option) {
            $optionFields = ['id', 'text'];
            return $option->toArray($optionFields);
        }), 'organizer' => $organizer->toArray(['name', 'email'])]);
        return $json;
    }
}

Implement get poll API action

Implement get poll API action


<?php

namespace App\Exceptions;

use App\Exceptions\SolverException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;

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

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof ValidationException) {
            return response()->json([
                'message' => trans('error.validation'),
                'errors' => $exception->errors(),
            ], 422);
        }

        if ($exception instanceof SolverException) {
            return response()->json([
                'message' => trans('error.solution'),
            ], 422);
        }

        if ($exception instanceof InvalidSignatureException) {
            return response()->json([
                'message' => trans('error.signature'),
            ], 500);
        }

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

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;

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

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (ValidationException $e, $request) {
            return response()->json([
                'message' => trans('error.validation'),
                'errors' => $e->errors(),
            ], 422);
        });

        $this->renderable(function (InvalidSignatureException $e, $request) {
            return response()->json([
                'message' => trans('error.signature'),
            ], 500);
        });

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

Use exception renderable instead of uses of instanceof


<?php
	require_once(dirname(__FILE__) . '/config.php');
	require_once(dirname(__FILE__) . '/functions.php');

	$id = 0;
	if (!empty($_REQUEST['id'])) {
		$id = $_REQUEST['id'];
	} else if (!empty($argv[1])) {
		$id = $argv[1];
	}
	if (!is_numeric($id) || $id < 1 || !file_exists($xmldir . $id . '.xml')) {
		die();
	}

	$xmlfile = $xmldir . $id . '.xml';

	header("content-type: application/x-javascript");
	echo 'var layout = ' . xml2json($xmlfile, $id);
?>

<?php
	require_once(dirname(__FILE__) . '/config.php');
	require_once(dirname(__FILE__) . '/functions.php');

	$id = 0;
	if (!empty($_REQUEST['id'])) {
		$id = $_REQUEST['id'];
	} else if (!empty($argv[1])) {
		$id = $argv[1];
	}
	if (!is_numeric($id) || $id < 1 || !file_exists($xmldir . $id . '.xml')) {
		die();
	}

	$xmlfile = $xmldir . $id . '.xml';

	header("content-type: application/x-javascript");
	echo xml2json($xmlfile, $id);
?>

Drop the "var layout ="

Drop the "var layout ="


<?php

require('./vendor/Slim/Slim/Slim.php');

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/list-files', function () {

    $it = new RecursiveDirectoryIterator("Knowledge");

    $display = array ( 'md' );

    $result = array ();
    $result['files'] = array ();

    foreach(new RecursiveIteratorIterator($it) as $file)
    {
        //filter files
        if (in_array(strtolower(array_pop(explode('.', $file))), $display)) {
            $dir = explode ('/', $file);
            $filename = array_pop($dir);
            $dirname = implode($dir, '/');
            $result['files'][$dirname][] = ''.$filename;
        }
    }

    echo json_encode($result);
});

$app->post('/show-file-contents', function () use ($app) {

    $body = $app->request->getBody();
    $body = json_decode($body);

    $filename = $body->file;

    $result = array ();
    $result['file']['contents']         = file_get_contents(__DIR__ . '/' . $filename);
    $result['file']['lastModifiedDate'] = date("Y-m-d H:i:s",filemtime($filename));

    echo json_encode($result);
});

$app->run();

?>

<?php

require(__DIR__ . '/vendor/Slim/Slim/Slim.php');

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/list-files', function () use ($app) {

    $it = new RecursiveDirectoryIterator("Knowledge");

    $display = array ( 'md' );

    $result = array ();
    $result['files'] = array ();
    $slash = DIRECTORY_SEPARATOR;

    foreach(new RecursiveIteratorIterator($it) as $file)
    {
        //filter files
        if (in_array(strtolower(array_pop(explode('.', $file))), $display)) {
            $dir = explode ($slash, $file);
            $filename = array_pop($dir);
            $dirname = implode($dir, $slash);
            $result['files'][$dirname][] = ''.$filename;
        }
    }

    echo json_encode($result);
});

$app->post('/show-file-contents', function () use ($app) {

    $body = $app->request->getBody();
    $body = json_decode($body);

    $filename = $body->file;
    $slash = DIRECTORY_SEPARATOR;

    $result = array ();
    $result['file']['contents']         = file_get_contents(__DIR__ . $slash . $filename);
    $result['file']['lastModifiedDate'] = date("Y-m-d H:i:s",filemtime($filename));

    echo json_encode($result);
});

$app->run();

?>

Select separator by SO (backend)

Add: Select separator by SO (backend)