<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Block\BlockType\BlockType;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20161208000000 extends AbstractMigration
{

    protected function output($message)
    {
        $this->version->getConfiguration()->getOutputWriter()->write($message);
    }

    protected function updateBlocks()
    {
        $this->output(t('Refreshing blocks.'));
        $bt = BlockType::getByHandle('express_entry_detail');
        if (is_object($bt)) {
            $bt->refresh();
        }
        $bt = BlockType::getByHandle('page_attribute_display');
        if (is_object($bt)) {
            $bt->refresh();
        }
    }

    protected function updateEmptyFileAttributes()
    {
        $this->output(t('Updating old empty file attributes.'));
        $this->connection->executeQuery('update atFile set fID = null where fID = 0');
    }

    public function up(Schema $schema)
    {
        $this->updateBlocks();
        $this->updateEmptyFileAttributes();
    }

    public function down(Schema $schema)
    {
    }
}

<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Block\BlockType\BlockType;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20161208000000 extends AbstractMigration
{

    protected function output($message)
    {
        $this->version->getConfiguration()->getOutputWriter()->write($message);
    }

    protected function updateBlocks()
    {
        $this->output(t('Refreshing blocks.'));
        $bt = BlockType::getByHandle('express_entry_detail');
        if (is_object($bt)) {
            $bt->refresh();
        }
        $bt = BlockType::getByHandle('page_attribute_display');
        if (is_object($bt)) {
            $bt->refresh();
        }
    }

    protected function updateDoctrineXmlTables()
    {
        $this->output(t('Updating tables found in doctrine xml...'));
        // Update tables that still exist in db.xml
        \Concrete\Core\Database\Schema\Schema::refreshCoreXMLSchema(array(
            'TreeSearchQueryNodes',
        ));
    }

    protected function updateEmptyFileAttributes()
    {
        $this->output(t('Updating old empty file attributes.'));
        $this->connection->executeQuery('update atFile set fID = null where fID = 0');
    }

    public function up(Schema $schema)
    {
        $this->updateBlocks();
        $this->updateEmptyFileAttributes();
        $this->updateDoctrineXmlTables();
    }

    public function down(Schema $schema)
    {
    }
}

Fix tree search query nodes table not being added in update.

Former-commit-id: d8094d69cd4d32146eba4233b177ad6f6a278abd
Former-commit-id: 9ccf9dcf7a6df28610a0b8a4a2356a5f2cbf2e95


<?php

namespace App\Importer;

class ImportDataFactory
{
    /**
     * Instanciate an import data class depending on given file.
     *
     * @param  string  $filepath
     * @return \Gallib\Macope\Importer\ImportDataInterface
     */
    public static function create($filepath)
    {
        $factory = new PostFinanceImport($filepath);

        if ($factory->isValid()) {
            return $factory;
        }

        $factory = new MigrosBankImport($filepath);

        if ($factory->isValid()) {
            return $factory;
        }

        throw new \InvalidArgumentException("{$filepath->getClientOriginalName()} is not a valid file");
    }
}

<?php

namespace App\Importer;

class ImportDataFactory
{
    /**
     * Instanciate an import data class depending on given file.
     *
     * @param  string  $filepath
     * @return \Gallib\Macope\Importer\ImportDataInterface
     */
    public static function create($filepath)
    {
        $factory = new PostFinanceImport($filepath);

        if ($factory->isValid()) {
            return $factory;
        }

        $factory = new MigrosBankImport($filepath);

        if ($factory->isValid()) {
            return $factory;
        }

        throw new \InvalidArgumentException("File is not valid");
    }
}

Fix bug where filepath is a string

Fix bug where filepath is a string


<?php

namespace RadDB\Http\Controllers;

use Charts;
use RadDB\Machine;
use RadDB\TestDates;
use RadDB\GenData;
use RadDB\HVLData;
use RadDB\RadSurveyData;
use RadDB\RadiationOutput;
use Illuminate\Http\Request;

class QAController extends Controller
{
    /**
     * Index page for QA/survey data section
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Show a table of machines with QA data in the database
        // Get a list of the survey IDs in the gendata table
        $surveys = GenData::select('survey_id')->distinct()->get();
        $machines = TestDate::whereIn('id', $surveys->toArray())->get();

        return view('qa.index', [

        ]);
    }
}

<?php

namespace RadDB\Http\Controllers;

use Charts;
use RadDB\GenData;
use RadDB\HVLData;
use RadDB\Machine;
use RadDB\TestDates;
use RadDB\RadSurveyData;
use RadDB\RadiationOutput;
use Illuminate\Http\Request;

class QAController extends Controller
{
    /**
     * Index page for QA/survey data section
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Show a table of machines with QA data in the database
        // Get a list of the survey IDs in the gendata table
        $surveys = GenData::select('survey_id')->distinct()->get();
        $machines = TestDate::whereIn('id', $surveys->toArray())->get();

        return view('qa.index', [
            'surveys' => $surveys,
            'machines' => $machines,
        ]);
    }
}

Add variables to send to the view

Add variables to send to the view


<?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\Currency\Context;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    // Key used to store the currency in storage.
    const STORAGE_KEY = '_sylius.currency';

    /**
     * Get the default currency.
     *
     * @return string
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return string
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param string $currency
     */
    public function setCurrency($currency);
}

<?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\Currency\Context;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    // Key used to store the currency in storage.
    const STORAGE_KEY = '_sylius_currency';

    /**
     * Get the default currency.
     *
     * @return string
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return string
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param string $currency
     */
    public function setCurrency($currency);
}

Make STORAGE_KEY work when using CookieStorage

Unfortunately PHP will convert **dot**s into underscore when parsing cookie names! So we have to remove dots in our `STORAKE_KEY`s so that is possible to use a CookieStorage.

[The full list of field-name characters that PHP converts to _](http://ca.php.net/manual/en/language.variables.external.php#81080)
[A random blog post](http://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/)


<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** @var WC_Aplazame $aplazame */
global $aplazame;
if ( ! $aplazame->enabled ) {
	return;
}

/** @var WC_Product $product */
global $product;

switch ( $product->get_type() ) {
	case 'variable':
		$price_selector = '#main [itemtype="http://schema.org/Product"] .woocommerce-variation-price .amount';
		$price = '';
		break;
	default:
		$price_selector = '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount';
		$price = Aplazame_Filters::decimals( $product->get_price() );
}
?>

<div
	data-aplazame-simulator=""
	data-view="product"
	data-price='<?php echo $price_selector; ?>'
	data-currency="<?php echo get_woocommerce_currency(); ?>"
	data-stock="<?php echo $product->is_in_stock() ? 'true' : 'false'; ?>">
</div>

<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** @var WC_Aplazame $aplazame */
global $aplazame;
if ( ! $aplazame->enabled ) {
	return;
}

/** @var WC_Product $product */
global $product;

switch ( $product->get_type() ) {
	case 'variable':
		$price_selector = '#main [itemtype="http://schema.org/Product"] .single_variation_wrap .amount';
		$price = '';
		break;
	default:
		$price_selector = '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount';
		$price = Aplazame_Filters::decimals( $product->get_price() );
}
?>

<div
	data-aplazame-simulator=""
	data-view="product"
	data-price='<?php echo $price_selector; ?>'
	data-currency="<?php echo get_woocommerce_currency(); ?>"
	data-stock="<?php echo $product->is_in_stock() ? 'true' : 'false'; ?>">
</div>

Fix woocommerce-variation-price may not exists

Related 034e1fac038566cdc69d8f50b210e44ed8211d9d


<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 10/10/2018
 * Time: 08:38
 */

namespace vr\core\validators;

use vr\core\Inflector;
use yii\helpers\ArrayHelper;
use yii\validators\Validator;

/**
 * Class ArrayFilterValidator
 * @package vr\core\validators
 */
class ArrayFilterValidator extends Validator
{
    /**
     * @var
     */
    public $allowed = [];

    /**
     * @var bool
     */
    public $variablize = true;

    /**
     * @param \yii\base\Model $model
     * @param string          $attribute
     */
    public function validateAttribute($model, $attribute)
    {
        if (empty($this->allowed)) {
            $this->allowed = $model->fields();
        }

        if (!empty($this->allowed)) {

            if ($this->variablize) {
                foreach ($this->allowed as $key => $allowed) {
                    $this->allowed[$key] = Inflector::variablize($allowed);
                }
            }

            $model->$attribute = ArrayHelper::filter($model->$attribute, $this->allowed);
        }
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 10/10/2018
 * Time: 08:38
 */

namespace vr\core\validators;

use vr\core\Inflector;
use yii\helpers\ArrayHelper;
use yii\validators\Validator;

/**
 * Class ArrayFilterValidator
 * @package vr\core\validators
 */
class ArrayFilterValidator extends Validator
{
    /**
     * @var
     */
    public $allowed = [];

    /**
     * @var bool
     */
    public $variablize = true;

    /**
     * @param \yii\base\Model $model
     * @param string          $attribute
     */
    public function validateAttribute($model, $attribute)
    {
        if (empty($this->allowed)) {
            $this->allowed = $model->fields();
            $this->allowed = array_merge($this->allowed, array_keys($model->extraFields()));
        }

        if (!empty($this->allowed)) {

            if ($this->variablize) {
                foreach ($this->allowed as $key => $allowed) {
                    $this->allowed[$key] = Inflector::variablize($allowed);
                }
            }

            $model->$attribute = ArrayHelper::filter($model->$attribute, $this->allowed);
        }
    }
}

Add extraFields values to the list of defaultAttributes if the allowed property is empty


@extends('layouts/default')

{{-- Page title --}}
@section('title')
    Personal API Keys
    @parent
@stop

{{-- Page content --}}
@section('content')
     @if (!config('app.lock_passwords'))
        <passport-personal-access-tokens
            token-url="{{ url('oauth/personal-access-tokens') }}"
            scopes-url="{{ url('oauth/scopes') }}">
        </passport-personal-access-tokens>
     @else

{{ trans('general.feature_disabled') }}

    @endif
@stop

@section('moar_scripts')

@endsection

@extends('layouts/default')

{{-- Page title --}}
@section('title')
    Personal API Keys
    @parent
@stop

{{-- Page content --}}
@section('content')

                 @if (!config('app.lock_passwords'))
                    <passport-personal-access-tokens
                        token-url="{{ url('oauth/personal-access-tokens') }}"
                        scopes-url="{{ url('oauth/scopes') }}">
                    </passport-personal-access-tokens>
                 @else

{{ trans('general.feature_disabled') }}

                @endif

Your API endpoint is located at:

                {{ url('/api/v1') }}

When you generate an API token, be sure to copy it down immediately as they will not be visible to you again.

@stop

@section('moar_scripts')

@endsection

Add API endpoint to API keys page

Add API endpoint to API keys page

// TODO - localize it


<?php namespace Picqer\Financials\Exact\Persistance;

trait Storable {

    public function save()
    {
        if ($this->exists())
        {
            $this->fill($this->update());
        } else
        {
            $this->fill($this->insert());
        }

        return $this;
    }

    public function insert()
    {
        return $this->connection()->post($this->url, $this->json());
    }

    public function update()
    {
        return $this->connection()->put($this->url . "(guid'$this->primaryKey')", $this->json());
    }

    public function delete()
    {
        return $this->connection()->delete($this->url . "(guid'$this->primaryKey')");
    }
}

<?php namespace Picqer\Financials\Exact\Persistance;

trait Storable {

    public function save()
    {
        if ($this->exists())
        {
            $this->fill($this->update());
        } else
        {
            $this->fill($this->insert());
        }

        return $this;
    }

    public function insert()
    {
        return $this->connection()->post($this->url, $this->json());
    }

    public function update()
    {
        return $this->connection()->put($this->url . "(guid'" . $this->attributes[$this->primaryKey] . "')", $this->json());
    }

    public function delete()
    {
        return $this->connection()->delete($this->url . "(guid'" . $this->attributes[$this->primaryKey] . "')");
    }
}

Use the actual primary key value instead of the key name for updating/deleting.


<?php
namespace Stringizer\Transformers;

use Stringizer\Transformers\TransformerCaseInsensitive;

/**
 * StringFirstOccurrence
 *
 * @link https://github.com/jasonlam604/Stringizer
 * @copyright Copyright (c) 2016 Jason Lam
 * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
 */
class StringFirstOccurrence extends TransformerCaseInsensitive implements TransformerInterface
{

    private $needle;

    private $beforeNeedle;

    public function __construct($value, $needle, $beforeNeedle = false)
    {
        parent::__construct($value);
        $this->needle = $needle;
        $this->beforeNeedle = $beforeNeedle;
        $this->caseInsensitive = false;
    }

    /**
     * StringFirstOccurrence
     */
    public function execute()
    {
        if ($this->isCaseInsensitive())
            return mb_stristr($this->getValue(), $this->needle, $this->beforeNeedle);
        else
            return mb_strstr($this->getValue(), $this->needle, $this->beforeNeedle);
    }
}

<?php
namespace Stringizer\Transformers;

use Stringizer\Transformers\TransformerCaseInsensitive;

/**
 * StringFirstOccurrence
 *
 * @link https://github.com/jasonlam604/Stringizer
 * @copyright Copyright (c) 2016 Jason Lam
 * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
 */
class StringFirstOccurrence extends TransformerCaseInsensitive implements TransformerInterface
{

    private $needle;

    private $beforeNeedle;

    public function __construct($value, $needle, $beforeNeedle = false)
    {
        parent::__construct($value);
        $this->needle = $needle;
        $this->beforeNeedle = $beforeNeedle;
    }

    /**
     * StringFirstOccurrence
     */
    public function execute()
    {
        if ($this->isCaseInsensitive())
            return mb_stristr($this->getValue(), $this->needle, $this->beforeNeedle);
        else
            return mb_strstr($this->getValue(), $this->needle, $this->beforeNeedle);
    }
}

Remove unecessary initialization of case insensitive instance variable, already handled in parent class


<?php

namespace Milax\Mconsole\Core\API;

use Milax\Mconsole\Contracts\API\ModelAPI;

class Options extends ModelAPI
{
    /**
     * Get option value by its key
     *
     * @param  string $key
     * @return mixed
     */
    public function getByKey($key)
    {
        $model = $this->model;
        return $model::getByKey($key);
    }

    /**
     * Create or update options
     *
     * @param array $options [Options array]
     * @return void
     */
    public function install($options)
    {
        $model = $this->model;
        foreach ($options as $option) {
            if ($model::where('key', $option['key'])->count() == 0) {
                $model::create($option);
            } else {
                unset($option['value']);

                if (isset($option['rules'])) {
                    $option['rules'] = json_encode($option['rules']);
                }

                if (isset($option['options'])) {
                    $option['options'] = json_encode($option['options']);
                }
                $model::where('key', $option['key'])->update($option);
            }
        }
    }

    /**
     * Remove options from database
     *
     * @param array $options [Options array]
     * @return void
     */
    public function uninstall($options)
    {
        $model = $this->model;
        foreach ($options as $option) {
            $model::where('key', $option['key'])->delete();
        }
    }
}

<?php

namespace Milax\Mconsole\Core\API;

use Milax\Mconsole\Contracts\API\ModelAPI;

class Options extends ModelAPI
{
    /**
     * Get option value by its key
     *
     * @param  string $key
     * @return mixed
     */
    public function get($key)
    {
        $model = $this->model;
        return $model::getByKey($key);
    }

    /**
     * Create or update options
     *
     * @param array $options [Options array]
     * @return void
     */
    public function install($options)
    {
        $model = $this->model;
        foreach ($options as $option) {
            if ($model::where('key', $option['key'])->count() == 0) {
                $model::create($option);
            } else {
                unset($option['value']);

                if (isset($option['rules'])) {
                    $option['rules'] = json_encode($option['rules']);
                }

                if (isset($option['options'])) {
                    $option['options'] = json_encode($option['options']);
                }
                $model::where('key', $option['key'])->update($option);
            }
        }
    }

    /**
     * Remove options from database
     *
     * @param array $options [Options array]
     * @return void
     */
    public function uninstall($options)
    {
        $model = $this->model;
        foreach ($options as $option) {
            $model::where('key', $option['key'])->delete();
        }
    }
}

Rename options getByKey() method to get()


<?php

namespace NemC\IP2LocLite\Facades;

use Illuminate\Support\Facades\Facade;

class IP2LocLite extends Facade
{
    public static function get($ip)
    {
        $longIp = ip2long($ip);

        return static::$app['nemc_ip2loc-lite_helper']->getForLongIp($longIp);
    }
    protected static function getFacadeAccessor()
    {
        return 'nemc_ip2loc-lite_helper';
    }
}

<?php

namespace NemC\IP2LocLite\Facades;

use Illuminate\Support\Facades\Facade;

class IP2LocLite extends Facade
{
    public static function get($ip)
    {
        //trim IP just in case
        $ip = trim($ip);
        $longIp = ip2long($ip);
        if ($longIp !== false) {
            return static::$app['nemc_ip2loc-lite_helper']->getForLongIp($longIp);
        } else {
            return [];
        }

    }
    protected static function getFacadeAccessor()
    {
        return 'nemc_ip2loc-lite_helper';
    }
}

Trim IP before doing long2ip because of possible failures


<?php
/**
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

namespace OC\Memcache;

class Null extends Cache {
	public function get($key) {
		return null;
	}

	public function set($key, $value, $ttl = 0) {
		return true;
	}

	public function hasKey($key) {
		return false;
	}

	public function remove($key) {
		return true;
	}

	public function clear($prefix = '') {
		return true;
	}

	static public function isAvailable() {
		return true;
	}
}

<?php
/**
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

namespace OC\Memcache;

class Null extends Cache {
	public function get($key) {
		return null;
	}

	public function set($key, $value, $ttl = 0) {
		return true;
	}

	public function hasKey($key) {
		return false;
	}

	public function remove($key) {
		return true;
	}

	public function inc($key) {
		return true;
	}

	public function dec($key) {
		return true;
	}

	public function cas($key, $old, $new) {
		return true;
	}

	public function clear($prefix = '') {
		return true;
	}

	static public function isAvailable() {
		return true;
	}
}

Add CAS methods to Null memcache

Add CAS methods to Null memcache

This prevents breaking ownCloud completely when memcache is not enabled
and the locking code is triggered


<?php

namespace Slim\Middleware;

/**
 * HTTP Basic Authentication
 *
 * Provides HTTP Basic Authentication on given routes
 *
 * @package    Slim
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 */
class HttpBasicAuth extends \Slim\Middleware {

    public $options;

    public function __construct($options = null) {

        /* Default options. */
        $this->options = array(
            "users" => array(),
            "path" => "/",
            "real" => "Protected"
        );

        if ($options) {
            $this->options = array_merge($this->options, (array)$options);
        }
    }

    public function call() {
        $request = $this->app->request;

        /* If path matches what is given on initialization. */
        if (false !== strpos($request->getPath(), $this->options["path"])) {
            $user = $request->headers("PHP_AUTH_USER");
            $pass = $request->headers("PHP_AUTH_PW");

            /* Check if user and passwords matches. */
            if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
                $this->next->call();
            } else {
                $this->app->response->status(401);
                $this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
                return;
            }
        } else {
            $this->next->call();
        }
    }
}

<?php

namespace Slim\Middleware;

/**
 * HTTP Basic Authentication
 *
 * Provides HTTP Basic Authentication on given routes
 *
 * @package    Slim
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 */
class HttpBasicAuth extends \Slim\Middleware {

    public $options;

    public function __construct($options = null) {

        /* Default options. */
        $this->options = array(
            "users" => array(),
            "path" => "/",
            "realm" => "Protected"
        );

        if ($options) {
            $this->options = array_merge($this->options, (array)$options);
        }
    }

    public function call() {
        $request = $this->app->request;

        /* If path matches what is given on initialization. */
        if (false !== strpos($request->getPath(), $this->options["path"])) {
            $user = $request->headers("PHP_AUTH_USER");
            $pass = $request->headers("PHP_AUTH_PW");

            /* Check if user and passwords matches. */
            if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
                $this->next->call();
            } else {
                $this->app->response->status(401);
                $this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
                return;
            }
        } else {
            $this->next->call();
        }
    }
}

Fix typo in parameter name.

Fix typo in parameter name.


<?php
defined('C5_EXECUTE') or die(_("Access Denied."));

if (isset($error) && $error != '') {
	if ($error instanceof Exception) {
		$_error[] = $error->getMessage();
	} else if ($error instanceof ValidationErrorHelper) {
		$_error = $error->getList();
	} else if (is_array($error)) {
		$_error = $error;
	} else if (is_string($error)) {
		$_error[] = $error;
	}
	?>
	<? if ($format == 'block') { ?>

<button type="button" class="close" data-dismiss="alert">×</button>
	<?php foreach($_error as $e): ?>
		<?php echo $e?>

	<?php endforeach; ?>

	<? } else { ?>

	<?php foreach($_error as $e): ?>

<?php echo $e?>

	<?php endforeach; ?>

	<? } ?>

<?php } ?>

<?php
defined('C5_EXECUTE') or die(_("Access Denied."));

if (isset($error) && $error != '') {
	if ($error instanceof Exception) {
		$_error[] = $error->getMessage();
	} else if ($error instanceof ValidationErrorHelper) {
		$_error = $error->getList();
	} else if (is_array($error)) {
		$_error = $error;
	} else if (is_string($error)) {
		$_error[] = $error;
	}
	?>
	<? if($_error) { ?>
		<? if ($format == 'block') { ?>

<button type="button" class="close" data-dismiss="alert">×</button>
		<?php foreach($_error as $e): ?>
			<?php echo $e?>

		<?php endforeach; ?>

		<? } else { ?>

		<?php foreach($_error as $e): ?>

<?php echo $e?>

		<?php endforeach; ?>

		<? } ?>
	<? } ?>

<?php } ?>

Fix Attempting to Display Blank Errors

Fix Attempting to Display Blank Errors

Fix attempting to display blank errors in single pages

- This is particularly apparent with the newer `Controller::$error`
  property.

Former-commit-id: 19cb81a07b9cd71433f633c539a2d2759121b282


<?php

namespace Flooris\Prestashop\Traits;

trait CompositeKeyModelTrait
{
    /**
     * Set the keys for a save update query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function setKeysForSaveQuery($query)
    {
        $keys = $this->getKeyName();
        if(!is_array($keys)){
            return parent::setKeysForSaveQuery($query);
        }

        foreach($keys as $keyName){
            $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
        }

        return $query;
    }

    /**
     * Get the primary key value for a save query.
     *
     * @param mixed $keyName
     * @return mixed
     */
    protected function getKeyForSaveQuery($keyName = null)
    {
        if(is_null($keyName)){
            $keyName = $this->getKeyName();
        }

        if (isset($this->original[$keyName])) {
            return $this->original[$keyName];
        }

        return $this->getAttribute($keyName);
    }
}

<?php

namespace Flooris\Prestashop\Traits;

use Illuminate\Support\Str;

trait CompositeKeyModelTrait
{
    /**
     * Set the keys for a save update query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function setKeysForSaveQuery($query)
    {
        $keys = $this->getKeyName();
        if(!is_array($keys)){
            return parent::setKeysForSaveQuery($query);
        }

        foreach($keys as $keyName){
            $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
        }

        return $query;
    }

    /**
     * Get the primary key value for a save query.
     *
     * @param mixed $keyName
     * @return mixed
     */
    protected function getKeyForSaveQuery($keyName = null)
    {
        if(is_null($keyName)){
            $keyName = $this->getKeyName();
        }

        if (isset($this->original[$keyName])) {
            return $this->original[$keyName];
        }

        return $this->getAttribute($keyName);
    }

    /**
     * Qualify the given column name by the model's table.
     *
     * @param array|string $columns
     * @return string
     */
    public function qualifyColumn($columns)
    {
        if (is_array($columns)) {
            $column = $columns[0];
        }

        if (Str::contains($column, '.')) {
            return $column;
        }

        return $this->getTable() . '.' . $column;
    }
}

Fix issue in relations on classes with composite keys


<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package _s
 * @since _s 1.0
 */

get_header(); ?>

				<?php while ( have_posts() ) : the_post(); ?>

					<?php get_template_part( 'content', 'page' ); ?>

          <?php
            // If comments are open or we have at least one comment, load up the comment template
            if ( comments_open() || '0' != get_comments_number() )
              comments_template( '', true );
          ?>

				<?php endwhile; // end of the loop. ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Fix indentation on comments block

Fix indentation on comments block


<?php _e( 'Nothing Found', 'twentyseventeen' ); ?>

		<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>

<?php printf( __( 'Ready to publish your first post? Get started here.', 'twentyseventeen' ), esc_url( admin_url( 'post-new.php' ) ) ); ?>

		<?php else : ?>

<?php _e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'twentyseventeen' ); ?>

			<?php
			get_search_form();

		endif;
		?>

<?php _e('Nothing Found', 'twentyseventeen'); ?>

		<?php if (is_home() && current_user_can('publish_posts')) : ?>

<?php printf(__('Ready to publish your first post? Get started here.', 'twentyseventeen'), esc_url(admin_url('post-new.php'))); ?>

		<?php else : ?>

<?php _e('It seems we can’t find what you’re looking for. Perhaps searching can help.', 'twentyseventeen'); ?>

			<?php

			if (!is_search()):
				get_search_form();
			endif;

		endif;

		?>

Remove search form on search results template


<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Command\ContainerDebugCommand.
 */

namespace Drupal\AppConsole\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ContainerDebugCommand extends ContainerAwareCommand
{

  protected function configure()
  {
    $this
      ->setName('container:debug')
      ->setDescription('Displays current services for an application')
    ;
  }

  protected function execute(InputInterface $input, OutputInterface $output)
  {
    $services = $this->getServices();
    $table = $this->getHelperSet()->get('table');
    $table->setHeaders(['Service ID', 'Class name']);
    $table->setlayout($table::LAYOUT_COMPACT);
    foreach ($services as $serviceId) {
      $service = $this->getContainer()->get($serviceId);
      $class = get_class($service);
      $table->addRow([$serviceId, $class]);
    }
    $table->render($output);
  }
}

<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Command\ContainerDebugCommand.
 */

namespace Drupal\AppConsole\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ContainerDebugCommand extends ContainerAwareCommand
{

  protected function configure()
  {
    $this
      ->setName('container:debug')
      ->setDescription($this->trans('command.container.debug.description'))
    ;
  }

  protected function execute(InputInterface $input, OutputInterface $output)
  {
    $services = $this->getServices();
    $table = $this->getHelperSet()->get('table');
    $table->setHeaders(['Service ID', 'Class name']);
    $table->setlayout($table::LAYOUT_COMPACT);
    foreach ($services as $serviceId) {
      $service = $this->getContainer()->get($serviceId);
      $class = get_class($service);
      $table->addRow([$serviceId, $class]);
    }
    $table->render($output);
  }
}

Set command description using translation key


<?php

class OSMPointOfInterestExtension extends DataExtension {
	private static $db = array(
		// No Big Int support yet so use big decimal
		'OpenStreetMapID' => 'Decimal(20,0)'
	);

	// given millions of possible POIs an index is handy
	private static $indexes = array(
        'OpenStreetMapID' => true
    );
}

<?php

class OSMPointOfInterestExtension extends DataExtension {
	private static $db = array(
		// No Big Int support yet so use big decimal
		'OpenStreetMapID' => 'Decimal(20,0)'
	);

	// given millions of possible POIs an index is handy
	private static $indexes = array(
        'OpenStreetMapID' => true
    );

	/* The openstreetmap id is only for scripting purposes */
    public function updateCMSFields( FieldList $fields ) {
	    $osmid = $fields->removeByName('OpenStreetMapID');
	}
}

FIX: Hide openstreetmap id, only required for scripting


<?php

namespace Moxl\Xec\Action\AdHoc;

use Moxl\Xec\Action;
use Moxl\Stanza\AdHoc;

class Command extends Action
{
    private $_to;
    private $_node;

    public function request()
    {
        $this->store();
        AdHoc::command($this->_to, $this->_node);
    }

    public function setTo($to)
    {
        $this->_to = $to;
        return $this;
    }

    public function setNode($node)
    {
        $this->_node = $node;
        return $this;
    }

    public function handle($stanza, $parent = false) {
        $this->prepare($stanza, $parent);
        $this->pack($stanza->command, $stanza->from);
        $this->deliver();
    }

    public function error($errorid, $message)
    {
        $this->pack([
            "errorid" => $errorid,
            "message" => $message
        ]);
        $this->deliver();
    }
}

<?php

namespace Moxl\Xec\Action\AdHoc;

use Moxl\Xec\Action;
use Moxl\Stanza\AdHoc;

class Command extends Action
{
    private $_to;
    private $_node;

    public function request()
    {
        $this->store();
        AdHoc::command($this->_to, $this->_node);
    }

    public function setTo($to)
    {
        $this->_to = $to;
        return $this;
    }

    public function setNode($node)
    {
        $this->_node = $node;
        return $this;
    }

    public function handle($stanza, $parent = false) {
        $this->prepare($stanza, $parent);
        $this->pack($stanza->command);
        $this->deliver();
    }

    public function error($errorid, $message)
    {
        $this->pack([
            "errorid" => $errorid,
            "message" => $message
        ]);
        $this->deliver();
    }
}

Use the from set by prepare

Adhoc: Use the from set by prepare

Missed this when I submitted my last AdHoc PR. Should only set
from once: in prepare. Not override it with an (incorrect) string right
after.


<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->get('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->config('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

Fix generator path for service provider

Fix generator path for service provider


<?php

namespace GrooveHQ\Test\Service;

use GrooveHQ\Service\AgentsDescription;

class AgentsDescriptionTest extends \PHPUnit_Framework_TestCase
{

    public function testAgentsDescription()
    {
        $agents = new AgentsDescription(['token' => 'someToken']);

        $operations = $agents->getOperations();

        $expected = ['find'];
        $result = array_keys($operations);
        $this->assertEquals($expected, $result);

        $expected = ['agent_email', 'access_token'];
        $result = array_keys($operations['find']['parameters']);
        $this->assertEquals($expected, $result);
    }

}

<?php

namespace GrooveHQ\Test\Service;

use GrooveHQ\Service\AgentsDescription;

class AgentsDescriptionTest extends \PHPUnit_Framework_TestCase
{

    public function testAgentsDescription()
    {
        $agents = new AgentsDescription(['token' => 'someToken']);

        $operations = $agents->getOperations();

        $expected = ['list', 'find'];
        $result = array_keys($operations);
        $this->assertEquals($expected, $result);

        $expected = ['group', 'access_token'];
        $result = array_keys($operations['list']['parameters']);
        $this->assertEquals($expected, $result);

        $expected = ['agent_email', 'access_token'];
        $result = array_keys($operations['find']['parameters']);
        $this->assertEquals($expected, $result);
    }

}

Update unit test for AgentsDescription to include list operation.


<?php

namespace Common\DataCollector;

use SpoonDatabase;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DatabaseDataCollector extends DataCollector
{
    /**
     * @var SpoonDatabase
     */
    private $database;

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

    public function collect(Request $request, Response $response, \Exception $exception = null): void
    {
        $this->data = [
            'queries' => array_map(
                function (array $query) {
                    $query['query_formatted'] = \SqlFormatter::format($query['query']);

                    return $query;
                },
                (array) $this->database->getQueries()
            ),
            'queryCount' => count($this->database->getQueries()),
        ];
    }

    public function getQueryCount(): int
    {
        return $this->data['queryCount'];
    }

    public function getQueries(): array
    {
        return $this->data['queries'];
    }

    public function getName(): string
    {
        return 'database';
    }
}

<?php

namespace Common\DataCollector;

use SpoonDatabase;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DatabaseDataCollector extends DataCollector
{
    /**
     * @var SpoonDatabase
     */
    private $database;

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

    public function collect(Request $request, Response $response, \Exception $exception = null): void
    {
        $this->data = [
            'queries' => array_map(
                function (array $query) {
                    $query['query_formatted'] = \SqlFormatter::format($query['query']);

                    return $query;
                },
                (array) $this->database->getQueries()
            ),
            'queryCount' => count($this->database->getQueries()),
        ];
    }

    public function getQueryCount(): int
    {
        return $this->data['queryCount'] ?? 0;
    }

    public function getQueries(): array
    {
        return $this->data['queries'] ?? [];
    }

    public function getName(): string
    {
        return 'database';
    }

    public function reset()
    {
        $this->data = [];
    }
}

Implement the reset function of the data collector


<?php

$router = $di->get("router");

foreach ($application->getModules() as $key => $module) {
    $namespace = str_replace('Module','Controllers', $module["className"]);
    $router->add('/'.$key.'/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 'index',
        'action' => 'index',
        'params' => 1
    ])->setName($key);
    $router->add('/'.$key.'/:controller/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 'index',
        'params' => 2
    ]);
    $router->add('/'.$key.'/:controller/:action/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 2,
        'params' => 3
    ]);
}

$di->set("router", $router);

<?php

$router = $di->getRouter();

foreach ($application->getModules() as $key => $module) {
    $namespace = preg_replace('/Module$/', 'Controllers', $module["className"]);
    $router->add('/'.$key.'/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 'index',
        'action' => 'index',
        'params' => 1
    ])->setName($key);
    $router->add('/'.$key.'/:controller/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 'index',
        'params' => 2
    ]);
    $router->add('/'.$key.'/:controller/:action/:params', [
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 2,
        'params' => 3
    ]);
}

Fix in 'modules' project for module class name to module base namespace for setting up routing.


<?php
include_once 'core.php';
include_once 'db.php';

?>

<?php
if (isset($_GET['p'])) {
    echo '
';
} else {
    echo '
';
}
?>

<form method="get" action="search.php" id="search">
    <input type="hidden" name="mode" value="q">
    <input name="query" type="text" size="40" placeholder="Search..." />
  </form>

Home

Notifications<?php echo count_unseen_notf($pdo) ?>

    <?php if (isset($_GET['p'])): ?>

Settings

Friends

  <?php else:
    $nickname = get_user()['nickname'];
  echo "
{$nickname}
";
  endif; ?>

Logout

Fix the home button link.

Fix the home button link.


<?php
/**
 * @copyright Federico Nicolás Motta
 * @author Federico Nicolás Motta <fedemotta@gmail.com>
 * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
 * @package yii2-aws-sdk
 * @version 0.1
 */
namespace fedemotta\awssdk;
use yii\base\Component;
use Aws\Common\Aws;

/**
 * Yii2 component wrapping of the AWS SDK for easy configuration
 *
 * @author Federico Nicolás Motta <fedemotta@gmail.com>
 * @since 0.1
 */
class AwsSdk extends Component
{
    /*
     * @var string specifies the AWS key
     */
    public $key = null;

    /*
     * @var string specifies the AWS secret
     */
    public $secret = null;

    /*
     * @var string specifies the AWS region
     */
    public $region = null;

    /**
     * @var AWS SDK instance
     */
    protected $_awssdk;

    /**
     * Initializes (if needed) and fetches the AWS SDK instance
     * @return Aws instance
     */
    public function getAwsSdk()
    {
        if (empty($this->_awssdk) || !$this->_awssdk instanceof Aws\Common\Aws) {
            $this->setAwsSdk();
        }
        return $this->_awssdk;
    }
    /**
     * Sets the AWS SDK instance
     */
    public function setAwsSdk()
    {
        $this->_awssdk = Aws::factory([$this->key,$this->secret,$this->region]);
    }
}

<?php
/**
 * @copyright Federico Nicolás Motta
 * @author Federico Nicolás Motta <fedemotta@gmail.com>
 * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
 * @package yii2-aws-sdk
 */
namespace fedemotta\awssdk;
use yii\base\Component;
use Aws\Common\Aws;

/**
 * Yii2 component wrapping of the AWS SDK for easy configuration
 * @author Federico Nicolás Motta <fedemotta@gmail.com>
 */
class AwsSdk extends Component
{
    /*
     * @var string specifies the AWS key
     */
    public $key = null;

    /*
     * @var string specifies the AWS secret
     */
    public $secret = null;

    /*
     * @var string specifies the AWS region
     */
    public $region = null;

    /**
     * @var AWS SDK instance
     */
    protected $_awssdk;

    /**
     * Initializes (if needed) and fetches the AWS SDK instance
     * @return Aws instance
     */
    public function getAwsSdk()
    {
        if (empty($this->_awssdk) || !$this->_awssdk instanceof Aws\Common\Aws) {
            $this->setAwsSdk();
        }
        return $this->_awssdk;
    }
    /**
     * Sets the AWS SDK instance
     */
    public function setAwsSdk()
    {
        $this->_awssdk = Aws::factory([ 'key'=>$this->key,
                                        'secret'=>$this->secret,
                                        'region'=>$this->region]);
    }
}

Fix region and removing version in file

Fix region and removing version in file


<?php

/**
 * A Command that runs all of the available tests and outputs
 * the results to the console.
 */

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class RunTests extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'test';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Run all available tests.';

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		passthru('vendor/bin/phpunit');
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}

}

<?php

/**
 * A Command that runs all of the available tests and outputs
 * the results to the console.
 */

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class RunTests extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'test';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Run all automated tests';

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		passthru('vendor/bin/phpunit');
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}

}

Fix up "artisan test" help message

Fix up "artisan test" help message


<?php

namespace Ulrichsg\Getopt;

class ArgumentTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $argument1 = new Argument();
        $argument2 = new Argument(10);
        $this->assertFalse($argument1->hasDefaultValue());
        $this->assertEquals(10, $argument2->getDefaultValue());
    }

    public function testSetDefaultValueNotScalar()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setDefaultValue(array());
    }

    public function testValidates()
    {
        $argument = new Argument();
        $argument->setValidation(function($arg) use ($argument) {
            $this->assertEquals('test', $arg);
            return true;
        });
        $this->assertTrue($argument->hasValidation());
        $this->assertTrue($argument->validates('test'));
    }

    public function testSetValidationUncallable()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setValidation('');
    }

    public function testSetValidationInvalidCallable()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setValidation(function() {});
    }
}

<?php

namespace Ulrichsg\Getopt;

class ArgumentTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $argument1 = new Argument();
        $argument2 = new Argument(10);
        $this->assertFalse($argument1->hasDefaultValue());
        $this->assertEquals(10, $argument2->getDefaultValue());
    }

    public function testSetDefaultValueNotScalar()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setDefaultValue(array());
    }

    public function testValidates()
    {
        $test = $this;
        $argument = new Argument();
        $argument->setValidation(function($arg) use ($test, $argument) {
            $this->assertEquals('test', $arg);
            return true;
        });
        $this->assertTrue($argument->hasValidation());
        $this->assertTrue($argument->validates('test'));
    }

    public function testSetValidationUncallable()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setValidation('');
    }

    public function testSetValidationInvalidCallable()
    {
        $this->setExpectedException('InvalidArgumentException');
        $argument = new Argument();
        $argument->setValidation(function() {});
    }
}

Fix compatibility with PHP 5.3

Fix compatibility with PHP 5.3

Using  inside of anonymous functions is not supported in PHP 5.3
-> Injected reference to test object into anonymous function (testValidates)


<?php
/**
 * Este archivo contiene toda la logica de negocio asociada a la ropa que se le entrega
 * a cada trabajador de una relacion laboral.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.controllers
 * @since           Pragtico v 1.0.0
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @author          Martin Radosta <mradosta@pragmatia.com>
 */
/**
 * La clase encapsula la logica de negocio asociada a la ropa que se le entrega
 * a cada trabajador de una relacion laboral.
 *
 * @package     pragtico
 * @subpackage  app.controllers
 */
class RopasController extends AppController {

/**
 * Prendas.
 * Muestra via desglose las prendas entregadas.
 */
   	function prendas($id) {
		$this->Ropa->contain("RopasDetalle");
		$this->data = $this->Ropa->read(null, $id);
   	}

/**
 * imprimirOrden.
 * Genera una orden que el empleado pueda retirar la ropa.
 */
   	function imprimirOrden($id) {
		$this->layout = 'pdf';
		$this->data = $this->Ropa->read(null, $id);
   	}
}
?>

<?php
/**
 * Este archivo contiene toda la logica de negocio asociada a la ropa que se le entrega
 * a cada trabajador de una relacion laboral.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.controllers
 * @since           Pragtico v 1.0.0
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @author          Martin Radosta <mradosta@pragmatia.com>
 */
/**
 * La clase encapsula la logica de negocio asociada a la ropa que se le entrega
 * a cada trabajador de una relacion laboral.
 *
 * @package     pragtico
 * @subpackage  app.controllers
 */
class RopasController extends AppController {

/**
 * Prendas.
 * Muestra via desglose las prendas entregadas.
 */
   	function prendas($id) {
		$this->Ropa->contain("RopasDetalle");
		$this->data = $this->Ropa->read(null, $id);
   	}

}
?>

Remove the use of deprecated method

Remove the use of deprecated method


<?php

/*
 * This file is part of Laravel Pusher.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Pusher;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Pusher\PusherServiceProvider';
    }
}

<?php

/*
 * This file is part of Laravel Pusher.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Pusher;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
abstract class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Pusher\PusherServiceProvider';
    }
}

Make abstract test case class abstract

Make abstract test case class abstract


<?php
App::uses('AssetFilter', 'AssetCompress.Lib');

/**
 * Pre-processing filter that adds support for SCSS files.
 *
 * Requires ruby and sass rubygem to be installed
 *
 * @see http://sass-lang.com/
 */
class ScssFilter extends AssetFilter {

	protected $_settings = array(
		'ext' => '.scss',
		'sass' => '/usr/bin/sass'
	);

/**
 * Runs SCSS compiler against any files that match the configured extension.
 *
 * @param string $filename The name of the input file.
 * @param string $input The content of the file.
 * @return string
 */
	public function input($filename, $input) {
		if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
			return $input;
		}
		$bin = $this->_settings['sass'] . ' ' . $filename;
		$return = $this->_runCmd($bin, '');
		return $return;
	}

}

<?php
App::uses('AssetFilter', 'AssetCompress.Lib');

/**
 * Pre-processing filter that adds support for SCSS files.
 *
 * Requires ruby and sass rubygem to be installed
 *
 * @see http://sass-lang.com/
 */
class ScssFilter extends AssetFilter {

	protected $_settings = array(
		'ext' => '.scss',
		'sass' => '/usr/bin/sass',
		'path' => '/usr/bin',
	);

/**
 * Runs SCSS compiler against any files that match the configured extension.
 *
 * @param string $filename The name of the input file.
 * @param string $input The content of the file.
 * @return string
 */
	public function input($filename, $input) {
		if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
			return $input;
		}
		$bin = $this->_settings['sass'] . ' ' . $filename;
		$return = $this->_runCmd($bin, '', array('PATH' => $this->_settings['path']));
		return $return;
	}

}

Add PATH to the environment

Add PATH to the environment


<?php

class CM_Exception_Nonexistent extends CM_Exception {

	protected $_severity = self::WARN;

}

<?php

class CM_Exception_Nonexistent extends CM_Exception {

}

Remove auto WARN-severity for nonexistent exception


    @forelse($student->records as $record)

{{ link_to_route('clubs.show', $record->club->name, $record->club) }}
                    {!! $record->club->clubType->tag ?? '' !!}
                    @if(!$record->club->is_counted)
                        不列入集點
                    @endif

                    created_at }}">
                        {{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }}

                @if($showFeedbackButton ?? false)
                    @if($student->feedback->contains('club_id', $record->club->id))
                        @php($feedback = $student->feedback->filter(function($item)use($record){return $item->club_id == $record->club->id;})->first())

                             檢視回饋資料

                    @else
                        club) }}" class="btn btn-primary">
                             填寫回饋資料

                    @endif
                @endif

    @empty

                尚無打卡紀錄，快去打卡吧

    @endforelse

    @forelse($student->records as $record)

{{ link_to_route('clubs.show', $record->club->name, $record->club) }}
                {!! $record->club->clubType->tag ?? '' !!}
                @if(!$record->club->is_counted)
                    不列入集點
                @endif

                created_at }}">
                    {{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }}

    @empty

                尚無打卡紀錄，快去打卡吧

    @endforelse

Remove unnecessary section in record-list


<?php

class SpecificPricingExtension extends DataExtension{

	private static $has_many = array(
		"SpecificPrices" => "SpecificPrice"
	);

	function updateCMSFields(FieldList $fields) {
		if($tab = $fields->fieldByName("Root.Pricing")){
			$fields = $tab->Fields();
		}
		if($this->owner->isInDB() && ($fields->fieldByName("BasePrice") || $fields->fieldByName("Price"))){
			$fields->push(
				GridField::create("SpecificPrices","Specific Prices", $this->owner->SpecificPrices(),
					GridFieldConfig_RecordEditor::create()
				)
			);
		}
	}

	function updateSellingPrice(&$price){
		if($specificprice = SpecificPrice::filter(
			$this->owner->SpecificPrices()
				->filter("Price:LessThan", $price)
		)->first()){
			if ($specificprice->Price > 0) {
				$price = $specificprice->Price;
			} elseif ($specificprice->DiscountPercent > 0) {
				$price *= 1.0 - $specificprice->DiscountPercent;
			} else {
				// this would mean both discount and price were 0
				$price = 0;
			}
		}
	}

}

<?php

class SpecificPricingExtension extends DataExtension{

	private static $has_many = array(
		"SpecificPrices" => "SpecificPrice"
	);

	function updateCMSFields(FieldList $fields) {
		if($tab = $fields->fieldByName("Root.Pricing")){
			$fields = $tab->Fields();
		}
		if($this->owner->isInDB() && ($fields->fieldByName("BasePrice") || $fields->fieldByName("Price"))){
			$fields->push(
				GridField::create("SpecificPrices","Specific Prices", $this->owner->SpecificPrices(),
					GridFieldConfig_RecordEditor::create()
				)
			);
		}
	}

	function updateSellingPrice(&$price){
		if($specificprice = SpecificPrice::filter(
			$this->owner->SpecificPrices()
				->filter("Price:LessThan", $price), Member::currentUser()
		)->first()){
			if ($specificprice->Price > 0) {
				$price = $specificprice->Price;
			} elseif ($specificprice->DiscountPercent > 0) {
				$price *= 1.0 - $specificprice->DiscountPercent;
			} else {
				// this would mean both discount and price were 0
				$price = 0;
			}
		}
	}

}

Change needed to make SpecificPricingExtension work for a selected group


<?php

$title       = Orchestra\Site::get('title');
$description = Orchestra\Site::get('description'); ?>

{{ $title ?: 'Something Awesome' }}
		@if ( ! empty($description))
		{{ $description ?: '' }}
		@endif

<?php

$title       = Orchestra\Site::get('title');
$description = Orchestra\Site::get('description'); ?>

	@if (Orchestra\Site::get('header::add-button'))

		Add

	@endif

{{ $title ?: 'Something Awesome' }}
		@if ( ! empty($description))
		{{ $description ?: '' }}
		@endif

Allow to include add button

Allow to include add button


<?php

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

class CreateRolesUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('role_user', function(Blueprint $table)
        {
            $user = \App::make(\Config::get('auth.model'));
            $table->string('role_key')->index();
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('role_key')->references('name')->on('roles')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('user_id')->references($user['primaryKey'])->on($user['table'])->onDelete('cascade')->onUpdate('cascade');
        });
	}

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

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Schema;

class CreateRolesUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('role_user', function(Blueprint $table)
        {
            $user = app(config('auth.model'));
            $table->string('role_key')->index();
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('role_key')->references('name')->on('roles')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('user_id')->references($user->getKeyName())->on($user->getTable())->onDelete('cascade')->onUpdate('cascade');
        });
	}

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

Change methods to get user primary key field name and table name, use helper classes to create user object


<?php
/**
 * Provide a Proxy for third party APIs.
 */

namespace Graviton\ProxyBundle;

use Graviton\BundleBundle\GravitonBundleInterface;
use Graviton\ProxyBundle\DependencyInjection\Compiler\ApiDefinitionLoaderPass;
use Graviton\ProxyBundle\DependencyInjection\Compiler\TransformerPass;
use Graviton\ProxyExtensionBundle\GravitonProxyExtensionBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * GravitonProxyBundle
 *
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link    http://swisscom.ch
 */
class GravitonProxyBundle extends Bundle implements GravitonBundleInterface
{

    /**
     * {@inheritDoc}
     *
     * @return \Symfony\Component\HttpKernel\Bundle\Bundle[]
     */
    public function getBundles()
    {
        return array();
    }

    /**
     * {@inheritDoc}
     *
     * @param ContainerBuilder $container Symfony Service container
     *
     * @return void
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new TransformerPass());
        $container->addCompilerPass(new ApiDefinitionLoaderPass());
    }
}

<?php
/**
 * Provide a Proxy for third party APIs.
 */

namespace Graviton\ProxyBundle;

use Graviton\BundleBundle\GravitonBundleInterface;
use Graviton\ProxyBundle\DependencyInjection\Compiler\ApiDefinitionLoaderPass;
use Graviton\ProxyBundle\DependencyInjection\Compiler\TransformerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * GravitonProxyBundle
 *
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link    http://swisscom.ch
 */
class GravitonProxyBundle extends Bundle implements GravitonBundleInterface
{

    /**
     * {@inheritDoc}
     *
     * @return \Symfony\Component\HttpKernel\Bundle\Bundle[]
     */
    public function getBundles()
    {
        return array();
    }

    /**
     * {@inheritDoc}
     *
     * @param ContainerBuilder $container Symfony Service container
     *
     * @return void
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new TransformerPass());
        $container->addCompilerPass(new ApiDefinitionLoaderPass());
    }
}

ProxyExtensionBundle: Remove not referenced class use. And not used.


<?php

namespace Phalcon\Mvc {

	/**
	 * Phalcon\Mvc\ModuleDefinitionInterface initializer
	 */

	interface ModuleDefinitionInterface {

		/**
		 * Registers an autoloader related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerAutoloaders();

		/**
		 * Registers services related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerServices($dependencyInjector);

	}
}

<?php

namespace Phalcon\Mvc {

	/**
	 * Phalcon\Mvc\ModuleDefinitionInterface initializer
	 */

	interface ModuleDefinitionInterface {

		/**
		 * Registers an autoloader related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerAutoloaders($dependencyInjector);

		/**
		 * Registers services related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerServices($dependencyInjector);

	}
}

Correct method definition for registerAutoloaders


<?php
/**
 * Graphical interface for creating basic flowcharts
 */
class FlowchartAdmin extends ModelAdmin {

 	private static $managed_models = array('FlowchartPage','FlowState');

	private static $url_segment = 'flowcharts';

	private static $menu_title = 'Flowcharts';

	private static $menu_icon = "flowchart/images/flowchart.png";

	private static $tree_class = 'SS_Flowchart';

	public function getEditForm($id = null, $fields = null){
		$form = parent::getEditForm($id, $fields);
		$gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
		$config = $gridField->getConfig();

		if($this->sanitiseClassName($this->modelClass) == "FlowchartPage"){
			$config->removeComponentsByType('GridFieldDetailForm');
			$config->addComponent(new GridFieldFlowchartDetailForm());
		} else if($this->sanitiseClassName($this->modelClass) == "FlowState"){
			$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(
				singleton($this->sanitiseClassName($this->modelClass))->getCurrentDisplayFields()
			);
		}
		return $form;
	}
}

<?php
/**
 * Graphical interface for creating basic flowcharts
 */
class FlowchartAdmin extends ModelAdmin {

 	private static $managed_models = array('FlowchartPage','FlowState');

	private static $url_segment = 'flowcharts';

	private static $menu_title = 'Flowcharts';

	private static $menu_icon = "flowchart/images/flowchart.png";

	private static $tree_class = 'SS_Flowchart';

	public function getEditForm($id = null, $fields = null){
		$form = parent::getEditForm($id, $fields);
		$gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
		$config = $gridField->getConfig();

		if($this->sanitiseClassName($this->modelClass) == "FlowchartPage"){
			$config->removeComponentsByType('GridFieldDetailForm');
			$config->removeComponentsByType('GridFieldAddNewButton');
			$config->addComponent(new GridFieldFlowchartDetailForm());
		} else if($this->sanitiseClassName($this->modelClass) == "FlowState"){
			$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(
				singleton($this->sanitiseClassName($this->modelClass))->getCurrentDisplayFields()
			);
		}
		return $form;
	}
}

Remove add new flowchart page from modeladmin


<?php

namespace My\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LightController extends Controller
{
    public function switchAction($switch)
    {
        $lightSwitch = $this->container->get('light_switch');

        if($switch === "on") {
            $lightSwitch->on();
        } else {
            $lightSwitch->off();
        }

        return $this->redirect($this->generateUrl('light_status'), 301);
    }

    public function statusAction()
    {
        $lightSwitch = $this->container->get('light_switch');
        return $this->render('MyTestBundle:Light:status.html.twig', array('status' => $lightSwitch->getStatus()));
    }
}

<?php

namespace My\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use My\TestBundle\Light\LightSwitch;

class LightController extends Controller
{
    protected $lightSwitch;

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

    public function switchAction($switch)
    {
        if($switch === "on") {
            $this->lightSwitch->on();
        } else {
            $this->lightSwitch->off();
        }

        return $this->redirect($this->generateUrl('light_status'), 301);
    }

    public function statusAction()
    {
        return $this->render('MyTestBundle:Light:status.html.twig', array('status' => $this->lightSwitch->getStatus()));
    }
}

Rewrite controller for Dependency Injection.


<?php

namespace RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CommandRunner;

use RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder;

class CliFunctionChecker
{
    /**
     * @var \Rmiller\PhpSpecRunExtension\Process\CachingExecutableFinder
     */
    private $executableFinder;

    /**
     * @param \Rmiller\PhpSpecRunExtension\Process\CachingExecutableFinder $executableFinder
     */
    public function __construct(CachingExecutableFinder $executableFinder)
    {
        $this->executableFinder = $executableFinder;
    }

    /**
     * @param string $function
     *
     * @return bool
     */
    public function functionCanBeUsed($function)
    {
        return (php_sapi_name() == 'cli')
            && $this->executableFinder->getExecutablePath()
            && function_exists($function);
    }
}

<?php

namespace RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CommandRunner;

use RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder;

class CliFunctionChecker
{
    /**
     * @var \RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder
     */
    private $executableFinder;

    /**
     * @param \RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder $executableFinder
     */
    public function __construct(CachingExecutableFinder $executableFinder)
    {
        $this->executableFinder = $executableFinder;
    }

    /**
     * @param string $function
     *
     * @return bool
     */
    public function functionCanBeUsed($function)
    {
        return (php_sapi_name() == 'cli')
            && $this->executableFinder->getExecutablePath()
            && function_exists($function);
    }
}

Fix last namespace typos and casing (Rmiller -> RMiller)


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Currency\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Currencies;

class Currency implements CurrencyInterface
{
    use TimestampableTrait;

    /** @var mixed */
    protected $id;

    /** @var string|null */
    protected $code;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    public function __toString(): string
    {
        return (string) $this->getCode();
    }

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

    /**
     * {@inheritdoc}
     */
    public function getName(): ?string
    {
        return Currencies::getName($this->getCode());
    }

    /**
     * {@inheritdoc}
     */
    public function getCode(): ?string
    {
        return $this->code;
    }

    /**
     * {@inheritdoc}
     */
    public function setCode(?string $code): void
    {
        $this->code = $code;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Currency\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Currencies;

class Currency implements CurrencyInterface
{
    use TimestampableTrait;

    /** @var mixed */
    protected $id;

    /** @var string|null */
    protected $code;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    public function __toString(): string
    {
        return (string) $this->getCode();
    }

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

    /**
     * {@inheritdoc}
     */
    public function getName(): ?string
    {
        if (null === $code = $this->getCode()) {
            return null;
        }

        return Currencies::getName($code);
    }

    /**
     * {@inheritdoc}
     */
    public function getCode(): ?string
    {
        return $this->code;
    }

    /**
     * {@inheritdoc}
     */
    public function setCode(?string $code): void
    {
        $this->code = $code;
    }
}

Fix currency get name when it has no code


<?php

namespace Lstr\DnsmasqMgmt\Command;

use Exception;

use Lstr\Silex\App\AppAwareInterface;
use Lstr\Silex\App\AppAwareTrait;
use Silex\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class AddressUpdateCommand extends Command implements AppAwareInterface
{
    use AppAwareTrait;

    protected function configure()
    {
        $this
            ->setName('address:update')
            ->setAliases(['update-address'])
            ->setDescription('Remove an address')
            ->addArgument(
                'hostname',
                InputArgument::REQUIRED,
                'What is the hostname you want to update?'
            )
            ->addOption(
                'ip-address',
                null,
                InputOption::VALUE_REQUIRED,
                'What is the IP address you want to point the hostname to?'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app     = $this->getSilexApplication();
        $service = $app['lstr.dnsmasq'];

        return $service->updateAddress(
            $input->getArgument('hostname'),
            $input->getOption('ip-address')
        );
    }
}

<?php

namespace Lstr\DnsmasqMgmt\Command;

use Exception;

use Lstr\Silex\App\AppAwareInterface;
use Lstr\Silex\App\AppAwareTrait;
use Silex\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class AddressUpdateCommand extends Command implements AppAwareInterface
{
    use AppAwareTrait;

    protected function configure()
    {
        $this
            ->setName('address:update')
            ->setAliases(['update-address'])
            ->setDescription('Remove an address')
            ->addArgument(
                'hostname',
                InputArgument::REQUIRED,
                'What is the hostname you want to update?'
            )
            ->addOption(
                'ip-address',
                null,
                InputOption::VALUE_REQUIRED,
                'What is the IP address you want to point the hostname to?'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app     = $this->getSilexApplication();
        $service = $app['lstr.dnsmasq'];

        if (!$input->getOption('ip-address')) {
            throw new Exception("At least one option ('ip-address') should be provided.");
        }

        return $service->updateAddress(
            $input->getArgument('hostname'),
            $input->getOption('ip-address')
        );
    }
}

Add a message if no options are provided to update


<?php namespace Way\Generators\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class PivotGeneratorCommand extends BaseGeneratorCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'generate:pivot';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a pivot table';

    public function fire()
    {
        $tables = $this->sortDesiredTables();

        $this->call(
            'generate:migration',
            array(
                'name'      => "pivot_{$tables[0]}_{$tables[1]}_table",
                '--fields'  => "{$tables[0]}_id:integer, {$tables[1]}_id:integer"
            )
        );
    }

    public function sortDesiredTables()
    {
        $tableOne = str_singular($this->argument('tableOne'));
        $tableTwo = str_singular($this->argument('tableTwo'));

        $tables = array($tableOne, $tableTwo);
        sort($tables);

        return $tables;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
            array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
        );
    }

}

<?php namespace Way\Generators\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class PivotGeneratorCommand extends BaseGeneratorCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'generate:pivot';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a pivot table';

    public function fire()
    {
        $tables = $this->sortDesiredTables();

        $this->call(
            'generate:migration',
            array(
                'name'      => "pivot_{$tables[0]}_{$tables[1]}_table",
                '--fields'  => "{$tables[0]}_id:integer:unsigned, {$tables[1]}_id:integer:unsigned"
            )
        );
    }

    public function sortDesiredTables()
    {
        $tableOne = str_singular($this->argument('tableOne'));
        $tableTwo = str_singular($this->argument('tableTwo'));

        $tables = array($tableOne, $tableTwo);
        sort($tables);

        return $tables;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
            array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
        );
    }

}

Make foreign keys unsigned for pivot table generation


<?php

namespace App\Bootstrap;

use App\Constants\Services;
use League\Fractal\Manager as FractalManager;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconUtils\Http\Response;use PhalconUtils\Transformer\ResponseDataSerializer;

/**
 * Class ApiServicesBootStrap
 * @author Adeyemi Olaoye <yemi@cottacush.com>
 * @package App\Library\BootStrap
 */
class ApiServicesBootStrap extends BaseServicesBootStrap
{

    public function run(Injectable $app, DiInterface $di, Config $config)
    {
        parent::run($app, $di, $config);

        $di->set(Services::RESPONSE, function () {
            return new Response();
        });

        /**
         * Fractal
         */
        $di->setShared(Services::FRACTAL_MANAGER, function () {
            $fractal = new FractalManager();
            $fractal->setSerializer(new ResponseDataSerializer());
            return $fractal;
        });
    }
}

<?php

namespace App\Bootstrap;

use App\Constants\Services;
use League\Fractal\Manager as FractalManager;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconUtils\Http\Response;
use PhalconUtils\Transformer\ResponseDataSerializer;

/**
 * Class ApiServicesBootStrap
 * @author Adeyemi Olaoye <yemi@cottacush.com>
 * @package App\Library\BootStrap
 */
class ApiServicesBootStrap extends BaseServicesBootStrap
{

    public function run(Injectable $app, DiInterface $di, Config $config)
    {
        parent::run($app, $di, $config);

        $di->set(Services::RESPONSE, function () {
            return new Response();
        });

        /**
         * Fractal
         */
        $di->setShared(Services::FRACTAL_MANAGER, function () {
            $fractal = new FractalManager();
            $fractal->setSerializer(new ResponseDataSerializer());
            return $fractal;
        });
    }
}

Move use statement to next line

Refactor: Move use statement to next line


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ImageBundle\Form\Type;

use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Image form type
 */
class ImageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', 'vich_image', array(
            'label'    => false,
            'required' => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => AbstractImage::CLASS_NAME,
            'intention'  => md5(__FILE__),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'darvin_image_image';
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ImageBundle\Form\Type;

use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Image form type
 */
class ImageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', 'file', array(
            'label'    => false,
            'required' => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => AbstractImage::CLASS_NAME,
            'intention'  => md5(__FILE__),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'darvin_image_image';
    }
}

Change image form type "file" field type to "file".


<!DOCTYPE html>

@include('layouts.partials.htmlheader')

    @include('layouts.partials.mainheader')

    @include('layouts.partials.sidebar')

        @include('layouts.partials.contentheader')

            @yield('main-content')

    @include('layouts.partials.controlsidebar')

    @include('layouts.partials.footer')

@include('layouts.partials.scripts')

<!DOCTYPE html>

@section('htmlheader')
    @include('layouts.partials.htmlheader')
@show

    @include('layouts.partials.mainheader')

    @include('layouts.partials.sidebar')

        @include('layouts.partials.contentheader')

            @yield('main-content')

    @include('layouts.partials.controlsidebar')

    @include('layouts.partials.footer')

@section('scripts')
    @include('layouts.partials.scripts')
@show

Create sections for htmlhead and scripts

Make it possible to inject additional files from other views


<?php
namespace Album;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

<?php
namespace Album;

use Zend\Mvc\ModuleRouteListener;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\MvcEvent;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getServiceConfig()
    {
    	return array(
    			'factories' => array(
    					'Album\Model\AlbumTable' =>  function($sm) {
    						$tableGateway = $sm->get('AlbumTableGateway');
    						$table = new AlbumTable($tableGateway);
    						return $table;
    					},
    					'AlbumTableGateway' => function ($sm) {
    						$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    						$resultSetPrototype = new ResultSet();
    						$resultSetPrototype->setArrayObjectPrototype(new Album());
    						return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
    					},
    			),
    	);
    }
}

Add service configuration to the Album module


<?php
    function migrate( $sql_array = [] ) {
        require_once '../../config/config-local.php';
        require_once '../../models/database.php';
        require_once '../../models/db.php';

        global $config;

        $config = getConfig()[ getEnv( 'ENVIRONMENT' ) ];
        dbInit();

        foreach ( $sql_array as $sql ) {
            try {
                $res = db( $sql );
            }
            catch ( DBException $e ) {
                die( "Migration failed. SQL query died with the following error: " . mysql_error() . "\n" );
            }
        }
        echo "Migration successful.\n";
    }
?>

<?php
    function migrate( $sql_array = [] ) {
        if ( file_exists( '../../config/config-local.php' ) ) {
            require_once '../../config/config-local.php';
        }
        else {
            require_once '../../config/config.php';
        }
        require_once '../../models/database.php';
        require_once '../../models/db.php';

        global $config;

        $config = getConfig()[ getEnv( 'ENVIRONMENT' ) ];
        dbInit();

        foreach ( $sql_array as $sql ) {
            try {
                $res = db( $sql );
            }
            catch ( DBException $e ) {
                die( "Migration failed. SQL query died with the following error: " . mysql_error() . "\n" );
            }
        }
        echo "Migration successful.\n";
    }
?>

Make travis run all migrations before running tests


<?php

/*
   ----------------------------------------------------------------------
   FusionInventory
   Copyright (C) 2010-2011 by the FusionInventory Development Team.

   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
   ----------------------------------------------------------------------

   LICENSE

   This file is part of FusionInventory.

   FusionInventory is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   any later version.

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

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

   ------------------------------------------------------------------------
   Original Author of file: David DURIEUX
   Co-authors of file:
   Purpose of file:
   ----------------------------------------------------------------------
 */

if (strpos($_SERVER['PHP_SELF'],"showporthistory.php")) {
   define('GLPI_ROOT','../../..');
   include (GLPI_ROOT."/inc/includes.php");
   header("Content-Type: text/html; charset=UTF-8");
   header_nocache();
}
if (!defined('GLPI_ROOT')) {
   die("Can not acces directly to this file");
}

checkCentralAccess();

echo PluginFusinvsnmpNetworkPortLog::showHistory($_POST["ports_id"]);

?>

<?php

/*
   ----------------------------------------------------------------------
   FusionInventory
   Copyright (C) 2010-2011 by the FusionInventory Development Team.

   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
   ----------------------------------------------------------------------

   LICENSE

   This file is part of FusionInventory.

   FusionInventory is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   any later version.

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

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

   ------------------------------------------------------------------------
   Original Author of file: David DURIEUX
   Co-authors of file:
   Purpose of file:
   ----------------------------------------------------------------------
 */

if (strpos($_SERVER['PHP_SELF'],"showporthistory.php")) {
   define('GLPI_ROOT','../../..');
   include (GLPI_ROOT."/inc/includes.php");
   header("Content-Type: text/html; charset=UTF-8");
   header_nocache();
}
if (!defined('GLPI_ROOT')) {
   die("Can not acces directly to this file");
}

Session::checkCentralAccess();

echo PluginFusinvsnmpNetworkPortLog::showHistory($_POST["ports_id"]);

?>

Fix functions into Session class

Fix functions into Session class


<?php

class ncChangeLogEntryPeer extends PluginncChangeLogEntryPeer
{
  protected static function convertToAdapter($entries)
  {
    if (is_array($entries))
    {
      $res = array();
      foreach ($entries as $k => $e)
      {
        $res[$k] = $e->getAdapter();
      }
      return $res;
    }
    else
    {
      return $entries->getAdapter();
    }
  }

  public static function getChangeLogOfObject($class, $pk = null, $from_date = null, $to_date = null)
  {
    $c = new Criteria();

    $c->add(ncChangeLogEntryPeer::CLASS_NAME, $class);
    if (!is_null($pk))
      $c->add(ncChangeLogEntryPeer::OBJECT_PK, $pk);

    $criterion1 = $c->getNewCriterion(ncChangeLogEntryPeer::CREATED_AT, $from_date, Criteria::GREATER_EQUAL);
    $criterion2 = $c->getNewCriterion(ncChangeLogEntryPeer::CREATED_AT, $to_date, Criteria::LESS_EQUAL);

    $c->addAnd($criterion1);
    $c->addAnd($criterion2);

    return self::convertToAdapter(ncChangeLogEntryPeer::doSelect($c));
  }
}

<?php

class ncChangeLogEntryPeer extends PluginncChangeLogEntryPeer
{

}

Fix for the previous commit

Fix for the previous commit


<?php

// A very simple helper script used to generate self-signed certificates.
// Accepts the CN and an optional passphrase to encrypt the private key.
//
// $ php examples/99-generate-self-signed.php localhost swordfish > secret.pem

// certificate details (Distinguished Name)
// (OpenSSL applies defaults to missing fields)
$dn = array(
    "commonName" => isset($argv[1]) ? $argv[1] : "localhost",
//     "countryName" => "AU",
//     "stateOrProvinceName" => "Some-State",
//     "localityName" => "London",
//     "organizationName" => "Internet Widgits Pty Ltd",
//     "organizationalUnitName" => "R&D",
//     "emailAddress" => "admin@example.com"
);

// create certificate which is valid for ~10 years
$privkey = openssl_pkey_new();
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 3650);

// export public and (optionally encrypted) private key in PEM format
openssl_x509_export($cert, $out);
echo $out;

$passphrase = isset($argv[2]) ? $argv[2] : null;
openssl_pkey_export($privkey, $out, $passphrase);
echo $out;

<?php

// A very simple helper script used to generate self-signed certificates.
// Accepts the CN and an optional passphrase to encrypt the private key.
//
// $ php examples/99-generate-self-signed.php localhost my-secret-passphrase > secret.pem

// certificate details (Distinguished Name)
// (OpenSSL applies defaults to missing fields)
$dn = array(
    "commonName" => isset($argv[1]) ? $argv[1] : "localhost",
//     "countryName" => "AU",
//     "stateOrProvinceName" => "Some-State",
//     "localityName" => "London",
//     "organizationName" => "Internet Widgits Pty Ltd",
//     "organizationalUnitName" => "R&D",
//     "emailAddress" => "admin@example.com"
);

// create certificate which is valid for ~10 years
$privkey = openssl_pkey_new();
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 3650);

// export public and (optionally encrypted) private key in PEM format
openssl_x509_export($cert, $out);
echo $out;

$passphrase = isset($argv[2]) ? $argv[2] : null;
openssl_pkey_export($privkey, $out, $passphrase);
echo $out;

Use more descriptive example passphrase

Use more descriptive example passphrase