<?php

namespace CWreden\GitLog;

use CWreden\GitLog\GitHub\GitHubServiceProvider;
use CWreden\GitLog\GitHub\OAuthControllerProvider;
use Silex\Provider\DoctrineServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;

/**
 * Class Application
 * @package CWreden\GitLog
 */
class Application extends \Silex\Application
{
    /**
     * @param array $values
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this->register(new SessionServiceProvider());
        $this->register(new ServiceControllerServiceProvider());
        $this->register(new TwigServiceProvider());
        $this->register(new DoctrineServiceProvider());
        $this->register(new UrlGeneratorServiceProvider());

        $this->register(new GitHubServiceProvider());
        $this->mount('', new OAuthControllerProvider());
        $this->mount('', new GitLogControllerProvider());

        // TODO Create ChangeLog
        // TODO Edit/Ignore commit messages

        // TODO Export Services

        // TODO Search Services
        // TODO Report Services
    }
}

<?php

namespace CWreden\GitLog;

use CWreden\GitLog\GitHub\GitHubServiceProvider;
use CWreden\GitLog\GitHub\OAuthControllerProvider;
use Silex\Provider\DoctrineServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;

/**
 * Class Application
 * @package CWreden\GitLog
 */
class Application extends \Silex\Application
{
    /**
     * @param array $values
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this->register(new SessionServiceProvider());
        $this->register(new ServiceControllerServiceProvider());
        $this->register(new TwigServiceProvider());
        $this->register(new DoctrineServiceProvider());
        $this->register(new UrlGeneratorServiceProvider());

        $this->register(new GitHubServiceProvider());
        $this->mount('', new OAuthControllerProvider());
        $this->mount('', new GitLogControllerProvider());

        // TODO Create ChangeLog
        // TODO Edit/Ignore commit messages

        // TODO Export Services

        // TODO Search Services
        // TODO Report Services

        foreach ($values as $key => $value) {
            $this[$key] = $value;
        }
    }
}

Secure that the given values loading at least.


<?php

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

class AddUserRole extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->integer('role_id')->default(0)->index();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('role_id');
        });
    }
}

<?php

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

class AddUserRole extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->integer('role_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('role_id');
        });
    }
}

Change user role_id to nullable and remove index


<?php

namespace kop\y2sp\assets;

use yii\web\AssetBundle;

/**
 * This is "InfiniteAjaxScrollAsset" class.
 *
 * This class is an asset bundle for {@link http://infiniteajaxscroll.com/ JQuery Infinite Ajax Scroll plugin}.
 *
 * @link      http://kop.github.io/yii2-scroll-pager Y2SP project page.
 * @license   https://github.com/kop/yii2-scroll-pager/blob/master/LICENSE.md MIT
 *
 * @author    Ivan Koptiev <ikoptev@gmail.com>
 * @version   2.1.2
 */
class InfiniteAjaxScrollAsset extends AssetBundle
{
    /**
     * @var array List of bundle class names that this bundle depends on.
     */
    public $depends = [
        'yii\web\JqueryAsset',
    ];

    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->sourcePath = '@vendor/webcreate/jquery-ias/src';
        $this->js = [
            'callbacks.js',
            'jquery-ias.js',
            'extension/history.js',
            'extension/noneleft.js',
            'extension/paging.js',
            'extension/spinner.js',
            'extension/trigger.js'
        ];
    }
}

<?php

namespace kop\y2sp\assets;

use yii\web\AssetBundle;

/**
 * This is "InfiniteAjaxScrollAsset" class.
 *
 * This class is an asset bundle for {@link http://infiniteajaxscroll.com/ JQuery Infinite Ajax Scroll plugin}.
 *
 * @link      http://kop.github.io/yii2-scroll-pager Y2SP project page.
 * @license   https://github.com/kop/yii2-scroll-pager/blob/master/LICENSE.md MIT
 *
 * @author    Ivan Koptiev <ikoptev@gmail.com>
 * @version   2.2
 */
class InfiniteAjaxScrollAsset extends AssetBundle
{
    /**
     * @var array List of bundle class names that this bundle depends on.
     */
    public $depends = [
        'yii\web\JqueryAsset',
    ];

    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->sourcePath = '@vendor/webcreate/jquery-ias/src';
        $this->js = [
            'callbacks.js',
            'jquery-ias.js',
            'extension/history.js',
            'extension/noneleft.js',
            'extension/paging.js',
            'extension/spinner.js',
            'extension/trigger.js'
        ];
    }
}

Use composer version of jQuery IAS only

Use composer version of jQuery IAS only


<?php

class SV_Csync2StreamWrapper_CsyncConfig
{
    public function __construct()
    {
        //setlocale(LC_CTYPE, "en_US.UTF-8");
        //$this->debug_log
        //$this->csync_database = "/var/lib/csync2";
    }

    public $deferred_count = 0;
    public $deferred_commit_bulk = false;
    public $deferred_paths = array();
    public $deferred_files =  array();
    public $csync2_binary = "/usr/sbin/csync2";
    public $csync_database = ""; //= "/var/lib/csync2";

    public $debug_mode = false;
    public $debug_log = "";// = "/var/www/html/error.log";

    public $csync_groups = array();
    public $www_code = 'www_code';
    public $www_data = 'www_data';
    public $www_templates = 'www_templates';

    protected $_installed = false;

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

    public function setInstalled($_installed)
    {
        $this->_installed = $_installed;
    }

    protected static $_instance;

    public static function getInstance()
    {
        if (!self::$_instance)
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}

<?php

class SV_Csync2StreamWrapper_CsyncConfig
{
    public function __construct()
    {
        //setlocale(LC_CTYPE, "en_US.UTF-8");
        //$this->debug_log
        //$this->csync_database = "/var/lib/csync2";
    }

    public $deferred_count = 0;
    public $deferred_commit_bulk = false;
    public $deferred_paths = array();
    public $deferred_files =  array();
    public $csync2_binary = "/usr/sbin/csync2";
    public $csync_database = ""; //= "/var/lib/csync2";

    public $debug_mode = false;
    public $debug_log = "";// = "/var/www/html/error.log";

    public $csync_groups = array('www_code', 'www_data', 'www_templates');
    public $www_code = 'www_code';
    public $www_data = 'www_data';
    public $www_templates = 'www_templates';

    protected $_installed = false;

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

    public function setInstalled($_installed)
    {
        $this->_installed = $_installed;
    }

    protected static $_instance;

    public static function getInstance()
    {
        if (!self::$_instance)
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}

Use csync groups when doing a global update.


<?php

namespace Phuby;

class UnboundMethod extends Object {
    protected $owner;
    protected $name;
    protected $block;

    function initialize($owner, $name, $block) {
        $this->owner = $owner;
        $this->name = $name;
        $this->block = $block;
    }

    function bind($receiver) {
        return new Method($this, $receiver);
    }

    function inspect() {
        return '<'.get_called_class().": $this->owner#$this->name>";
    }

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

    function owner() {
        return Module::const_get($this->owner);
    }

    function to_proc() {
        return $this->block;
    }
}

<?php

namespace Phuby;

class UnboundMethod extends Object {
    static function initialized($self) {
        $self->attr_reader('name');
    }

    function initialize($owner, $name, $block) {
        $this->{'@owner'} = $owner;
        $this->{'@name'} = $name;
        $this->{'@block'} = $block;
    }

    function bind($receiver) {
        return new Method($this, $receiver);
    }

    function inspect() {
        return '<'.get_called_class().': '.$this->{'@owner'}.'#'.$this->{'@name'}.'>';
    }

    function name() {
        return $this->{'@name'};
    }

    function owner() {
        return Module::const_get($this->{'@owner'});
    }

    function to_proc() {
        return $this->{'@block'};
    }
}

Use ruby style instance variables in UnboundMethod


<?php namespace Blindern\UKA\Billett\Auth;

class Guard extends \Illuminate\Auth\Guard {
    /**
     * Temporary solution
     */
    protected static $allowed = array(
        'henrste',
        'vegardan',
        'kristinaca',

        // UKEstyret
        'marthhsa',
        'bjornreu',
        'linestandalsoernes',
        'trygvels',
        'miaemilie',
        'grieglet',
        'sebastwi',
        'tirilskaardal',

        // kjellerøkonomi
        'bfesche',
    );

    /**
     * Simple ACL check
     *
     * Check if we have access to a specific role
     *
     * @param string $role Name of role
     * @return boolean
     */
    public function hasRole($role)
    {
        $user = $this->user();

        // TODO: this is only temporary
        if ($user && in_array($user->username, static::$allowed))
        {
            return true;
        }

        return false;
    }

    /**
     * Get list over roles user have access to
     */
    public function getRoles()
    {
        if ($this->hasRole('all')) {
            return array('all');
        }

        return array();
    }

}

<?php namespace Blindern\UKA\Billett\Auth;

class Guard extends \Illuminate\Auth\Guard {
    /**
     * Temporary solution
     */
    protected static $allowed = array(
        'henrste', // ikt 2017/systemansvarlig
        'vegardan', // web 2017
        'kristinaca', // booking 2017

        // UKEstyret 2017
        'marthhsa',
        'bjornreu',
        'linestandalsoernes',
        'trygvels',
        'miaemilie',
        'grieglet',
        'sebastwi',
        'tirilskaardal',

        'bfesche', // kjellerøkonomi 2017
        'stianval', // billettsjef 2017
    );

    /**
     * Simple ACL check
     *
     * Check if we have access to a specific role
     *
     * @param string $role Name of role
     * @return boolean
     */
    public function hasRole($role)
    {
        $user = $this->user();

        // TODO: this is only temporary
        if ($user && in_array($user->username, static::$allowed))
        {
            return true;
        }

        return false;
    }

    /**
     * Get list over roles user have access to
     */
    public function getRoles()
    {
        if ($this->hasRole('all')) {
            return array('all');
        }

        return array();
    }

}

Add access to ticket chief

Add access to ticket chief


<?php
namespace SclZfCartPayment;

use SclZfCart\Entity\OrderInterface;
use SclZfCartPayment\Entity\PaymentInterface;
use Zend\Form\Form;

/**
 * The interface that a payment method must implement to integrate with this
 * payment module.
 *
 * @author Tom Oram <tom@scl.co.uk>
 */
interface PaymentMethodInterface
{
    /**
     * The name of the payment method.
     *
     * @return string
     */
    public function name();

    /**
     * The payment method may update the confirm form.
     *
     * @param  Form             $form
     * @param  OrderInteface    $cart
     * @param  PaymentInterface $cart
     * @return void
     */
    public function updateCompleteForm(
        Form $form,
        OrderInterface $cart,
        PaymentInterface $payment
    );

    /**
     * Takes the values returned from the payment method and completes the payment.
     *
     * @param  array $data
     * @return boolean Return true if the payment was successful
     */
    public function complete(array $data);
}

<?php
namespace SclZfCartPayment;

use SclZfCart\Entity\OrderInterface;
use SclZfCartPayment\Entity\PaymentInterface;
use Zend\Form\Form;

/**
 * The interface that a payment method must implement to integrate with this
 * payment module.
 *
 * @author Tom Oram <tom@scl.co.uk>
 */
interface PaymentMethodInterface
{
    /**
     * The name of the payment method.
     *
     * @return string
     */
    public function name();

    /**
     * The payment method may update the confirm form.
     *
     * @param  Form             $form
     * @param  OrderInteface    $order
     * @param  PaymentInterface $payment
     * @return void
     */
    public function updateCompleteForm(
        Form $form,
        OrderInterface $order,
        PaymentInterface $payment
    );

    /**
     * Takes the values returned from the payment method and completes the payment.
     *
     * @param  array $data
     * @return boolean Return true if the payment was successful
     */
    public function complete(array $data);
}

Fix the param names for updateCompleteForm()


<?php

namespace Illuminate\Encryption;

use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

class EncryptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('encrypter', function ($app) {
            $config = $app->make('config')->get('app');

            // If the key starts with "base64:", we will need to decode the key before handing
            // it off to the encrypter. Keys may be base-64 encoded for presentation and we
            // want to make sure to convert them back to the raw bytes before encrypting.
            if (Str::startsWith($key = $config['key'], 'base64:')) {
                $key = base64_decode(substr($key, 7));
            }

            return new Encrypter($key, $config['cipher']);
        });
    }
}

<?php

namespace Illuminate\Encryption;

use RuntimeException;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

class EncryptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('encrypter', function ($app) {
            $config = $app->make('config')->get('app');

            // If the key starts with "base64:", we will need to decode the key before handing
            // it off to the encrypter. Keys may be base-64 encoded for presentation and we
            // want to make sure to convert them back to the raw bytes before encrypting.
            if (Str::startsWith($key = $config['key'], 'base64:')) {
                $key = base64_decode(substr($key, 7));
            }

            if (is_null($key) || $key === '') {
                throw new RuntimeException(
                    'The application encryption key is missing. Run php artisan key:generate to generate it.'
                );
            }

            return new Encrypter($key, $config['cipher']);
        });
    }
}

Add better error message for missing app key


<?php
/**
 * @file
 * Override Symfony Console's HelpCommand to customize the appearance of help.
 */

namespace Platformsh\Cli\Command;

use Platformsh\Cli\CustomTextDescriptor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand as ParentHelpCommand;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class HelpCommand extends ParentHelpCommand
{

    protected $command;

    /**
     * @inheritdoc
     */
    public function setCommand(Command $command)
    {
        $this->command = $command;
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (null === $this->command) {
            $this->command = $this->getApplication()
                                  ->find($input->getArgument('command_name'));
        }

        if ($input->getOption('xml')) {
            $input->setOption('format', 'xml');
        }

        $helper = new DescriptorHelper();
        $helper->register('txt', new CustomTextDescriptor());
        $helper->describe(
          $output,
          $this->command,
          array(
            'format' => $input->getOption('format'),
            'raw' => $input->getOption('raw'),
          )
        );
    }

}

<?php
/**
 * @file
 * Override Symfony Console's HelpCommand to customize the appearance of help.
 */

namespace Platformsh\Cli\Command;

use Platformsh\Cli\CustomTextDescriptor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand as ParentHelpCommand;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class HelpCommand extends ParentHelpCommand
{

    protected $command;

    /**
     * @inheritdoc
     */
    public function setCommand(Command $command)
    {
        $this->command = $command;
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (null === $this->command) {
            $this->command = $this->getApplication()
                                  ->find($input->getArgument('command_name'));
        }

        if ($input->getOption('xml')) {
            $input->setOption('format', 'xml');
        }

        $helper = new DescriptorHelper();
        $helper->register('txt', new CustomTextDescriptor());
        $helper->describe(
          $output,
          $this->command,
          array(
            'format' => $input->getOption('format'),
            'raw_text' => $input->getOption('raw'),
          )
        );
    }

}

Fix --raw option for help command

Fix --raw option for help command


<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark;

/**
 * Converts CommonMark-compatible Markdown to HTML
 */
class CommonMarkConverter
{
    /**
     * Converts CommonMark to HTML
     * @param string $commonMark
     *
     * @return string
     *
     * @api
     */
    public function convertToHtml($commonMark)
    {
        $environment = Environment::createCommonMarkEnvironment();
        $docParser = new DocParser($environment);
        $renderer = new HtmlRenderer($environment);

        $documentAST = $docParser->parse($commonMark);
        $html = $renderer->renderBlock($documentAST);

        return $html;
    }
}

<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark;

/**
 * Converts CommonMark-compatible Markdown to HTML.
 */
class CommonMarkConverter
{
    /**
     * The document parser instance.
     *
     * @var \League\CommonMark\DocParser
     */
    protected $docParser;

    /**
     * The html renderer instance.
     *
     * @var \League\CommonMark\HtmlRenderer
     */
    protected $htmlRenderer;

    /**
     * Create a new commonmark converter instance.
     */
    public function __construct()
    {
        $environment = Environment::createCommonMarkEnvironment();
        $this->docParser = new DocParser($environment);
        $this->renderer = new HtmlRenderer($environment);
    }

    /**
     * Converts CommonMark to HTML.
     *
     * @param string $commonMark
     *
     * @return string
     *
     * @api
     */
    public function convertToHtml($commonMark)
    {
        $documentAST = $this->docParser->parse($commonMark);

        return $this->renderer->renderBlock($documentAST);
    }
}

Refactor the commonmark converter class

Refactor the commonmark converter class


<?php

namespace PHPSTORM_META {
    override(\ClassRegistry::init(0), map([
        '' => '@'
    ]));
}

<?php

namespace PHPSTORM_META {
    override(\ClassRegistry::init(0), map([
        '' => '@'
    ]));

    expectedArguments(\Model::find(),
        0,
        'first',
        'all',
        'count',
        'list',
        'threaded',
        'neighbors',
    );
}

Add completion for first field of `find()` on Cake2


<?php

/**
 *    Copyright 2015-2018 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

return [
    'top-headers' => [
        'headline' => 'Live Streams',
        'description' => 'Data is fetched from twitch.tv every five minutes based on the directory listing. Feel free to start streaming and get yourself listed! For more information on how to get setup, please check out the wiki page on live streaming.',
    ],
    'headers' => [
        'regular' => 'Currently Streaming',
    ],
];

<?php

/**
 *    Copyright 2015-2018 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

return [
    'top-headers' => [
        'headline' => 'Live Streams',
        'description' => 'Data is fetched from twitch.tv every five minutes based on the directory listing. Feel free to start streaming and get yourself listed! For more information on how to get setup, please check out :here.',

        'here' => 'the wiki page on live streaming',
    ],
    'headers' => [
        'regular' => 'Currently Streaming',
    ],
];

Change the structure of the string

Change the structure of the string


<?php
class InDbValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if ($this->model->$property !== null && $this->model->$property != '') {
			$dbRelation = (isset($rules['relation']) ? $rules['relation'] : false);

			if ($dbRelation) {
				$db = DatabaseFactory::getConnection();
				$dbCast = (isset($rules['type']) ? '::' . $rules['type'] : '');

				$query = "SELECT 1 FROM $dbRelation WHERE $property = ?{$dbCast}";
				if (!$db->getColumn($query, $this->model->$property)) {
					return array('in_db' => array($rules['name'], $this->model->$property));
				}
			}
		}

		return true;
	}
}
?>

<?php
class InDbValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if ($this->model->$property !== null && $this->model->$property != '') {
			$dbRelation = (isset($rules['relation']) ? $rules['relation'] : false);
			$dbColumn = (isset($rules['column']) ? $rules['column'] : $property);

			if ($dbRelation) {
				$db = DatabaseFactory::getConnection();
				$dbCast = (isset($rules['type']) ? '::' . $rules['type'] : '');

				$query = "SELECT 1 FROM $dbRelation WHERE $dbColumn = ?{$dbCast}";
				if (!$db->getColumn($query, $this->model->$property)) {
					return array('in_db' => array($rules['name'], $this->model->$property));
				}
			}
		}

		return true;
	}
}
?>

Update IN_DB validation rule to support specifying column different from model property.


<?php

include_once(__DIR__ . "/classes/includes.php");
session_start();

try {
	// Try creating output from request
	$controller = new Controller($_REQUEST['url']);
	$model = new Model($controller);
	$view = new View($controller, $model);
	echo $view->createOutput();

} catch(Exception $e){
	// Catch possible exceptions
	$exception = new View();
	$exception->setTemplate("error/exception");
	$exception->assign("e", $e);
	echo $exception->createOutput();
}

<?php

include_once(__DIR__ . "/classes/includes.php");
session_start();

try {
	// Try creating output from request
	$controller = new Controller($_REQUEST['url']);
	$model = new Model($controller);
	$view = new View($controller, $model);
	$view->assign("controller", $controller);
	echo $view->createOutput();

} catch(Exception $e){
	// Catch possible exceptions
	$exception = new View();
	$exception->setTemplate("error/exception");
	$exception->assign("e", $e);
	echo $exception->createOutput();
}

FIX assign controller to make it available in template


<?php

require_once("swordappentry.php");
require_once("utils.php");

class SWORDAPPErrorDocument extends SWORDAPPEntry {

	// The error URI
	public $sac_erroruri;

	// Construct a new deposit response by passing in the http status code
	function __construct($sac_newstatus, $sac_thexml) {
		// Call the super constructor
	        parent::__construct($sac_newstatus, $sac_thexml);
	}

	// Build the error document hierarchy
	function buildhierarchy($sac_dr, $sac_ns) {
		// Call the super version
		parent::buildhierarchy($sac_dr, $sac_ns);
		foreach($sac_dr->attributes() as $key => $value) {
		    if ($key == 'href') {
			    $this->sac_erroruri = (string)$value;
		    }
		}
		$this->sac_erroruri = (string)$sac_dr->attributes()->href;
     	}
}

?>

<?php

require_once("swordappentry.php");
require_once("utils.php");

class SWORDAPPErrorDocument extends SWORDAPPEntry {

	// The error URI
	public $sac_erroruri;

	// Summary description of error
	public $sac_error_summary;

	// Verbose description of error
	public $sac_verbose_description;

	// Construct a new deposit response by passing in the http status code
	function __construct($sac_newstatus, $sac_thexml) {
		// Call the super constructor
		parent::__construct($sac_newstatus, $sac_thexml);
	}

	// Build the error document hierarchy
	function buildhierarchy($sac_dr, $sac_ns) {
		// Call the super version
		parent::buildhierarchy($sac_dr, $sac_ns);

		foreach($sac_dr->attributes() as $key => $value) {
			if ($key == 'href') {
				$this->sac_erroruri = (string)$value;
			}
		}
		// Set error summary & verbose description, if available
		if(isset($sac_dr->children($sac_ns['atom'])->summary)) {
			$this->sac_error_summary = (string)$sac_dr->children($sac_ns['atom'])->summary;
		}
		if(isset($sac_dr->children($sac_ns['sword'])->verboseDescription)) {
			$this->sac_verbose_description = (string)$sac_dr->children($sac_ns['sword'])->verboseDescription;
		}
	}
}

?>

Add summary & verbose error description to SWORDAPPErrorDocument


<?php

namespace Picqer\BolPlazaClient\Request;

class CurlHttpRequest
{
    protected $ch = null;

    public function __construct($url)
    {
        $this->ch = curl_init($url);
    }

    public function setOption($option, $value)
    {
        curl_setopt($this->ch, $option, $value);
    }

    public function execute()
    {
        return curl_exec($this->ch);
    }

    public function getInfo($option = null)
    {
        return curl_getinfo($this->ch, $option);
    }

    public function close()
    {
        curl_close($this->ch);
    }

    public function getErrorNumber()
    {
        return curl_errno($this->ch);
    }
}

<?php

namespace Picqer\BolPlazaClient\Request;

class CurlHttpRequest
{
    protected $ch = null;

    public function __construct($url)
    {
        $this->ch = curl_init($url);
    }

    public function setOption($option, $value)
    {
        curl_setopt($this->ch, $option, $value);
    }

    public function execute()
    {
        return curl_exec($this->ch);
    }

    public function getInfo($option = null)
    {
        if($opt) {
            return curl_getinfo($this->ch, $option);
        } else {
            return curl_getinfo($this->ch);
        }
    }

    public function close()
    {
        curl_close($this->ch);
    }

    public function getErrorNumber()
    {
        return curl_errno($this->ch);
    }
}

Fix curl info for php >= 7.4.0

Fix curl info for php >= 7.4.0

PHP 7.4 does not give back all the options when passed null as second argument. This pull request fixes this.


Change build_dest default in config

Change build_dest default in config


<?php
/* ------------------------------------------------------------------------ *\
 * Theme Features
\* ------------------------------------------------------------------------ */

add_theme_support("html5", [
    "comment-list",
    "comment-form",
    "search-form",
    "gallery",
    "caption",
]);

add_theme_support("title-tag");

add_theme_support("automatic-feed-links");

add_theme_support("post-thumbnails");

/**
 * Disable "Additional CSS" in the Customizer screen
 *
 * @param WP_Customize_Manager $wp_customize
 * @return void
 */
function __gulp_init_namespace___disable_additional_css(WP_Customize_Manager $wp_customize): void {
    $wp_customize->remove_control("custom_css");
}
add_action("customize_register", "__gulp_init_namespace___disable_additional_css");

/**
 * Disallow file editing
 */
if (! defined("DISALLOW_FILE_EDIT")) {
    define("DISALLOW_FILE_EDIT", true);
}

<?php
/* ------------------------------------------------------------------------ *\
 * Theme Features
\* ------------------------------------------------------------------------ */

add_theme_support("html5", [
    "comment-list",
    "comment-form",
    "search-form",
    "gallery",
    "caption",
]);

add_theme_support("title-tag");

add_theme_support("automatic-feed-links");

add_theme_support("post-thumbnails");

/**
 * Disable "Additional CSS" in the Customizer screen
 *
 * @param WP_Customize_Manager $wp_customize
 * @return void
 */
function __gulp_init_namespace___disable_additional_css(WP_Customize_Manager $wp_customize): void {
    $wp_customize->remove_control("custom_css");
}
add_action("customize_register", "__gulp_init_namespace___disable_additional_css");

/**
 * Enable "Formats" button in TinyMCE
 *
 * @param array $buttons
 * @return array
 */
function __gulp_init_namespace___tinymce_enable_format_button(array $buttons): array {
    array_unshift($buttons, "styleselect");

    return $buttons;
}
add_filter("mce_buttons_2", "__gulp_init_namespace___tinymce_enable_format_button", 10, 1);

/**
 * Add 'Button' format to TinyMCE
 *
 * @param array $init_array
 * @return array
 */
function __gulp_init_namespace___tinymce_button_format(array $init_array): array {
    $init_array["style_formats"] = wp_json_encode([
        [
            "title"    => esc_html__("Button", "__gulp_init_namespace__"),
            "classes"  => "button",
            "selector" => "a",
        ],
    ]);

    return $init_array;
}
add_filter("tiny_mce_before_init", "__gulp_init_namespace___tinymce_button_format", 10, 1);

/**
 * Disallow file editing
 */
if (! defined("DISALLOW_FILE_EDIT")) {
    define("DISALLOW_FILE_EDIT", true);
}

Add button format to TinyMCE

Add button format to TinyMCE


<?php
namespace Stringizer\Transformers;

/**
 * Empty, checks if value is empty this includes the what is defined by the PHP empty function, see
 * http://php.net/manual/en/function.empty.php prior and includes a value that contains whitespace
 * such as tabs and linefeeds
 *
 * @link https://github.com/jasonlam604/Stringizer
 * @copyright Copyright (c) 2016 Jason Lam
 * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
 */
class EmptyCheck extends Transformer implements TransformerInterface
{

    public function __construct($value)
    {
        parent::__construct($value);
    }

    public function execute()
    {
        return empty(trim($this->getValue()));
    }
}

<?php
namespace Stringizer\Transformers;

use Stringizer\Stringizer;

/**
 * Empty, checks if value is empty this includes the what is defined by the PHP empty function, see
 * http://php.net/manual/en/function.empty.php prior and includes a value that contains whitespace
 * such as tabs and linefeeds
 *
 * @link https://github.com/jasonlam604/Stringizer
 * @copyright Copyright (c) 2016 Jason Lam
 * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
 */
class EmptyCheck extends Transformer implements TransformerInterface
{

    public function __construct($value)
    {
        parent::__construct($value);
    }

    public function execute()
    {
        $s = new Stringizer($this->getValue());
        $s->removeWhitespace();

        return empty(trim($s->getString()));
    }
}

Use RemoveWhitespace class instead of just trim


<?php

class ObserverTest extends Ibuildings_Mage_Test_PHPUnit_ControllerTestCase
{
    public function testDispatchTask()
    {
        $ps = explode(PHP_EOL, `ps ax | grep test_worker`);
        $found = false;
        foreach ($ps as $line) {
            if (preg_match('/php test_worker\.php/', $line)) {
                $found = true;
                break;
            }
        }
        $this->assertTrue($found);
        $id         = uniqid();
        $data       = 'This is a string!';
        $e          = array();
        $e['queue'] = 'test';
        $e['task']  = array(
            'id' => $id,
            'payload' => $data,
            'callback' => 'http://magento.development.local/index.php'
        );
        Mage::dispatchEvent('gearman_do_async_task', $e);
        sleep(1);
        $log = explode(PHP_EOL, file_get_contents('./testing.log'));
        $res = preg_match(
            '/' . $id . ' \- ' . $data . '/',
            $log[count($log) - 2]
        );
        $this->assertEquals(1, $res);
    }
}

<?php

class ObserverTest extends Ibuildings_Mage_Test_PHPUnit_ControllerTestCase
{
    public function testDispatchTask()
    {
        $ps = explode(PHP_EOL, `ps ax | grep test_worker`);
        $found = false;
        foreach ($ps as $line) {
            if (preg_match('/test_worker\.php/', $line)) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            $this->fail(
                'You need to have started test_worker.php from the ' .
                'tests directory'
            );
        }
        $this->assertTrue($found);

        $id         = uniqid();
        $data       = 'This is a string!';
        $e          = array();
        $e['queue'] = 'test';
        $e['task']  = array(
            'id' => $id,
            'payload' => $data,
            'callback' => 'http://magento.development.local/index.php'
        );

        Mage::dispatchEvent('gearman_do_async_task', $e);
        sleep(1);
        $log = explode(
            PHP_EOL,
            file_get_contents(LOG_PATH . 'gearman_testing.log')
        );
        $res = preg_match(
            '/' . $id . ' \- ' . $data . '/',
            $log[count($log) - 2]
        );
        $this->assertEquals(1, $res);
    }
}

Use LOG_PATH for log path and make failures more descriptive


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Flancer32\Lib;

/**
 * Access properties of the data object using accessors (getters & setters).
 *
 * @SuppressWarnings(PHPMD.CamelCaseMethodName)
 */
class DataT030AccessorsSimpleTest
    extends \PHPUnit_Framework_TestCase
{

    public function test_010_asScalar()
    {
        $value = 'value';
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals($value, $obj->getProperty());
    }

    public function test_020_asObj()
    {
        $value = new class
        {
            public $prop = 32;
        };
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals(32, $obj->getProperty()->prop);
    }

    public function test_030_asArr()
    {
        $value = ['prop' => 64];
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals(64, $obj->getProperty()['prop']);
    }
}

<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Flancer32\Lib;

/**
 * Access properties of the data object using accessors (getters & setters).
 *
 * @SuppressWarnings(PHPMD.CamelCaseMethodName)
 */
class DataT030AccessorsSimpleTest
    extends \PHPUnit_Framework_TestCase
{

    public function test_010_asScalar()
    {
        $value = 'value';
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals($value, $obj->getProperty());
    }

    public function test_020_asObj()
    {
        $value = new \stdClass();
        $value->prop = 32;
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals(32, $obj->getProperty()->prop);
    }

    public function test_030_asArr()
    {
        $value = ['prop' => 64];
        $obj = new Data();
        $obj->setProperty($value);
        $this->assertEquals(64, $obj->getProperty()['prop']);
    }
}

Use get(), set(), unset() methods (with or w/o paths).


<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

Update User Role - Date : 28/10/2016

Update User Role - Date : 28/10/2016


---
---
<?php

///////////////////////////////////////
// Basic Config of the phpCAS client //
///////////////////////////////////////

// Full Hostname of your CAS Server
$cas_host = 'cas.fsu.edu';

// Context of the CAS Server
$cas_context = '/cas';

// Port of your CAS server. Normally for a https server it's 443
$cas_port = 443;

// Path to the ca chain that issued the cas server certificate
$cas_server_ca_cert_path = __DIR__ . '/COMODOHigh-AssuranceSecureServerCA.crt';

//////////////////////////////////////////
// Cassowary Setting                    //
//////////////////////////////////////////

// Default list of users with global access
// note: rely on the fact that JSON string lists are PHP compatible
//$cassowary_users = {{ site.administrators | jsonify }};
$cassowary_users = array('{{ site.administrators | join: "', '" }}');

// Show or hide 19th century cassowary prints
$cassowary_show_pics = true;

// Show or hide page debug info
$cassowary_show_debug = false;

---
---
<?php

///////////////////////////////////////
// Basic Config of the phpCAS client //
///////////////////////////////////////

// Full Hostname of your CAS Server
$cas_host = 'cas.fsu.edu';

// Context of the CAS Server
$cas_context = '/cas';

// Port of your CAS server. Normally for a https server it's 443
$cas_port = 443;

// Path to the ca chain that issued the cas server certificate
//$cas_server_ca_cert_path = __DIR__ . '/COMODOHigh-AssuranceSecureServerCA.crt';

//////////////////////////////////////////
// Cassowary Setting                    //
//////////////////////////////////////////

// Default list of users with global access
// note: rely on the fact that JSON string lists are PHP compatible
//$cassowary_users = {{ site.administrators | jsonify }};
$cassowary_users = array('{{ site.administrators | join: "', '" }}');

// Show or hide 19th century cassowary prints
$cassowary_show_pics = true;

// Show or hide page debug info
$cassowary_show_debug = false;

Disable CA cert checking, since it doesn't work on DH.


<?php

function phutil_get_library_root($library) {
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

<?php

function phutil_get_library_root($library = null) {
  if (!$library) {
    $library = phutil_get_current_library_name();
  }
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

Simplify the use of `phutil_get_library_root`

Summary:
Currently, in order to retrieve the library root of the current phutil module, the following code is required:

```lang=php
$library = phutil_get_current_library_name();
$root = phutil_get_library_root($library);
```

This can be simplified by allowing the use of `phutil_get_library_root()` (without any arguments) to mean "get the library root for the current module".

Test Plan: N/A

Reviewers: #blessed_reviewers, epriestley

Reviewed By: #blessed_reviewers, epriestley

Subscribers: Korvin, epriestley

Differential Revision: https://secure.phabricator.com/D11326


<?php

class ErrorHandlerTest extends PHPUnit_Framework_TestCase
{
    public function testHandlesException()
    {
        $handler = new \Fyuze\Error\ErrorHandler();

        ob_start();

        $handler->handle(new Exception('exception handled'));

        $this->assertEquals('exception handled', ob_get_clean());
    }

    public function testHandlesWithRegisteredHandler()
    {
        $handler = new \Fyuze\Error\ErrorHandler();
        $handler->register('TestException', function ($e) {
            echo $e->getMessage();
            return true;
        });

        $message = 'test exception thrown';

        ob_start();

        $handler->handle(new TestException($message));

        $this->assertEquals($message, ob_get_clean());
    }

    public function testCatchesHandlersThrowingErrors()
    {
        $handler = new \Fyuze\Error\ErrorHandler();
        $handler->register('TestException', function ($e) {
            throw new Exception('Oops!');
        });

        ob_start();
        $handler->handle(new TestException('this is just a test'));
        $this->assertTrue(
            strpos(ob_get_clean(), 'Oops!') !== false
        );
    }
}

class TestException extends Exception
{
}

<?php

class ErrorHandlerTest extends PHPUnit_Framework_TestCase
{
    public function testHandlesException()
    {
        $handler = new \Fyuze\Error\ErrorHandler();

        ob_start();

        $handler->handle(new Exception('exception handled'));

        $this->assertEquals('exception handled', ob_get_clean());
    }

    public function testHandlesWithRegisteredHandler()
    {
        $handler = new \Fyuze\Error\ErrorHandler();
        $handler->register('TestException', function ($e) {
            echo $e->getMessage();
            return true;
        });

        $message = 'test exception thrown';

        ob_start();

        $handler->handle(new TestException($message));

        $this->assertEquals($message, ob_get_clean());
    }

    public function testCatchesHandlersThrowingErrors()
    {
        $handler = new \Fyuze\Error\ErrorHandler();
        $handler->register('TestException', function ($e) {
            throw new Exception('Oops!');
        });

        ob_start();
        $handler->handle(new TestException('this is just a test'));
        $this->assertTrue(
            strpos(ob_get_clean(), 'Oops!') !== false
        );
    }

    public function testSetsExceptionHandler() {

        $handler = new \Fyuze\Error\ErrorHandler();

        $reflect = new ReflectionClass($handler);
        $method =$reflect->getMethod('setExceptionHandler');
        $method->setAccessible(true);

        $closure = $method->invoke($handler);

        $message = 'exception handler set';

        ob_start();
        $closure->__invoke(new \Exception($message));
        $this->assertEquals($message, ob_get_clean());
    }

    /**
     * @expectedException ErrorException
     */
    public function testSetsErrorHandler() {

        $handler = new \Fyuze\Error\ErrorHandler();

        $reflect = new ReflectionClass($handler);
        $method =$reflect->getMethod('setErrorHandler');
        $method->setAccessible(true);

        /** @var Closure $closure */
        $closure = $method->invoke($handler);

        $closure(1, '', '', 1);
    }
}

class TestException extends Exception
{
}

Bring coverage back to 100%

Bring coverage back to 100%


<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class OrganismsWithTraitTest extends \PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        //Test for the correct number of elements in the returned array
        list($service) = WebService::factory('details/OrganismsWithTrait');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'trait_type_id' => 1)));
        $this->assertEquals(5, count($results));
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'trait_type_id' => 1, 'limit' => 10)));
        $this->assertEquals(10, count($results));
    }
}

<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class OrganismsWithTraitTest extends \PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        //Test for the correct number of elements in the returned array
        list($service) = WebService::factory('details/OrganismsWithTrait');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'trait_type_id' => 1)));
        $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'trait_type_id' => 1, 'limit' => 10)));
        $this->assertEquals(10, count($results));
    }
}

Fix test for OrganismsWithTrait webservice


<?php
	use \CRD\Core\App as App;
	use \CRD\Core\Template as Template;
	use \CRD\Core\Resource as Resource;

?><!doctype html>
<html lang="<?php echo Resource::$locale; ?>">
	<head>
		<meta charset="utf-8">
		<title><?= ((!empty(Template::$title))? Template::$title . ' — ' : '') . App::$name; ?></title>

		<!-- Handheld support -->
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<!-- CSS includes -->
		<link rel="stylesheet" href="/assets/css/game.css?cache=2">

		<!-- Initialise advanced UI -->
		<script>document.documentElement.className = 'wf-loading advanced';</script>
	</head>
	<body class="<?= Template::$name ?>">

		<div id="container">
<?= Template::content('main') ?>
		</div>

		<!-- Script includes -->
		<script src="/assets/js/3rd-party/jquery-1.8.3.min.js"></script>
		<script src="/assets/js/3rd-party/head.load.min.js"></script>
		<script src="/assets/js/3rd-party/typekit-loader.min.js"></script>

		<!-- Leaderboard functionality -->
		<script src="/assets/js/game.js?cache=2"></script>
	</body>
</html>

<?php
	use \CRD\Core\App as App;
	use \CRD\Core\Template as Template;
	use \CRD\Core\Resource as Resource;

?><!doctype html>
<html lang="<?php echo Resource::$locale; ?>">
	<head>
		<meta charset="utf-8">
		<title><?= ((!empty(Template::$title))? Template::$title . ' — ' : '') . App::$name; ?></title>

		<!-- Handheld support -->
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<!-- CSS includes -->
		<link rel="stylesheet" href="/assets/css/game.css?cache=<?= urlencode(App::$version) ?>">

		<!-- Initialise advanced UI -->
		<script>document.documentElement.className = 'wf-loading advanced';</script>
	</head>
	<body class="<?= Template::$name ?>">

		<div id="container">
<?= Template::content('main') ?>
		</div>

		<!-- Script includes -->
		<script src="/assets/js/3rd-party/jquery-1.8.3.min.js"></script>
		<script src="/assets/js/3rd-party/head.load.min.js"></script>
		<script src="/assets/js/3rd-party/typekit-loader.min.js"></script>

		<!-- Leaderboard functionality -->
		<script src="/assets/js/game.js?cache=<?= urlencode(App::$version) ?>"></script>
	</body>
</html>

Use version string as cache-busting query string


<?php
// check if the flexible content field has rows of data
if( have_rows('blocks') ): ?>

<?php

    if(!isset( $GLOBALS['fcb_rows_count'] ) )
		$GLOBALS['fcb_rows_count'] = 0;

?>

    <?php
    // loop through the rows of data
    while ( have_rows('blocks') ) : the_row(); ?>

        <?php cfb_template('blocks/layout-base', get_row_layout()); $GLOBALS['fcb_rows_count']++; ?>
<?php
    endwhile;

endif;

?>

<?php
// check if the flexible content field has rows of data
if( have_rows('blocks') ): ?>

<?php

    if(!isset( $GLOBALS['fcb_rows_count'] ) )
	$GLOBALS['fcb_rows_count'] = 0;

?>

    <?php
    // loop through the rows of data
    while ( have_rows('blocks') ) : the_row(); ?>

        <?php
        	do_action('fcb_before_block');
        	cfb_template('blocks/layout-base', get_row_layout());
        	do_action('fcb_after_block');
        	$GLOBALS['fcb_rows_count']++;

       	?>
<?php
    endwhile;

endif;

?>

Add action hooks before and after block

Add action hooks before and after block


<?php

namespace spec\SearchApi\Providers;

use SearchApi;
use SearchApi\Models;
use SearchApi\Services\Search;
use SearchApi\Builders\QueryBuilder;
use SearchApi\Clients\HttpClient;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

/**
 * SolrSearchSpec - Spec test for SolrSearch
 */
class SolrSearchSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' );
  }

  function it_should_call_query_builder( QueryBuilder $queryBuilder ) {
    $this->beConstructedWith( $queryBuilder );

    $queryBuilder->build( 'test', null )->shouldBeCalled();

    $this->query( 'test' );
  }

  function it_should_return_null_when_keywords_empty() {
    $result = $this->query( null );

    $result->shouldBeNull();
  }

  function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) {
    $queryBuilder->build( 'test', null )->willReturn( 'test2' );
    $httpClient->get( Argument::any() )->willReturn( '{"responseHeader":{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' );

    $result = $this->query( 'test' );
    $result->shouldHaveType( 'SearchApi\Models\SearchResult' );
    $result->count->shouldBe( 1 );
  }
}

<?php

namespace spec\SearchApi\Providers;

use SearchApi;
use SearchApi\Models;
use SearchApi\Services\Search;
use SearchApi\Builders\QueryBuilder;
use SearchApi\Clients\HttpClient;

use PhpSpec\ObjectBehavior;

/**
 * SolrSearchSpec - Spec test for SolrSearch
 */
class SolrSearchSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' );
  }

  function it_should_call_query_builder( QueryBuilder $queryBuilder ) {
    $this->beConstructedWith( $queryBuilder );

    $queryBuilder->build( 'test', null )->shouldBeCalled();

    $this->query( 'test' );
  }

  function it_should_return_null_when_keywords_empty() {
    $result = $this->query( null );

    $result->shouldBeNull();
  }

  function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) {
    $queryBuilder->build( 'test', null )->willReturn( 'test_query' );
    $httpClient->get( 'test_query' )->willReturn( '{"responseHeader":{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' );

    $result = $this->query( 'test' );
    $result->shouldHaveType( 'SearchApi\Models\SearchResult' );
    $result->count->shouldBe( 1 );
  }
}

Use literal param in prophecy

Use literal param in prophecy


<?php
/* This is a list of packages and versions
 * that will be used to create the PEAR folder
 * in the windows snapshot.
 * See win32/build/mkdist.php for more details
 * $Id$
 */
$packages  = array(
"PEAR"                  =>    "1.3.1",
"Mail"                  =>    "1.1.2",
"Net_SMTP"              =>    "1.2.5",
"Net_Socket"            =>    "1.0.1",
"PHPUnit"               =>    "2.0.0beta1",
"Console_Getopt"        =>    "1.2",
"DB"                    =>    "1.6.2",
"HTTP"                  =>    "1.2.3",
"Archive_Tar"           =>    "1.1",
"Pager"                 =>    "1.0.8",
"HTML_Template_IT"      =>    "1.1",
"XML_Parser"            =>    "1.0.1",
"XML_RPC"               =>    "1.1.0",
"Net_UserAgent_Detect"  =>    "1.0",
"PEAR_Frontend_Web"     =>    "0.3"
);

?>

<?php
/* This is a list of packages and versions
 * that will be used to create the PEAR folder
 * in the windows snapshot.
 * See win32/build/mkdist.php for more details
 * $Id$
 */
$packages  = array(
"PEAR"                  =>    "1.3.1",
"Mail"                  =>    "1.1.3",
"Net_SMTP"              =>    "1.2.5",
"Net_Socket"            =>    "1.0.1",
"PHPUnit"               =>    "2.0.0beta1",
"Console_Getopt"        =>    "1.2",
"DB"                    =>    "1.6.2",
"HTTP"                  =>    "1.2.3",
"Archive_Tar"           =>    "1.1",
"Pager"                 =>    "1.0.8",
"HTML_Template_IT"      =>    "1.1",
"XML_Parser"            =>    "1.0.1",
"XML_RPC"               =>    "1.1.0",
"Net_UserAgent_Detect"  =>    "1.0",
"PEAR_Frontend_Web"     =>    "0.3"
);

?>

Include Mail 1.1.3 with PHP 5.

Include Mail 1.1.3 with PHP 5.


<?php

namespace Furniture\FrontendBundle\Form\Type\UserProfile;

use Furniture\RetailerBundle\Entity\RetailerUserProfile;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RetailerUserProfileType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => RetailerUserProfile::class
        ]);
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('position', 'text', [
                'label' => 'frontend.position',
                'required' => false
            ])
            ->add('phones', 'text', [
                'label' => 'frontend.phones_contact',
                'required' => false
            ]);

        $builder->get('phones')->addModelTransformer(new ArrayToStringTransformer(','));
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'retailer_user_profile';
    }
}

<?php

namespace Furniture\FrontendBundle\Form\Type\UserProfile;

use Furniture\CommonBundle\Form\DataTransformer\ArrayToStringTransformer;
use Furniture\RetailerBundle\Entity\RetailerUserProfile;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RetailerUserProfileType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => RetailerUserProfile::class
        ]);
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('position', 'text', [
                'label' => 'frontend.position',
                'required' => false
            ])
            ->add('phones', 'text', [
                'label' => 'frontend.phones_contact',
                'required' => false
            ]);

        $builder->get('phones')->addModelTransformer(new ArrayToStringTransformer(','));
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'retailer_user_profile';
    }
}

Fix phones in update profile form

Fix phones in update profile form


<?php

namespace AlgoWeb\PODataLaravel\Kernels;

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

class ConsoleKernel extends Kernel
{
    /**
     * The bootstrap classes for the application.
     *
     * @var array
     */
    protected $bootstrappers = [
        'Illuminate\Foundation\Bootstrap\DetectEnvironment',
        'Illuminate\Foundation\Bootstrap\HandleExceptions',
        'Illuminate\Foundation\Bootstrap\RegisterFacades',
        'Illuminate\Foundation\Bootstrap\SetRequestForConsole',
        'Illuminate\Foundation\Bootstrap\RegisterProviders',
        'Illuminate\Foundation\Bootstrap\BootProviders',
    ];
}

<?php

namespace AlgoWeb\PODataLaravel\Kernels;

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

class ConsoleKernel extends Kernel
{
    protected $oldEnv = 'Illuminate\Foundation\Bootstrap\DetectEnvironment';
    protected $newEnv = 'Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables';
    protected $env;

    /**
     * The bootstrap classes for the application.
     *
     * @var array
     */
    protected $bootstrappers = [
        'Illuminate\Foundation\Bootstrap\HandleExceptions',
        'Illuminate\Foundation\Bootstrap\RegisterFacades',
        'Illuminate\Foundation\Bootstrap\SetRequestForConsole',
        'Illuminate\Foundation\Bootstrap\RegisterProviders',
        'Illuminate\Foundation\Bootstrap\BootProviders',
    ];

    /**
     * Create a new console kernel instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function __construct(Application $app, Dispatcher $events)
    {
        if (class_exists($this->oldEnv)) {
            $this->env = $this->oldEnv;
        } else {
            $this->env = $this->newEnv;
        }

        array_unshift($this->bootstrappers, $this->env);
        parent::__construct($app, $events);
    }
}

Make test skeleton bootstrappers polyglot across L5.1-5.4


<?php

use MapasCulturais\i; ?>

        {{field.title}}

<?php i::_e('obrigatório') ?>*

{{::fieldfield.description}}

<?php i::_e('obrigatório') ?>*

<?php $this->part('registration-field-types/fields/brPhone') ?>

<?php

use MapasCulturais\i; ?>

        {{field.title}}

<?php i::_e('obrigatório') ?>*

{{::fieldfield.description}}

<?php $this->part('registration-field-types/fields/brPhone') ?>

Remove duplicitade da informação required


<?php

namespace Knp\RadBundle\DependencyInjection;

use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\DependencyInjection\Container;

class ServiceIdGenerator
{
    public function generateForBundleClass(BundleInterface $bundle, $className)
    {
        $namespace = $bundle->getNamespace();
        $extension = $bundle->getExtension();

        $extensionAlias = $extension->getAlias();

        $bundleClass = substr($className, strlen($namespace) + 1);
        $bundlePart = str_replace('\\', '.', Container::underscore($bundleClass));

        return sprintf('%s.%s', $extensionAlias, $bundlePart);
    }
}

<?php

namespace Knp\RadBundle\DependencyInjection;

use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\DependencyInjection\Container;

class ServiceIdGenerator
{
    public function generateForBundleClass(BundleInterface $bundle, $className)
    {
        $namespace = $bundle->getNamespace();
        $extension = $bundle->getContainerExtension();

        $extensionAlias = $extension->getAlias();

        $bundleClass = substr($className, strlen($namespace) + 1);
        $bundlePart = str_replace('\\', '.', Container::underscore($bundleClass));

        return sprintf('%s.%s', $extensionAlias, $bundlePart);
    }
}

Fix bad method name in service id generator


<?php

namespace SumoCoders\FrameworkMultiUserBundle\Security;

use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class ObjectUserEmailProvider implements UserProviderInterface
{
    /** @var UserRepositoryCollection */
    private $userRepositoryCollection;

    /**
     * @param UserRepositoryCollection $userRepositoryCollection
     */
    public function __construct(UserRepositoryCollection $userRepositoryCollection)
    {
        $this->userRepositoryCollection = $userRepositoryCollection;
    }

    public function loadUserByUsername($username)
    {
        foreach ($this->userRepositoryCollection->all() as $repository) {
            $user = $repository->findByEmailAddress($username);

            if ($user instanceof User) {
                return $user;
            }
        }

        throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', $username)
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user))) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getEmail());
    }

    public function supportsClass($class)
    {
        return $this->userRepositoryCollection->supportsClass($class);
    }
}

<?php

namespace SumoCoders\FrameworkMultiUserBundle\Security;

use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class ObjectUserEmailProvider implements UserProviderInterface
{
    /** @var UserRepositoryCollection */
    private $userRepositoryCollection;

    /**
     * @param UserRepositoryCollection $userRepositoryCollection
     */
    public function __construct(UserRepositoryCollection $userRepositoryCollection)
    {
        $this->userRepositoryCollection = $userRepositoryCollection;
    }

    public function loadUserByUsername($emailAddress)
    {
        foreach ($this->userRepositoryCollection->all() as $repository) {
            $user = $repository->findByEmailAddress($emailAddress);

            if ($user instanceof User) {
                return $user;
            }
        }

        // Since we are using the email as username we keep this exception since it is a part of symfony
        throw new UsernameNotFoundException(
            sprintf('Email "%s" does not exist.', $emailAddress)
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user))) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getEmail());
    }

    public function supportsClass($class)
    {
        return $this->userRepositoryCollection->supportsClass($class);
    }
}

Make it clear that we are using an email as username


Password Reset Complete

Your account's password has been reset. An email has been dispatched with a temporary password you may use to login and then change it to anything you wish.

Update password reset complete page to latest bootstrap.


<?php
/**
 *
 */

namespace Server\Config;

use Mvc5\Config\Config;
use Mvc5\Service\Scope;

trait Server
{
    /**
     *
     */
    use Config;

    /**
     * @return string
     */
    public function documentRoot()
    {
        return $this['DOCUMENT_ROOT'];
    }

    /**
     * @return array
     */
    public function uri()
    {
        return $this['PHP_URI'];
    }

    /**
     *
     */
    public function __clone()
    {
        if (!is_object($this->config)) {
            return;
        }

        if (!$this->config instanceof Scope) {
            $this->config = clone $this->config;
            return;
        }

        $this->config->scope(true);

        $this->config = clone $this->config;

        $this->config->scope($this);
    }
}

<?php
/**
 *
 */

namespace Server\Config;

use Mvc5\Service\Config\Scope;

trait Server
{
    /**
     *
     */
    use Scope;

    /**
     * @return string
     */
    public function documentRoot()
    {
        return $this['DOCUMENT_ROOT'];
    }

    /**
     * @return array
     */
    public function uri()
    {
        return $this['PHP_URI'];
    }
}

Add Service\Config\Scope for clone method


<?php

// TODO: Capitalize the css ns
namespace Kibo\Phast\Services\Css;

use Kibo\Phast\Filters\HTML\ImagesOptimizationService\ImageURLRewriter;
use Kibo\Phast\Retrievers\Retriever;
use Kibo\Phast\Security\ServiceSignature;
use Kibo\Phast\Services\ProxyBaseService;
use Kibo\Phast\Services\ServiceFilter;
use Kibo\Phast\ValueObjects\Resource;

class Service extends ProxyBaseService {

    /**
     * @var ImageURLRewriter
     */
    private $imageUrlRewriter;

    public function __construct(
        ServiceSignature $signature,
        $whitelist,
        Retriever $retriever,
        ServiceFilter $filter,
        ImageURLRewriter $imageURLRewriter
    ) {
        parent::__construct($signature, $whitelist, $retriever, $filter);
        $this->imageUrlRewriter = $imageURLRewriter;
    }

    protected function makeResponse(Resource $resource, array $request) {
        $response = parent::makeResponse($resource, $request);
        $response->setHeader('Content-Type', 'text/css');
        $response->setContent($this->imageUrlRewriter->rewriteStyle($response->getContent()));
        return $response;
    }
}

<?php

namespace Kibo\Phast\Services\Css;

use Kibo\Phast\Filters\HTML\ImagesOptimizationService\ImageURLRewriter;
use Kibo\Phast\Retrievers\Retriever;
use Kibo\Phast\Security\ServiceSignature;
use Kibo\Phast\Services\ProxyBaseService;
use Kibo\Phast\Services\ServiceFilter;
use Kibo\Phast\ValueObjects\Resource;

class Service extends ProxyBaseService {

    /**
     * @var ImageURLRewriter
     */
    private $imageUrlRewriter;

    public function __construct(
        ServiceSignature $signature,
        $whitelist,
        Retriever $retriever,
        ServiceFilter $filter,
        ImageURLRewriter $imageURLRewriter
    ) {
        parent::__construct($signature, $whitelist, $retriever, $filter);
        $this->imageUrlRewriter = $imageURLRewriter;
    }

    protected function makeResponse(Resource $resource, array $request) {
        $response = parent::makeResponse($resource, $request);
        $response->setHeader('Content-Type', 'text/css');
        $response->setContent($this->imageUrlRewriter->rewriteStyle($response->getContent()));
        return $response;
    }
}

Remove todo: Renaming to uppercase breaks service discovery


<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Categories Toolbar Class
 *
 * @author      John Bell <http://nooku.assembla.com/profile/johnbell>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 */
class ComCategoriesControllerToolbarCategories extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSeperator()
			 ->addEnable(array('label' => 'publish'))
			 ->addDisable(array('label' => 'unpublish'));
    }

    protected function _commandNew(KControllerToolbarCommand $command)
    {
        $option  = $this->_identifier->package;
		$view	 = KInflector::singularize($this->_identifier->name);
		$section = $this->getController()->getModel()->get('section');

        $command->append(array(
            'attribs' => array(
                'href'     => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&section='.$section )
            )
        ));
    }
}

<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Categories Toolbar Class
 *
 * @author      John Bell <http://nooku.assembla.com/profile/johnbell>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 */
class ComCategoriesControllerToolbarCategories extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
			 ->addEnable(array('label' => 'publish'))
			 ->addDisable(array('label' => 'unpublish'));

        return parent::getCommands();
    }

    protected function _commandNew(KControllerToolbarCommand $command)
    {
        $option  = $this->_identifier->package;
		$view	 = KInflector::singularize($this->_identifier->name);
		$section = $this->getController()->getModel()->get('section');

        $command->append(array(
            'attribs' => array(
                'href'     => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&section='.$section )
            )
        ));
    }
}

Insert custom commands through the getCommands() function.


<?php

class SearchController extends BaseController {

    protected $layout = 'layouts.master';

	public function showSearchForm()
	{
		$this->layout->content = View::make('search');
	}

	public function showResults()
	{
	    $query = Input::get('q');
	    $facets = array('author' => 10, 'inLanguage' => 10);
	    $options = array('facets' => $facets);

	    if (Input::get('startNum')){
	        $options['startNum'] = Input::get('startNum');
	    }

	    $response = Bib::Search($query, Session::get('accessToken'), $options);
	    if (is_a($response, '\Guzzle\Http\Exception\BadResponseException')) {
	        $this->layout->content = View::make('error', array('title' => 'Error', 'error' => $response));
	    } else {

	        $this->layout->content = View::make('search.results', array('title' => 'Search Results', 'search' => $response, 'query' => $query, 'pagination' => pagination($response)));
	    }
	}
}

<?php

class SearchController extends BaseController {

    protected $layout = 'layouts.master';

	public function showSearchForm()
	{
		$this->layout->content = View::make('search');
	}

	public function showResults()
	{
	    $query = Input::get('q');
	    $facets = array('about' => 10, 'author' => 10, 'datePublished' => 10, 'genre' => 10, 'itemType' => 10, 'inLanguage' => 10);
	    $options = array('facets' => $facets);

	    if (Input::get('startNum')){
	        $options['startNum'] = Input::get('startNum');
	    }

	    $response = Bib::Search($query, Session::get('accessToken'), $options);
	    if (is_a($response, '\Guzzle\Http\Exception\BadResponseException')) {
	        $this->layout->content = View::make('error', array('title' => 'Error', 'error' => $response));
	    } else {

	        $this->layout->content = View::make('search.results', array('title' => 'Search Results', 'search' => $response, 'query' => $query, 'pagination' => pagination($response)));
	    }
	}
}

Make Search Controller request all facets be shown


<?php
define('ENVIRONMENT_LOCAL', 0);
define('ENVIRONMENT_CURRENT', ENVIRONMENT_LOCAL);

define('DOMAIN', getenv('MULTISITE_DOMAIN'));
define('BASE_URL','http://movies.'.DOMAIN.'/');
define('SUPER_SEARCH_URL', 'http://search.'.DOMAIN.'/index.php?q=');
define('ROOT_PATH', dirname(__FILE__, 2).'/');

define('API_URL', BASE_URL.'api/');
define('HOME_URL', BASE_URL.'');
define('RATED_URL', BASE_URL.'rated/');
define('SUGGESTIONS_URL', BASE_URL.'suggestions/');
define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');

<?php
define('ENVIRONMENT_LOCAL', 0);
define('ENVIRONMENT_CURRENT', ENVIRONMENT_LOCAL);

//Path constants
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');

//Url Constants
define('DOMAIN', getenv('MULTISITE_DOMAIN'));
define('BASE_URL','http://movies.'.DOMAIN.'/');
define('SUPER_SEARCH_URL', 'http://search.'.DOMAIN.'/index.php?q=');

define('API_URL', BASE_URL.'api/');
define('HOME_URL', BASE_URL.'');
define('RATED_URL', BASE_URL.'rated/');
define('SUGGESTIONS_URL', BASE_URL.'suggestions/');
define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

//Application constants
define('APP_TITLE', 'Movie List');

Reorder constants for clarity and add app title constant


<?php
/**
 * Custom functions that act independently of the theme templates.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package _s
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function _s_body_classes( $classes ) {
	// Adds a class of group-blog to blogs with more than 1 published author.
	if ( is_multi_author() ) {
		$classes[] = 'group-blog';
	}

	return $classes;
}
add_filter( 'body_class', '_s_body_classes' );

<?php
/**
 * Custom functions that act independently of the theme templates.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package _s
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function _s_body_classes( $classes ) {
	// Adds a class of group-blog to blogs with more than 1 published author.
	if ( is_multi_author() ) {
		$classes[] = 'group-blog';
	}

	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	return $classes;
}
add_filter( 'body_class', '_s_body_classes' );

Add 'hfeed' class via body_class

Add 'hfeed' class via body_class

* Only add the 'hfeed' class when viewing a non-singular page, such as an index or archive


<?php

namespace CloudCreativity\Utils\Collection\Tests;

use CloudCreativity\Utils\Collection\Collection;
use CloudCreativity\Utils\Collection\StandardIterator;
use DateTime;

class DateTimeIterator extends StandardIterator
{

    /**
     * DateTimeIterator constructor.
     *
     * @param DateTime[] ...$items
     */
    public function __construct(DateTime ...$items)
    {
        parent::__construct(...$items);
    }

    /**
     * @param $format
     * @return Collection
     */
    public function format($format)
    {
        return $this->stack->invoke('format', $format);
    }
}

<?php

/**
 * Copyright 2017 Cloud Creativity Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace CloudCreativity\Utils\Collection\Tests;

use CloudCreativity\Utils\Collection\Collection;
use CloudCreativity\Utils\Collection\StandardIterator;
use DateTime;

/**
 * Class DateTimeIterator
 *
 * @package CloudCreativity\Utils\Collection
 */
class DateTimeIterator extends StandardIterator
{

    /**
     * DateTimeIterator constructor.
     *
     * @param DateTime[] ...$items
     */
    public function __construct(DateTime ...$items)
    {
        parent::__construct(...$items);
    }

    /**
     * @param $format
     * @return Collection
     */
    public function format($format)
    {
        return $this->stack->invoke('format', $format);
    }
}

Add doc blocks to test iterator

[Docs] Add doc blocks to test iterator


<?php
/**
 * Copyright 2017 The WildPHP Team
 *
 * You should have received a copy of the MIT license with the project.
 * See the LICENSE file for more information.
 */

use WildPHP\Core\EventEmitter;

class EventEmitterTest extends \PHPUnit\Framework\TestCase
{
	public function testFirst()
	{
		$eventEmitter = new EventEmitter();

		$eventEmitter->on('test', [$this, 'ing']);
		$eventEmitter->on('test', [$this, 'foo']);
		$eventEmitter->first('test', [$this, 'bar']);

		$listeners = $eventEmitter->listeners('test');
		self::assertEquals([[$this, 'bar'], [$this, 'ing'], [$this, 'foo']], $listeners);
		self::assertEquals([$this, 'bar'], array_shift($listeners));
	}

	public function ing()
	{

	}

	public function foo()
	{

	}

	public function bar()
	{

	}
}

<?php
/**
 * Copyright 2017 The WildPHP Team
 *
 * You should have received a copy of the MIT license with the project.
 * See the LICENSE file for more information.
 */

use WildPHP\Core\EventEmitter;

class EventEmitterTest extends \PHPUnit\Framework\TestCase
{
	public function testFirst()
	{
		$eventEmitter = new EventEmitter();

		$eventEmitter->on('test', [$this, 'ing']);
		$eventEmitter->on('test', [$this, 'foo']);
		$eventEmitter->first('test', [$this, 'bar']);

		$listeners = $eventEmitter->listeners('test');
		self::assertEquals([[$this, 'bar'], [$this, 'ing'], [$this, 'foo']], $listeners);
		self::assertEquals([$this, 'bar'], array_shift($listeners));

		$eventEmitter->on('ing', [$this, 'foo']);
		$listeners = $eventEmitter->listeners('ing');
		self::assertEquals([[$this, 'foo']], $listeners);
		self::assertEquals([$this, 'foo'], array_shift($listeners));
	}

	public function ing()
	{

	}

	public function foo()
	{

	}

	public function bar()
	{

	}
}

Test with empty listener list to be sure.

Signed-off-by: Yoshi2889 <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com>


<?php
/**
 * Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de>
 * Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */
?>
<input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" />

	<input type="hidden" id="bookmark_add_id" value="0" />
	<input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" />
	<input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" />
	<input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" />
	<input type="submit" value="<?php echo $l->t('Add bookmark'); ?>" id="bookmark_add_submit" />

	<?php
		echo $l->t('You have no bookmarks');
		require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php');
		createBookmarklet();
	?>

<?php
/**
 * Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de>
 * Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */
?>
<input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" />

	<input type="hidden" id="bookmark_add_id" value="0" />
	<input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" />
	<input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" />
	<input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" />
	<input type="submit" value="<?php echo $l->t('Save bookmark'); ?>" id="bookmark_add_submit" />

	<?php
		echo $l->t('You have no bookmarks');
		require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php');
		createBookmarklet();
	?>

Change label for saving bookmark button

Change label for saving bookmark button


<?php
$ds = DIRECTORY_SEPARATOR;
include __DIR__ . $ds . ".." . $ds . "vendor" . $ds . "autoload.php";

<?php
$ds = DIRECTORY_SEPARATOR;
$paths = array(
    ".." . $ds . "vendor",
    ".." . $ds . ".." . $ds . ".."
);
foreach ($paths as $path) {
    $abspath = __DIR__ . $ds . $path . $ds . "autoload.php";
    if (file_exists($abspath)) {
        require_once $abspath;
        break;
    }
}

Allow tests execution even when the library is downloaded as a composer package


<?php

namespace wcf\system\form\builder\field;

use wcf\system\WCF;

/**
 * Implementation of a checkbox form field for boolen values.
 *
 * @author  Peter Lohse
 * @copyright   2001-2020 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Form\Builder\Field
 * @since   5.3
 */
class CheckboxFormField extends BooleanFormField
{
    /**
     * @inheritDoc
     */
    protected $javaScriptDataHandlerModule = 'WoltLabSuite/Core/Form/Builder/Field/CheckedVoid';

    /**
     * @inheritDoc
     */
    public function readValue()
    {
        $this->value = $this->getDocument()->hasRequestData($this->getPrefixedId());

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getHtml()
    {
        if ($this->requiresLabel() && $this->getLabel() === null) {
            throw new \UnexpectedValueException("Form field '{$this->getPrefixedId()}' requires a label.");
        }

        return WCF::getTPL()->fetch(
            '__checkboxFormField',
            'wcf',
            [
                'field' => $this,
            ]
        );
    }
}

<?php

namespace wcf\system\form\builder\field;

use wcf\system\WCF;

/**
 * Implementation of a checkbox form field for boolean values.
 *
 * @author  Peter Lohse
 * @copyright   2001-2020 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Form\Builder\Field
 * @since   5.3
 */
class CheckboxFormField extends BooleanFormField
{
    /**
     * @inheritDoc
     */
    protected $javaScriptDataHandlerModule = 'WoltLabSuite/Core/Form/Builder/Field/CheckedVoid';

    /**
     * @inheritDoc
     */
    public function readValue()
    {
        $this->value = $this->getDocument()->hasRequestData($this->getPrefixedId());

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getHtml()
    {
        if ($this->requiresLabel() && $this->getLabel() === null) {
            throw new \UnexpectedValueException("Form field '{$this->getPrefixedId()}' requires a label.");
        }

        return WCF::getTPL()->fetch(
            '__checkboxFormField',
            'wcf',
            [
                'field' => $this,
            ]
        );
    }
}

Fix typo in PHPDoc of CheckboxFormField

Fix typo in PHPDoc of CheckboxFormField


<?php

namespace Mimic\Test\Fake;

class Put {
	public $one;
	public $two;

	protected $_internal = array();

	public function __get($name) {
		return $this->_internal[$name];
	}

	public function __set($name, $value) {
		$this->_internal[$name] = $value;
	}
}

<?php

namespace Mimic\Test\Fake;

class Put {
	public $one;
	public $two;

	public $internal = array();

	public function __get($name) {
		return $this->internal[$name];
	}

	public function __set($name, $value) {
		$this->internal[$name] = $value;
	}
}

Make public for testing purposes.

Make public for testing purposes.


<?php

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

namespace Flarum\Tags\Access;

use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;

class GlobalPolicy extends AbstractPolicy
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

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

    /**
     * @param Flarum\User\User $actor
     * @param string $ability
     * @return bool|void
     */
    public function can(User $actor, string $ability)
    {
        if (in_array($ability, ['viewDiscussions', 'startDiscussion'])) {
            $enoughPrimary = count(Tag::getIdsWhereCan($actor, $ability, true, false)) >= $this->settings->get('min_primary_tags');
            $enoughSecondary = count(Tag::getIdsWhereCan($actor, $ability, false, true)) >= $this->settings->get('min_secondary_tags');

            if ($enoughPrimary && $enoughSecondary) {
                return $this->allow();
            } else {
                return $this->deny();
            }
        }
    }
}

<?php

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

namespace Flarum\Tags\Access;

use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;

class GlobalPolicy extends AbstractPolicy
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

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

    /**
     * @param Flarum\User\User $actor
     * @param string $ability
     * @return bool|void
     */
    public function can(User $actor, string $ability)
    {
        if (in_array($ability, ['viewDiscussions', 'startDiscussion'])) {
            $enoughPrimary = count(Tag::getIdsWhereCan($actor, $ability, true, false)) >= $this->settings->get('flarum-tags.min_primary_tags');
            $enoughSecondary = count(Tag::getIdsWhereCan($actor, $ability, false, true)) >= $this->settings->get('flarum-tags.min_secondary_tags');

            if ($enoughPrimary && $enoughSecondary) {
                return $this->allow();
            } else {
                return $this->deny();
            }
        }
    }
}

Use the correct setting keys

Use the correct setting keys


<?php

namespace Edujugon\PushNotification\Channels;

use Edujugon\PushNotification\Messages\PushMessage;

class ApnChannel extends PushChannel
{
    /**
     * {@inheritdoc}
     */
    protected function pushServiceName()
    {
        return 'apn';
    }

    /**
     * {@inheritdoc}
     */
    protected function buildData(PushMessage $message)
    {
        $data = [
            'aps' => [
                'alert' => [
                    'title' => $message->title,
                    'body' => $message->body,
                ],
                'sound' => $message->sound,
                'badge' => $message->badge,
            ],
        ];

        if (! empty($message->extra)) {
            $data['extraPayLoad'] = $message->extra;
        }

        return $data;
    }
}

<?php

namespace Edujugon\PushNotification\Channels;

use Edujugon\PushNotification\Messages\PushMessage;

class ApnChannel extends PushChannel
{
    /**
     * {@inheritdoc}
     */
    protected function pushServiceName()
    {
        return 'apn';
    }

    /**
     * {@inheritdoc}
     */
    protected function buildData(PushMessage $message)
    {
        $data = [
            'aps' => [
                'alert' => [
                    'title' => $message->title,
                    'body' => $message->body,
                ],
                'sound' => $message->sound,
            ],
        ];

        if (! empty($message->extra)) {
            $data['extraPayLoad'] = $message->extra;
        }

        if (is_numeric($message->badge)) {
            $data['aps']['badge'] = $message->badge;
        }

        return $data;
    }
}

Add a badge key to the data only if it has been provided and is numeric


<?php

/**
 * This file belongs to Kreta.
 * The source code of application includes a LICENSE file
 * with all information about license.
 *
 * @author benatespina <benatespina@gmail.com>
 * @author gorkalaucirica <gorka.lauzirika@gmail.com>
 */

namespace spec\Kreta\Bundle\CommentBundle\DependencyInjection;

use PhpSpec\ObjectBehavior;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Class KretaCommentExtensionSpec.
 *
 * @package spec\Kreta\Bundle\CommentBundle\DependencyInjection
 */
class KretaCommentExtensionSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Kreta\Bundle\CommentBundle\DependencyInjection\KretaCommentExtension');
    }

    function it_loads(ContainerBuilder $container)
    {
        $this->load([], $container);
    }
}

<?php

/**
 * This file belongs to Kreta.
 * The source code of application includes a LICENSE file
 * with all information about license.
 *
 * @author benatespina <benatespina@gmail.com>
 * @author gorkalaucirica <gorka.lauzirika@gmail.com>
 */

namespace spec\Kreta\Bundle\CommentBundle\DependencyInjection;

use PhpSpec\ObjectBehavior;

/**
 * Class KretaCommentExtensionSpec.
 *
 * @package spec\Kreta\Bundle\CommentBundle\DependencyInjection
 */
class KretaCommentExtensionSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Kreta\Bundle\CommentBundle\DependencyInjection\KretaCommentExtension');
    }

    function it_extends_kreta_extension()
    {
        $this->shouldHaveType('Kreta\Bundle\CoreBundle\DependencyInjection\Extension');
    }
}

Add tests for dependency injection

Add tests for dependency injection


<?php

declare(strict_types=1);

namespace Keystone\Queue\Router;

use Keystone\Queue\Envelope;
use Keystone\Queue\Exception\RoutingException;
use Keystone\Queue\Router;

class SimpleRouter implements Router
{
    /**
     * @var object[]
     */
    private $workers;

    /**
     * @param object[] $workers
     */
    public function __construct(array $workers)
    {
        $this->workers = $workers;
    }

    /**
     * {@inheritdoc}
     */
    public function map(Envelope $envelope)
    {
        $className = get_class($envelope->getMessage());
        if (!array_key_exists($className, $this->workers)) {
            throw new RoutingException(sprintf(
                'Unable to find worker for message "%s"',
                $className
            ));
        }

        return $this->workers[$className];
    }
}

<?php

declare(strict_types=1);

namespace Keystone\Queue\Router;

use Keystone\Queue\Envelope;
use Keystone\Queue\Exception\RoutingException;
use Keystone\Queue\Router;

class SimpleRouter implements Router
{
    /**
     * @var object[]
     */
    private $workers;

    /**
     * @param object[] $workers
     */
    public function __construct(array $workers = [])
    {
        $this->workers = $workers;
    }

    /**
     * @param string $messageName
     * @param object $worker
     */
    public function add(string $messageName, $worker)
    {
        $this->workers[$messageName] = $worker;
    }

    /**
     * {@inheritdoc}
     */
    public function map(Envelope $envelope)
    {
        $className = get_class($envelope->getMessage());
        if (!array_key_exists($className, $this->workers)) {
            throw new RoutingException(sprintf(
                'Unable to find worker for message "%s"',
                $className
            ));
        }

        return $this->workers[$className];
    }
}

Allow adding workers to the router.

Allow adding workers to the router.


<?php

include '../../config/resync-config.php';

?>

        <title>ResourceSync web test</title>

ResourceSync PHP Client Library

<?php
    include '../../ResyncDiscover.php';
    include '../../ResyncCapabilities.php';
    $resyncdiscover = new ResyncDiscover($_GET['url']);
    $sitemaps = $resyncdiscover->getSitemaps();
?>
    There were <?=count($sitemaps)?> sitemaps found at
    <a href='<?=$resyncdiscover->getURL()?>'><?=$resyncdiscover->getURL()?>:

    <?php foreach ($sitemaps as $sitemap) { ?>

<a href='<?=$sitemap?>'><?=$sitemap?>
<?php
            flush();
            ob_flush();
            $resynccapabilities = new ResyncCapabilities($sitemap);
            $capabilities = $resynccapabilities->getCapabilities();
            foreach($capabilities as $capability => $type) {?>

<a href='<?=$capability?>'><?=$capability?> (capability type: <?=$type?>)
<?php
            }
        ?>

    <?php } ?>

<?php

include '../../config/resync-config.php';

?>

        <title>ResourceSync web test</title>

ResourceSync PHP Client Library

<?php
    include '../../ResyncDiscover.php';
    include '../../ResyncCapabilities.php';
    $resyncdiscover = new ResyncDiscover($_GET['url']);
    $sitemaps = $resyncdiscover->getSitemaps();
?>
    There were <?=count($sitemaps)?> sitemaps found at
    <a href='<?=$resyncdiscover->getURL()?>'><?=$resyncdiscover->getURL()?>:

    <?php foreach ($sitemaps as $sitemap) { ?>

<a href='<?=$sitemap?>'><?=$sitemap?>
<?php
            flush();
            ob_flush();
            $resynccapabilities = new ResyncCapabilities($sitemap);
            $capabilities = $resynccapabilities->getCapabilities();
            foreach($capabilities as $capability => $type) {?>

<a href='<?=$capability?>'><?=$capability?> (capability type: <?=$type?><?php
                    if ($type == 'resourcelist') {
                        ?> [<a href='../baseline/index.php?url=<?=$capability?>'>baseline sync]<?php
                    } else if ($type == 'changelist') {
                        ?> [<a href='../changelist/index.php?url=<?=$capability?>'>update]<?php
                    }
                ?>)
<?php
            }
        ?>

    <?php } ?>

Add links to baseline sync and process changelist


<?php

namespace Michaeljennings\Snapshot\Contracts;

interface Dispatcher
{

}

<?php

namespace Michaeljennings\Snapshot\Contracts;

interface Dispatcher
{
    /**
     * Fire an event.
     *
     * @param mixed $event
     * @param array $data
     * @return \League\Event\EventInterface
     */
    public function emit($event, array $data);

    /**
     * Add an event listener.
     *
     * @param mixed $event
     * @param mixed $listener
     * @return \Michaeljennings\Snapshot\Dispatcher
     */
    public function listen($event, $listener);
}

Add methods to dispatcher contract

Add methods to dispatcher contract