<?php

namespace Zerg\Field;

use Zerg\Stream\AbstractStream;

/**
 * String represents string type data.
 *
 * Data, parsed by this type of field returns as it is in binary file.
 * @since 0.1
 * */
class String extends Scalar
{
    /**
     * @var bool Whether returned string should process like UTF-8 encoded.
     * */
    protected $utf;

    /**
     * Read string from stream as it is.
     *
     * @param AbstractStream $stream Stream from which read.
     * @return string Returned string.
     */
    public function read(AbstractStream $stream)
    {
        $string = $stream->getReader()->readString($this->getSize());

        if ($this->utf) {

            if (strlen($string) < 2) {
                return '';
            }

            if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff ||
                ord($string[0]) == 0xff && ord($string[1]) == 0xfe) {
                $string = substr($string, 2);
            }

            return $string;

        }

        return $this->format($string);
    }
}

<?php

namespace Zerg\Field;

use Zerg\Stream\AbstractStream;

/**
 * String represents string type data.
 *
 * Data, parsed by this type of field returns as it is in binary file.
 * @since 0.1
 * */
class String extends Scalar
{
    /**
     * @var bool Whether returned string should process like UTF-8 encoded.
     * */
    protected $utf;

    /**
     * Read string from stream as it is.
     *
     * @param AbstractStream $stream Stream from which read.
     * @return string Returned string.
     */
    public function read(AbstractStream $stream)
    {
        $string = $stream->getReader()
            ->setCurrentBit(0)
            ->readString($this->getSize());

        if ($this->utf) {

            if (strlen($string) < 2) {
                return '';
            }

            if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff ||
                ord($string[0]) == 0xff && ord($string[1]) == 0xfe) {
                $string = substr($string, 2);
            }

            return $string;

        }

        return $this->format($string);
    }
}

Clear current bit in reader while read string field Just for avoiding unwonted behaviour when read part of byte then string and again part of byte


<?php

/*
 * This file is part of the Eulogix\Lib package.
 *
 * (c) Eulogix <http://www.eulogix.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eulogix\Lib\Java;

/**
 * @author Pietro Baricco <pietro@eulogix.com>
 */

class Bridge {

    /**
     * @var string
     */
    private $url = "", $dir = "";

    /**
     * @param string $url
     */
    public function __construct($url, $dir) {
        $this->url = $url;
        $this->dir = $dir;

        $javaInc = $dir.DIRECTORY_SEPARATOR."Java.inc";
        if(!file_exists($javaInc)) {
            copy("$url/java/Java.inc", $javaInc);
        }

        require_once($javaInc);
    }

    /**
     * @param string $class
     * @return object
     */
    public function instanceJavaClass($class)
    {
        return new \java($class);
    }

}

<?php

/*
 * This file is part of the Eulogix\Lib package.
 *
 * (c) Eulogix <http://www.eulogix.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eulogix\Lib\Java;

/**
 * @author Pietro Baricco <pietro@eulogix.com>
 */

class Bridge {

    /**
     * @var string
     */
    private $url = "";

    /**
     * @param string $url
     */
    public function __construct($url) {
        $this->url = $url;
        require_once("$url/java/Java.inc");
    }

    /**
     * @param string $class
     * @return object
     */
    public function instanceJavaClass($class)
    {
        return new \java($class);
    }

}

Revert "Java.inc now included from a cache so that it is debuggable"

This reverts commit ad4c67b356187883ba050056aab430a4f83cd14c.


<?php
namespace pshopws;

/**
 * @author Marcos Redondo <kusflo at gmail.com>
 */
class ServiceSimpleXmlToArray
{
    public static function take($xmlObject)
    {
        $service = new self($xmlObject);
        return $service->xmlToArray($xmlObject);
    }

    public static function takeMultiple($xmlObjects)
    {
        foreach ($xmlObjects as $obj) {
            $array[] = self::take($obj);
        }
        return $array;
    }

    private function __construct($xmlObject)
    {
        if (!is_a($xmlObject, \SimpleXMLElement::class)) {
            throw new PShopWsException('The service ' . __CLASS__ . ' has received a parameter other than SimpleXmlElement');
        }
    }

    private function xmlToArray($xmlObject, $out = array())
    {
        foreach ((array)$xmlObject as $index => $node) {
            $out[$index] = (is_object($node)) ? $this->xmlToArray($node) : $node;
        }
        return $out;
    }
}

<?php

namespace pshopws;

/**
 * @author Marcos Redondo <kusflo at gmail.com>
 */
class ServiceSimpleXmlToArray
{
    public static function take($xmlObject)
    {
        $service = new self($xmlObject);

        return $service->xmlToArray($xmlObject);
    }

    public static function takeMultiple($xmlObjects)
    {
        $array = array();
        foreach ($xmlObjects as $obj) {
            $array[] = self::take($obj);
        }

        return $array;
    }

    private function __construct($xmlObject)
    {
        if (!is_a($xmlObject, \SimpleXMLElement::class)) {
            throw new PShopWsException('The service '.__CLASS__.' has received a parameter other than SimpleXmlElement');
        }
    }

    private function xmlToArray($xmlObject, $out = array())
    {
        foreach ((array)$xmlObject as $index => $node) {
            $out[$index] = (is_object($node)) ? $this->xmlToArray($node) : $node;
        }

        return $out;
    }
}

Change to LF end of line

Change to LF end of line


<?php namespace TCK\Odbc;

use Illuminate\Database\Connection;

class ODBCConnection extends Connection {

	/**
	 * Get the default query grammar instance.
	 *
	 * @return Illuminate\Database\Query\Grammars\Grammars\Grammar
	 */
	protected function getDefaultQueryGrammar()
	{
		return $this->withTablePrefix( new ODBCQueryGrammar );
	}

	/**
	 * Get the default schema grammar instance.
	 *
	 * @return Illuminate\Database\Schema\Grammars\Grammar
	 */
	protected function getDefaultSchemaGrammar()
	{
		return $this->withTablePrefix( new ODBCSchemaGrammar );
	}

}

<?php namespace TCK\Odbc;

use Illuminate\Database\Connection;

class ODBCConnection extends Connection {

	/**
	 * Get the default query grammar instance.
	 *
	 * @return Illuminate\Database\Query\Grammars\Grammars\Grammar
	 */
	protected function getDefaultQueryGrammar()
	{
		$class = config('database.connections.odbc.grammar.query') ?: '\TCK\Odbc\ODBCQueryGrammar';
		return $this->withTablePrefix( new $class );
	}

	/**
	 * Get the default schema grammar instance.
	 *
	 * @return Illuminate\Database\Schema\Grammars\Grammar
	 */
	protected function getDefaultSchemaGrammar()
	{
		$class = config('database.connections.odbc.grammar.schema') ?: '\TCK\Odbc\ODBCSchemaGrammar';
		return $this->withTablePrefix( new ODBCSchemaGrammar );
	}

}

Allow grammer classes to be overridden via config


<?php

namespace IPay;

interface IPayInterface
{
    /**
     * This method use for set price in Rial.
     *
     * @param int $amount in Rial
     *
     * @return $this
     */
    public function set($amount);

    /**
     * Some of the ports can be send additional data to port server.
     * This method for set this additional data.
     *
     * @param array $data
     *
     * @return $this
     */
    public function with(array $data);

    /**
     * This method use for done everything that necessary before redirect to port.
     *
     * @return $this
     */
    public function ready();

    /**
     * Get ref id, in some ports ref id has a different name such as authority
     *
     * @return int|string
     */
    public function getRefId();

    /**
     * This method use for redirect to port
     *
     * @return mixed
     */
    public function redirect();

    /**
     * Return result of payment
     * If result is done, return $this, otherwise throws an related exception
     *
     * @return $this
     */
    public function verify();

    /**
     * Return tracking code
     *
     * @return int|string
     */
    public function trackingCode();
}

<?php

namespace IPay;

interface IPayInterface
{
    /**
     * Initialize class
     *
     * @param IPay\Config $config
     * @param IPay\DatabaseManager $db
     * @param int $portId
     *
     * @return void
     */
    public function __construct(Config $config, DatabaseManager $db, $portId);

    /**
     * This method use for set price in Rial.
     *
     * @param int $amount in Rial
     *
     * @return $this
     */
    public function set($amount);

    /**
     * Some of the ports can be send additional data to port server.
     * This method for set this additional data.
     *
     * @param array $data
     *
     * @return $this
     */
    public function with(array $data);

    /**
     * This method use for done everything that necessary before redirect to port.
     *
     * @return $this
     */
    public function ready();

    /**
     * Get ref id, in some ports ref id has a different name such as authority
     *
     * @return int|string
     */
    public function getRefId();

    /**
     * This method use for redirect to port
     *
     * @return mixed
     */
    public function redirect();

    /**
     * Return result of payment
     * If result is done, return $this, otherwise throws an related exception
     *
     * @return $this
     */
    public function verify();

    /**
     * Return tracking code
     *
     * @return int|string
     */
    public function trackingCode();

    /**
     * Get port id, $this->portId
     *
     * @return int
     */
    public function portId();
}

Add construct and portId to Interface

Add construct and portId to Interface


<?php
namespace elasticsearch;

$sections['integration'] = array(
	'icon' => NHP_OPTIONS_URL.'img/glyphicons/glyphicons_083_random.png',
	'title' => 'Wordpress Integration',
	'fields' => array(
		'enable' => array(
			'id' => 'enable',
			'type' => 'checkbox',
			'title' => 'Enable Search',
			'sub_desc' => 'If enabled, the default wordpress search will use ElasticSearch.'
		),
		'enable_categories' => array(
			'id' => 'enable_categories',
			'type' => 'cats_multi_select',
			'title' => 'Categories to Enable',
			'sub_desc' => 'If enabled, category listings will use ElasticSearch for filtering and faceting. To use faceting, read the facted search implementation instructions'
		)
	)
);

?>

<?php
namespace elasticsearch;

$sections['integration'] = array(
	'icon' => NHP_OPTIONS_URL.'img/glyphicons/glyphicons_083_random.png',
	'title' => 'Wordpress Integration',
	'fields' => array(
		'enable' => array(
			'id' => 'enable',
			'type' => 'checkbox',
			'title' => 'Enable Search',
			'sub_desc' => 'If enabled, the default wordpress search will use ElasticSearch.'
		),
		'enable_categories' => array(
			'id' => 'enable_categories',
			'type' => 'cats_multi_select',
			'title' => 'Categories to Enable',
			'sub_desc' => 'If enabled, category listings will use ElasticSearch for filtering and faceting. To use faceting, read the facted search implementation instructions',
			'args' => array()
		)
	)
);

?>

Add empty args for select to prevent notice


<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
    $path = $configuration->getRootPath();
    $relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path, array('placeholder' => t('Example: %ssome/path', $_SERVER['DOCUMENT_ROOT'])))?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath, array('placeholder' => t('Example: %s', '/some/path')))?>

<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
    $path = $configuration->getRootPath();
    $relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path, array('placeholder' => t('Example: %ssome/path', $_SERVER['DOCUMENT_ROOT'] . '/')))?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath, array('placeholder' => t('Example: %ssome/path', '/')))?>

Fix placeholders on storage location paths

Former-commit-id: a30af224940900603ce5c648b6dddfb77bddf278
Former-commit-id: 3ef7882fdd778d09c921eb931582610c87c5d06d


<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\AdminBundle\DependencyInjection;

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

final class SyliusAdminExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container): void
    {
        $config = $this->processConfiguration($this->getConfiguration([], $container), $config);
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

        $container->setParameter('sylius.admin.notification.enabled', $config['notifications']['enabled']);
        $container->setParameter('sylius.admin.notification.frequency', $config['notifications']['frequency']);
        $container->setParameter('sylius.admin.shop_enabled', false);

        $bundles = $container->getParameter('kernel.bundles');
        if (array_key_exists('SyliusShopBundle', $bundles)) {
            $loader->load('services/integrations/shop.xml');
            $container->setParameter('sylius.admin.shop_enabled', true);
        }

        $loader->load('services.xml');
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\AdminBundle\DependencyInjection;

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

final class SyliusAdminExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container): void
    {
        $config = $this->processConfiguration($this->getConfiguration([], $container), $configs);
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

        $container->setParameter('sylius.admin.notification.enabled', $config['notifications']['enabled']);
        $container->setParameter('sylius.admin.notification.frequency', $config['notifications']['frequency']);
        $container->setParameter('sylius.admin.shop_enabled', false);

        $bundles = $container->getParameter('kernel.bundles');
        if (array_key_exists('SyliusShopBundle', $bundles)) {
            $loader->load('services/integrations/shop.xml');
            $container->setParameter('sylius.admin.shop_enabled', true);
        }

        $loader->load('services.xml');
    }
}

Adjust variable names to interfaces

[Maintenance] Adjust variable names to interfaces


<?php

use Dash\_;

class setTest extends PHPUnit_Framework_TestCase
{
	/**
	 * @dataProvider cases
	 */
	public function test($input, $field, $value, $expected)
	{
		$this->assertEquals($expected, Dash\set($input, $field, $value));
	}

	public function cases()
	{
		return [
		];
	}
}

<?php

use Dash\_;

class setTest extends PHPUnit_Framework_TestCase
{
	public function test()
	{
		$this->markTestIncomplete();
	}
}

Mark set() test as incomplete

Mark set() test as incomplete


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

/**
 * Html View Class
 *
 * @author      Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @package     Nooku_Server
 * @subpackage  Articles
 */

class ComApplicationViewHtml extends KViewHtml
{
    protected function _initialize(KConfig $config)
    {
        $config->append(array(
            'auto_assign' => false,
        ));

        parent::_initialize($config);
    }

    public function display()
    {
        //Set the language information
        $this->language  = JFactory::getLanguage()->getTag();
        $this->direction = JFactory::getLanguage()->isRTL() ? 'rtl' : 'ltr';

        return parent::display();
    }
}

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

/**
 * Html View Class
 *
 * @author      Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @package     Nooku_Server
 * @subpackage  Articles
 */

class ComApplicationViewHtml extends KViewHtml
{
    protected function _initialize(KConfig $config)
    {
        $config->append(array(
            'auto_assign' => false,
            'template_filters' => array('script', 'style', 'link', 'meta'),
        ));

        parent::_initialize($config);
    }

    public function display()
    {
        //Set the language information
        $this->language  = JFactory::getLanguage()->getTag();
        $this->direction = JFactory::getLanguage()->isRTL() ? 'rtl' : 'ltr';

        return parent::display();
    }
}

Add script, style, meta and link filters.


<?php

namespace MinePlus\VoterBundle;

class VoteDispatcher
{

    protected $voters;

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

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

    public function decide($eventName, $event)
    {
        return (boolean) $this->getLevel($eventName, $event);
    }

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

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

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

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

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

}

?>

<?php

namespace MinePlus\VoterBundle;

class VoteDispatcher
{

    protected $voters;

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

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

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

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

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

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

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

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

}

?>

Set getLevel() public, fix type-casting bug.


<?php

namespace League\JsonGuard\Test\Constraint;

use League\JsonGuard\Constraint\DraftFour\Type;
use League\JsonGuard\ValidationError;
use League\JsonGuard\Validator;

class TypeTest extends \PHPUnit_Framework_TestCase
{
    function test_numeric_string_is_not_a_number()
    {
        $type = new Type();

        $error = $type->validate('1', 'number', new Validator([], new \stdClass()));

        $this->assertInstanceOf(ValidationError::class, $error);
    }
}

<?php

namespace League\JsonGuard\Test\Constraint;

use League\JsonGuard\Constraint\DraftFour\Type;
use League\JsonGuard\ValidationError;
use League\JsonGuard\Validator;

class TypeTest extends \PHPUnit_Framework_TestCase
{
    function test_numeric_string_is_not_a_number()
    {
        $type = new Type();

        $error = $type->validate('1', 'number', new Validator([], new \stdClass()));

        $this->assertInstanceOf(ValidationError::class, $error);
    }

    function test_numeric_string_is_a_string()
    {
        $type = new Type();

        $error = $type->validate('9223372036854775999', 'string', new Validator([], new \stdClass()));

        $this->assertNull($error);
    }
}

Add test for numeric strings

Add test for numeric strings


<?php

/**
 *
 * This file is part of the Apix Project.
 *
 * (c) Franck Cassedanne <franck at ouarz.net>
 *
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
 *
 */

namespace Apix\Log\tests\Logger;

use Apix\Log\Logger;

class ErrorLogTest extends TestCase
{

    protected $dest = './apix-unit-test-logger.log';
    // protected $dest = '/dev/stdout';

    protected function setUp()
    {
        ini_set('error_log', $this->dest);
    }

    protected function tearDown()
    {
        if (file_exists($this->dest)) {
            unlink($this->dest);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getLogger()
    {
        return new Logger\ErrorLog();
    }

}

<?php

/**
 *
 * This file is part of the Apix Project.
 *
 * (c) Franck Cassedanne <franck at ouarz.net>
 *
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
 *
 */

namespace Apix\Log\tests\Logger;

use Apix\Log\Logger;

class ErrorLogTest extends TestCase
{

    protected $dest = './apix-unit-test-logger.log';
    // protected $dest = '/dev/stdout';

    protected function setUp()
    {
        // HHVM support
        // @see: https://github.com/facebook/hhvm/issues/3558
        if (defined('HHVM_VERSION')) {
            ini_set('log_errors', 'On');
            ini_set('error_log', $this->dest);
        }

        ini_set('error_log', $this->dest);
    }

    protected function tearDown()
    {
        if (file_exists($this->dest)) {
            unlink($this->dest);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getLogger()
    {
        return new Logger\ErrorLog();
    }

}

Fix ini_set('error_log', ...) with HHVM

Fix ini_set('error_log', ...) with HHVM

https://github.com/facebook/hhvm/issues/3558


<?php

class BodyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \HieuLe\BodyClasses\Body
     */
    private $_obj;

    public function setUp()
    {
        parent::setUp();

        $this->_obj = new \HieuLe\BodyClasses\Body();
    }

    public function testAddClassesAsString()
    {
        $this->_obj->addClasses('foo');
        $this->assertEquals(['foo'], $this->_obj->getClassArray());
        $this->assertEquals('foo', $this->_obj->getClasses());
    }

    public function testAddClassesAsArray()
    {
        $this->_obj->addClasses(['bar', 'baz']);
        $this->assertEquals(['bar', 'baz'], $this->_obj->getClassArray());
        $this->assertEquals('bar baz', $this->_obj->getClasses());
    }

    public function testAddDuplicatedClasses()
    {
        $this->_obj->addClasses('foo');
        $this->_obj->addClasses('bar');
        $this->_obj->addClasses(['foo']);

        $this->assertEquals(['foo', 'bar'], $this->_obj->getClassArray());
        $this->assertEquals('foo bar', $this->_obj->getClasses());
    }
}

<?php

class BodyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \HieuLe\BodyClasses\Body
     */
    private $_obj;

    public function setUp()
    {
        parent::setUp();

        $this->_obj = new \HieuLe\BodyClasses\Body();
    }

    public function testAddClassesAsString()
    {
        $this->_obj->addClasses('foo');
        $this->assertEquals(array('foo'), $this->_obj->getClassArray());
        $this->assertEquals('foo', $this->_obj->getClasses());
    }

    public function testAddClassesAsArray()
    {
        $this->_obj->addClasses(array('bar', 'baz'));
        $this->assertEquals(array('bar', 'baz'), $this->_obj->getClassArray());
        $this->assertEquals('bar baz', $this->_obj->getClasses());
    }

    public function testAddDuplicatedClasses()
    {
        $this->_obj->addClasses('foo');
        $this->_obj->addClasses('bar');
        $this->_obj->addClasses(array('foo'));

        $this->assertEquals(array('foo', 'bar'), $this->_obj->getClassArray());
        $this->assertEquals('foo bar', $this->_obj->getClasses());
    }
}

Replace short array syntax to compatible with PHP 5.3


<?php

class SiteMapTest extends FunctionalTest
{
    protected static $fixture_file = 'SiteMapTest.yml';

    public function testSiteMap()
    {
        $this->logInWithPermission('ADMIN');
        // pages need published, fixtures are not
		foreach (Page::get() as $page) {
			$page->doPublish();
		}
		$response = $this->get('/sitemap/');
        $this->assertEquals(200, $response->getStatusCode());
        $positions = array();
        $body = $response->getBody();
        for ($i=1; $i <= 4; $i++) {
        	$row = '
Page ' . $i . '
';
        	$this->assertContains($row, $body);

        	$positions["{$i}"] = strpos($body, $row);
        }

        //assert order
        $this->assertGreaterThan($positions['3'], $positions['4']);
        $this->assertGreaterThan($positions['2'], $positions['3']);
        $this->assertGreaterThan($positions['1'], $positions['2']);
    }
}

<?php

class SiteMapTest extends FunctionalTest
{
    protected static $fixture_file = 'SiteMapTest.yml';

    public function testSiteMap()
    {
        $this->logInWithPermission('ADMIN');
        // pages need published, fixtures are not
		foreach (Page::get() as $page) {
			$page->doPublish();
			error_log($page->ClassName . ':' . $page->Link());
		}
		$response = $this->get('/sitemap/');
        $this->assertEquals(200, $response->getStatusCode());
        $positions = array();
        $body = $response->getBody();

        // assert is a sitemap
       	$this->assertContains('
', $body);

       	// assert root level pages
        for ($i=1; $i <= 4; $i++) {
        	$row = '
Page ' . $i . '';
        	$this->assertContains($row, $body);

        	$positions["{$i}"] = strpos($body, $row);
        }

        //assert order
        $this->assertGreaterThan($positions['3'], $positions['4']);
        $this->assertGreaterThan($positions['2'], $positions['3']);
        $this->assertGreaterThan($positions['1'], $positions['2']);
    }
}

FIX: Test for SiteMap class and sitemap links (was menu)


<?php

/**
 * Mock CreateSend 'general' class.
 *
 * @author			: Stephen Lewis <addons@experienceinternet.co.uk>
 * @copyright		: Experience Internet
 * @package			: Campaigner
 */

require_once dirname(__FILE__).'/mock.base_classes.php';

class Mock_CS_REST_General extends Mock_CS_REST_Wrapper_Base {

	/* --------------------------------------------------------------
	 * PUBLIC METHODS
	 * ------------------------------------------------------------ */

	public function get_timezones() {}
	public function get_systemdate() {}
	public function get_countries() {}
	public function get_apikey($username, $password, $site_url) {}
	public function get_clients() {}
}

/* End of file			: mock.csrest_general.php */
/* File location		: third_party/campaigner/tests/mocks/createsend-php/mock.csrest_general.php */

<?php

/**
 * Mock CreateSend 'general' class.
 *
 * @author			: Stephen Lewis <addons@experienceinternet.co.uk>
 * @copyright		: Experience Internet
 * @package			: Campaigner
 */

require_once PATH_THIRD .'campaigner/tests/mocks/createsend-php/mock.base_classes.php';

class Mock_CS_REST_General extends Mock_CS_REST_Wrapper_Base {

	/* --------------------------------------------------------------
	 * PUBLIC METHODS
	 * ------------------------------------------------------------ */

	public function get_timezones() {}
	public function get_systemdate() {}
	public function get_countries() {}
	public function get_apikey($username, $password, $site_url) {}
	public function get_clients() {}
}

/* End of file			: mock.csrest_general.php */
/* File location		: third_party/campaigner/tests/mocks/createsend-php/mock.csrest_general.php */

Update require_once to use PATH_THIRD, even though it's way more verbose that way.


<?php

declare(strict_types=1);

namespace InvertColor\Exceptions;

use UnexpectedValueException;

class InvalidRGBException extends UnexpectedValueException implements ColorException
{
    /**
     * @var array
     */
    private $value;

    /**
     * @param array $value
     */
    public function __construct(string $explanation, array $value)
    {
        parent::__construct('Invalid RGB: ' . $explanation);
        $this->value = $value;
    }

    /**
     * @return array
     */
    public function getValue(): array
    {
        return $this->value;
    }
}

<?php

declare(strict_types=1);

namespace InvertColor\Exceptions;

use UnexpectedValueException;

class InvalidRGBException extends UnexpectedValueException implements ColorException
{
    /**
     * @var array
     */
    private $value;

    /**
     * @param string $explanation
     * @param array $value
     */
    public function __construct(string $explanation, array $value)
    {
        parent::__construct('Invalid RGB: ' . $explanation);
        $this->value = $value;
    }

    /**
     * @return array
     */
    public function getValue(): array
    {
        return $this->value;
    }
}

Add missing parameter in PhpDoc

Add missing parameter in PhpDoc


@extends('layouts.master')

@section('body', '')

@push('styles')
@endpush

@section('title')
    {{ $category->title }} | @parent
@stop

@section('keywords', $category->param('meta_keywords') ?? config('site.keywords'))
@section('description', $category->param('meta_description') ?? config('site.description'))
@section('author', $category->param('author_alias') ?? config('site.author'))

@section('page-title')
    {{ $category->title }}
@stop

@section('content')
    @if($category->param('show_description'))

                {!! $category->description !!}

    @endif

    @each('category.partials.articles', $articles, 'article', 'category.partials.no-articles')

    {!! $articles->render() !!}
@stop

@extends('layouts.master')

@section('body', '')

@push('styles')
@endpush

@section('title')
    {{ $category->title }} | @parent
@stop

@section('keywords', $category->param('meta_keywords') ?? config('site.keywords'))
@section('description', $category->param('meta_description') ?? config('site.description'))
@section('author', $category->param('author_alias') ?? config('site.author'))

@section('page-title')
    {{ $category->title }}
@stop

@section('content')
    @if($category->description)

                {!! $category->description !!}

    @endif

    @each('category.partials.articles', $articles, 'article', 'category.partials.no-articles')

    {!! $articles->render() !!}
@stop

Fix displaying of category description.

Fix displaying of category description.


<?php

namespace wcf\http\middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use wcf\system\exception\NamedUserException;
use wcf\system\request\RequestHandler;
use wcf\system\WCF;

/**
 * Checks whether the system environment is unacceptable and prevents processing in that case.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Http\Middleware
 * @since   5.6
 */
final class CheckSystemEnvironment implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!RequestHandler::getInstance()->isACPRequest()) {
            if (!(80100 <= \PHP_VERSION_ID && \PHP_VERSION_ID <= 80199)) {
                \header('HTTP/1.1 500 Internal Server Error');

                throw new NamedUserException(WCF::getLanguage()->get('wcf.global.incompatiblePhpVersion'));
            }
        }

        return $handler->handle($request);
    }
}

<?php

namespace wcf\http\middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use wcf\system\exception\NamedUserException;
use wcf\system\request\RequestHandler;
use wcf\system\WCF;

/**
 * Checks whether the system environment is unacceptable and prevents processing in that case.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Http\Middleware
 * @since   5.6
 */
final class CheckSystemEnvironment implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!RequestHandler::getInstance()->isACPRequest()) {
            if (!(80100 <= \PHP_VERSION_ID && \PHP_VERSION_ID <= 80299)) {
                \header('HTTP/1.1 500 Internal Server Error');

                throw new NamedUserException(WCF::getLanguage()->get('wcf.global.incompatiblePhpVersion'));
            }
        }

        return $handler->handle($request);
    }
}

Allow PHP 8.2 in CheckSystemEnvironment

Allow PHP 8.2 in CheckSystemEnvironment


<?php namespace Watson\Autologin;

use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;

class AutologinController extends Controller {

	/**
	 * AuthenticationInterface provider instance.
	 *
	 * @var \Studious\Autologin\Interfaces\AuthenticationInterface
	 */
	protected $provider;

	/**
	 * Studious Autologin instance.
	 *
	 * @var \Studious\Autologin\Autologin
	 */
	protected $autologin;

	/**
	 * Instantiate the controller.
	 */
	public function __construct(AuthenticationInterface $authProvider, Autologin $autologin)
	{
		$this->authProvider = $authProvider;
		$this->autologin = $autologin;
	}

	/**
	 * Process the autologin token and perform the redirect.
	 */
	public function autologin($token)
	{
		if ($autologin = $this->autologin->validate($token))
		{
			// Active token found, login the user and redirect to the
			// intended path.
			$this->authProvider->loginUsingId($autologin->getUserId());

			return Redirect::to($autologin->getPath());
		}

		// Token was invalid, redirect back to the home page.
		return Redirect::to(base_path());
	}

}

<?php namespace Watson\Autologin;

use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;

class AutologinController extends Controller {

	/**
	 * AuthenticationInterface provider instance.
	 *
	 * @var \Studious\Autologin\Interfaces\AuthenticationInterface
	 */
	protected $provider;

	/**
	 * Studious Autologin instance.
	 *
	 * @var \Studious\Autologin\Autologin
	 */
	protected $autologin;

	/**
	 * Instantiate the controller.
	 */
	public function __construct(AuthenticationInterface $authProvider, Autologin $autologin)
	{
		$this->authProvider = $authProvider;
		$this->autologin = $autologin;
	}

	/**
	 * Process the autologin token and perform the redirect.
	 */
	public function autologin($token)
	{
		if ($autologin = $this->autologin->validate($token))
		{
			// Active token found, login the user and redirect to the
			// intended path.
			$this->authProvider->loginUsingId($autologin->getUserId());

			return Redirect::to($autologin->getPath());
		}

		// Token was invalid, redirect back to the home page.
		return Redirect::to('/');
	}

}

Fix redirection to home on invalid token


<?php

namespace JoeTannenbaum\PHPushbullet;

class Device {

	/**
	 * The fields that we want to retrieve for the device
	 *
	 * @var array $fields
	 */

	protected $fields = [
							'nickname',
							'iden',
							'model',
							'type',
							'active',
							'pushable',
							'manufacturer',
							'created',
						];

	public function __construct( Array $attr )
	{
		foreach ( $this->fields as $field )
		{
			$method = 'set' . ucwords( $field );

			if ( method_exists( $this, $method ) )
			{
				// If there is a setter for this field, use that
				$this->$field = $this->$method( $attr[ $field ] );
			}
			else
			{
				// Otherwise just set the property
				$this->$field = $attr[ $field ];
			}
		}
	}

	/**
	 * Format the date so that it's readable
	 *
	 * @param integer $date
	 * @return string
	 */

	protected function setCreated( $date )
	{
		return date( 'Y-m-d h:i:sA T', $date );
	}

}

<?php

namespace JoeTannenbaum\PHPushbullet;

class Device {

	/**
	 * The fields that we want to retrieve for the device
	 *
	 * @var array $fields
	 */

	protected $fields = [
							'nickname',
							'iden',
							'model',
							'type',
							'active',
							'pushable',
							'manufacturer',
							'created',
						];

	public function __construct( Array $attr )
	{
		foreach ( $this->fields as $field )
		{
			$method = 'set' . ucwords( $field );

			if ( method_exists( $this, $method ) )
			{
				// If there is a setter for this field, use that
				$this->$field = $this->$method( $attr[ $field ] );
			}
			else
			{
				// Otherwise just set the property
				$this->$field = isset($attr[ $field ]) ? $attr[ $field ] : null;
			}
		}
	}

	/**
	 * Format the date so that it's readable
	 *
	 * @param integer $date
	 * @return string
	 */

	protected function setCreated( $date )
	{
		return date( 'Y-m-d h:i:sA T', $date );
	}

}

Fix undefined index notice bug

Fix undefined index notice bug


<?php

add_action('enqueue_block_assets', function () {
    // Dequeue default block styles. Must be included in the asset build.
    wp_dequeue_style('wp-core-blocks');
});

<?php

add_action('enqueue_block_assets', function () {
    // Dequeue default block styles. Must be included in the asset build.
    // Must probably be extended to also dequeue additional block styles
    // registered by plugins etc.
    wp_dequeue_style('wp-block-library');
});

Fix dequeuing of default gutenberg block styles


has($fieldname) ? ' has-error' : '' }}">
    {{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}

        <select class="js-data-ajax" data-endpoint="companies" name="{{ $fieldname }}" style="width: 100%" id="company_select">
            @if ($company_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
                <option value="{{ $company_id }}" selected="selected">
                    {{ \App\Models\Company::find($company_id)->name }}
                </option>
            @else
                <option value="">{{ trans('general.select_company') }}</option>
            @endif
        </select>

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

has($fieldname) ? ' has-error' : '' }}">
    {{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}

        <select class="js-data-ajax" data-endpoint="companies" name="{{ $fieldname }}" style="width: 100%" id="company_select">
            @if ($company_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
                <option value="{{ $company_id }}" selected="selected">
                    {{ (\App\Models\Company::find($company_id)) ? \App\Models\Company::find($company_id)->name : '' }}
                </option>
            @else
                <option value="">{{ trans('general.select_company') }}</option>
            @endif
        </select>

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

Check that the company is valid in select ajax


<?php
/**
 * Belgian Police Web Platform - Districts Component
 *
 * @copyright	Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.police.be
 */

namespace Nooku\Component\Districts;
use Nooku\Library;

class DatabaseRowOfficer extends Library\DatabaseRowTable
{
    public function __get($column)
    {
        if($column == 'title' && !isset($this->_data['title'])) {
            $this->_data['title'] = $this->firstname.' '.$this->lastname;
        }

        if($column == 'params' && !is_array($this->_data['params'])) {
           $this->_data['params'] = json_decode($this->_data['params']);
        }

        return parent::__get($column);
    }
}

<?php
/**
 * Belgian Police Web Platform - Districts Component
 *
 * @copyright	Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.police.be
 */

namespace Nooku\Component\Districts;
use Nooku\Library;

class DatabaseRowOfficer extends Library\DatabaseRowTable
{
    public function __get($column)
    {
        if($column == 'title' && !isset($this->_data['title'])) {
            $this->_data['title'] = $this->firstname.' '.$this->lastname;
        }

        if($column == 'params' && !is_array($this->_data['params'])) {
            $this->_data['params'] = $this->getObject('com:districts.database.row.officer')
                ->setData(json_decode($this->_data['params'], true));
        }

        return parent::__get($column);
    }
}

Update Nooku Framework, using the row object to get params data


<?php
require_once 'MdCompile.php';
define ('ACTION', $_POST['_action']);
switch (ACTION) {
	case 'get':
		echo json_encode(
			array (
				'markdown' => file_get_contents('../courses/Markdown/'.$_POST['name'].'.md'),
				'html' => file_get_contents('../courses/HTML/'.$_POST['name'].'.html')
			)
		);
		break;

	case 'create':
		$compiled = parseMD($_POST['content']);
		file_put_contents('../courses/Markdown/'.$_POST['name'].'.md', $_POST['content']);
		file_put_contents('../courses/HTML/'.$_POST['name'].'.html', '<!doctype html><title>'.$_POST['name'].' - CollegeEditor</title><meta charset="utf-8" />'.$compiled.'');
		echo json_encode(
			array (
				'compiled' => $compiled
			)
		);
		break;

	case 'delete':
		unlink('../courses/Markdown/'.$_POST['name'].'.md');
		break;

	default:
		header('HTTP/1.1 403 Forbidden');
		exit();
		break;
}
?>

Add font family in finals HTML documents


<?php
$discussion = $document->data;
$postsCount = count($discussion->relationships->posts->data);
?>

{{ $discussion->attributes->title }}

        @foreach ($posts as $post)

                <?php $user = $getResource($post->relationships->user->data); ?>

{{ $user ? $user->attributes->username : $translator->trans('core.lib.username.deleted_text') }}

                    {!! $post->attributes->contentHtml !!}

        @endforeach

    @if ($page > 1)
         $page - 1]) }}">« {{ $translator->trans('core.views.discussion.previous_page_button') }}
    @endif

    @if ($page < $postsCount / 20)
         $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} »
    @endif

<?php
$discussion = $document->data;
$postsCount = count($discussion->relationships->posts->data);
?>

{{ $discussion->attributes->title }}

        @foreach ($posts as $post)

                <?php $user = ! empty($post->relationships->user->data) ? $getResource($post->relationships->user->data) : null; ?>

{{ $user ? $user->attributes->username : $translator->trans('core.lib.username.deleted_text') }}

                    {!! $post->attributes->contentHtml !!}

        @endforeach

    @if ($page > 1)
         $page - 1]) }}">« {{ $translator->trans('core.views.discussion.previous_page_button') }}
    @endif

    @if ($page < $postsCount / 20)
         $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} »
    @endif

Fix crash when post's user has been deleted


<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {

	/**
 	 * Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
 	 * This command migrates extended models to the new namespace.
 	 */
	public function migrateGarpModels() {
		$modelDir = APPLICATION_PATH . '/modules/default/Model';
		$dirIterator = new DirectoryIterator($modelDir);
		foreach ($dirIterator as $finfo) {
			if ($finfo->isDot()) {
				continue;
			}
			$this->_modifyModelFile($finfo);
		}
	}

	protected function _modifyModelFile($finfo) {
		$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
		$contents = file_get_contents($path);
		if (strpos($contents, 'extends G_Model_') === false) {
			return;
		}
		$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
		return file_put_contents($path, $contents);
	}
}

<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {

	/**
 	 * Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
 	 * This command migrates extended models to the new namespace.
 	 */
	public function migrateGarpModels() {
		$modelDir = APPLICATION_PATH . '/modules/default/Model';
		$dirIterator = new DirectoryIterator($modelDir);
		foreach ($dirIterator as $finfo) {
			if ($finfo->isDot()) {
				continue;
			}
			$this->_modifyModelFile($finfo);
		}

		$this->_updateCropTemplateRefs();
	}

	// Change references to G_Model_CropTemplate
	protected function _updateCropTemplateRefs() {
		$iniPaths = ['/configs/content.ini', '/configs/acl.ini'];
		foreach ($iniPaths as $i => $path) {
			$content = file_get_contents(APPLICATION_PATH . $path);
			$content = str_replace('G_Model_CropTemplate', 'Garp_Model_Db_CropTemplate', $content);
			file_put_contents(APPLICATION_PATH . $path, $content);
		}
	}

	protected function _modifyModelFile($finfo) {
		$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
		$contents = file_get_contents($path);
		if (strpos($contents, 'extends G_Model_') === false) {
			return;
		}
		$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
		return file_put_contents($path, $contents);
	}
}

Migrate script now also updates CropTemplate


<?php
    namespace SamBenne\Execute;

    /**
     * Class Timer
     * @package Execute
     */
    class Timer
    {
        /**
         * @var \SamBenne\Execute\Timer|null
         */
        protected static $instance = null;

        /**
         * @var array $timers
         */
        private static $timers = [];

        public static function getInstance()
        {
            if (!isset(static::$instance)) {
                static::$instance = new static();
            }

            return static::$instance;
        }

        /**
         * Start Timer
         *
         * @param string $id
         */
        public static function start( $id )
        {
            self::$timers[$id] = [ 'start' => microtime(TRUE) ];
        }

        /**
         * Stop Timer
         *
         * @param string $id
         */
        public static function stop( $id )
        {
            self::$timers[$id]['stop'] = microtime(TRUE);
        }

        /**
         * Output Time
         *
         * This will call self::stop
         *
         * @param string $id
         *
         * @return string
         */
        public static function output( $id )
        {
            self::stop($id);
            $timer = self::$timers[$id];

            $executionTime = ($timer['stop'] - $timer['start']);

            return '<b>Total Execution Time:</b> '.$executionTime.' Secs';
        }
    }

<?php
    namespace SamBenne\Execute;

    /**
     * Class Timer
     * @package Execute
     */
    class Timer
    {
        /**
         * @var \SamBenne\Execute\Timer|null
         */
        protected static $instance = null;

        /**
         * @var array $timers
         */
        private static $timers = [];

        public static function getInstance()
        {
            if (!isset(static::$instance)) {
                static::$instance = new static();
            }

            return static::$instance;
        }

        /**
         * Start Timer
         *
         * @param string $id
         */
        public static function start( $id = "default")
        {
            self::$timers[$id] = [ 'start' => microtime(TRUE) ];
        }

        /**
         * Stop Timer
         *
         * @param string $id
         */
        public static function stop( $id = "default")
        {
            self::$timers[$id]['stop'] = microtime(TRUE);
        }

        /**
         * Output Time
         *
         * This will call self::stop
         *
         * @param string $id
         *
         * @return string
         */
        public static function output( $id = "default")
        {
            self::stop($id);
            $timer = self::$timers[$id];

            $executionTime = ($timer['stop'] - $timer['start']);

            return '<b>Total Execution Time:</b> '.$executionTime.' Secs';
        }
    }

Apply a default timer name

Apply a default timer name


<?php
namespace wcf\acp\action;
use wcf\action\AbstractSecureAction;
use wcf\system\request\LinkHandler;
use wcf\system\WCF;
use wcf\util\HeaderUtil;

/**
 * Does the user logout in the admin control panel.
 *
 * @author	Marcel Werk
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Acp\Action
 */
class LogoutAction extends AbstractSecureAction {
	/**
	 * @inheritDoc
	 */
	public $loginRequired = true;

	/**
	 * @inheritDoc
	 */
	public function execute() {
		parent::execute();

		// do logout
		WCF::getSession()->delete();

		$this->executed();

		// forward to index page
		// warning: if doLogout() writes a cookie this is buggy in MS IIS
		HeaderUtil::redirect(LinkHandler::getInstance()->getLink('Login'));
		exit;
	}
}

<?php
namespace wcf\acp\action;
use wcf\action\AbstractSecureAction;
use wcf\system\request\LinkHandler;
use wcf\system\WCF;
use wcf\util\HeaderUtil;

/**
 * Does the user logout in the admin control panel.
 *
 * @author	Tim Duesterhus, Marcel Werk
 * @copyright	2001-2021 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Acp\Action
 */
class LogoutAction extends AbstractSecureAction {
	/**
	 * @inheritDoc
	 */
	public $loginRequired = true;

	/**
	 * @inheritDoc
	 */
	public function execute() {
		parent::execute();

		// do logout
		WCF::getSession()->clearReauthentication();

		$this->executed();

		HeaderUtil::redirect(LinkHandler::getInstance()->getLink(null, [
			'forceFrontend' => true,
		]));
		exit;
	}
}

Clear reauthentication in ACP logout

Clear reauthentication in ACP logout

This will kill access to the ACP without invalidating the frontend session. By
redirecting to the frontend the user can easily perform a full logout.


<?php
namespace Neos\Flow\Http;

/**
 * A Flow specific uploaded file.
 */
class FlowUploadedFile extends UploadedFile
{
    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     *
     * @var array|string
     */
    protected $originallySubmittedResource;

    /**
     * @var string
     */
    protected $collectionName;

    /**
     * @return array|string
     */
    public function getOriginallySubmittedResource()
    {
        return $this->originallySubmittedResource;
    }

    /**
     * Sets a previously submitted resource reference.
     *
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @param array|string $originallySubmittedResource
     */
    public function setOriginallySubmittedResource($originallySubmittedResource)
    {
        $this->originallySubmittedResource = $originallySubmittedResource;
    }

    /**
     * @return string
     */
    public function getCollectionName()
    {
        return $this->collectionName;
    }

    /**
     * @param string $collectionName
     */
    public function setCollectionName($collectionName)
    {
        $this->collectionName = $collectionName;
    }
}

<?php
namespace Neos\Flow\Http;

/**
 * A Flow specific uploaded file.
 */
class FlowUploadedFile extends UploadedFile
{
    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @var array|string
     */
    protected $originallySubmittedResource;

    /**
     * @var string
     */
    protected $collectionName;

    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @return array|string
     */
    public function getOriginallySubmittedResource()
    {
        return $this->originallySubmittedResource;
    }

    /**
     * Sets a previously submitted resource reference.
     *
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @param array|string $originallySubmittedResource
     */
    public function setOriginallySubmittedResource($originallySubmittedResource)
    {
        $this->originallySubmittedResource = $originallySubmittedResource;
    }

    /**
     * @return string
     */
    public function getCollectionName()
    {
        return $this->collectionName;
    }

    /**
     * @param string $collectionName
     */
    public function setCollectionName($collectionName)
    {
        $this->collectionName = $collectionName;
    }
}

Add a missing method description

TASK: Add a missing method description


<?php
	puff_hook('post-content');
	puff_hook('sidebar');
	puff_hook('footer');
?>
</body>
</html><?php puff_hook('endload'); ?>

Remove closing PHP tag at end of file

Remove closing PHP tag at end of file


<?php

require_once(dirname(__FILE__).'/../bootstrap/common.php');
sfContext::createInstance($configuration);

$t = new lime_test(0);

$t->comment("Création d'une génération");
$date = "99998877665544";

$doc = GenerationClient::getInstance()->find("GENERATION-TEST-".$date);
if($doc) { $doc->delete; }
$doc = GenerationClient::getInstance()->find("GENERATION-TEST-".$date."-TESTSOUSGENERATION");
if($doc) { $doc->delete; }
$doc = GenerationClient::getInstance()->find("GENERATION-TEST-".$date."-TESTSOUSGENERATION2");
if($doc) { $doc->delete; }

$generation = new Generation();
$generation->date_emission = $date;
$generation->type_document = "TEST";
$generation->constructId();
$generation->save();

$t->is($generation->_id, "GENERATION-TEST-".$date, "id de la génération");

$sousSeneration1 = $generation->getOrCreateSubGeneration("TESTSOUSGENERATION");
$sousSeneration1->save();
$sousSeneration2 = $generation->getOrCreateSubGeneration("TESTSOUSGENERATION2");
$sousSeneration2->save();

$t->is($sousSeneration->_id, $generation->_id."-TESTSOUSGENERATION", "id de la sous génération");
$t->is($sousSeneration->getMasterGeneration()->id, $generation->_id, "Récupération de la génération maitre");
$t->is(count($generation->getSubGenerations()), 2, "Récupération des sous générations");

Test de la sous génération

Test de la sous génération


<?php namespace App\Http\Controllers;

use App\Jobs\UpdateLiveCopy;
use App\Jobs\UpdateVersionHashes;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;

class HooksController extends Controller
{
  use DispatchesJobs;

  public function specChange(Request $request)
  {
    // GitHub update hook, load new version hashes
    $json = json_decode($request->input('payload'), true);

    switch ($request->header('x-github-event'))
    {
      case 'pull_request': break;
      case 'push':
        // just initiate spec and version updates
        $this->dispatch(new UpdateLiveCopy());
        $this->dispatch(new UpdateVersionHashes());
        break;

      case 'ping':
      default:
        return response()->json(['result' => Inspiring::quote()]);
    }
  }

  public function addVersion()
  {
    // Buildkite build finish hook, receive a packed fully built version
  }
}

<?php namespace App\Http\Controllers;

use App\Jobs\UpdateLiveCopy;
use App\Jobs\UpdateVersionHashes;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;

class HooksController extends Controller
{
  use DispatchesJobs;

  public function specChange(Request $request)
  {
    switch ($request->header('x-github-event'))
    {
      case 'pull_request':
        // update jobs are only necessary on PR merges
        $json = json_decode($request->input('payload'), true);

        if ($json['action'] == 'closed' && $json['merged'])
        {
          $this->dispatch(new UpdateLiveCopy());
          $this->dispatch(new UpdateVersionHashes());
        }
        break;

      case 'push':
        // just initiate spec and version updates
        $this->dispatch(new UpdateLiveCopy());
        $this->dispatch(new UpdateVersionHashes());
        break;

      case 'ping':
      default:
        return response()->json(['result' => Inspiring::quote()]);
    }
  }

  public function addVersion()
  {
    // Buildkite build finish hook, receive a packed fully built version
  }
}

Add PR merge hook handling.

Add PR merge hook handling.


<?php

namespace App\Http\Middleware;

use Closure;
use App\IpBlacklist;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        $blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();

        if (empty($blacklist)) {
            return $next($request);
        }

        abort(503);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;

use App\IpBlacklist;
use Log;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        $blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();

        if (empty($blacklist)) {
            return $next($request);
        }

        Log::Error(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason));
        abort(503);
    }
}

Add logging whenever someone triggers the IP blacklist


<?php

namespace Moip\Tests;

use Moip\Tests\MoipTestCase;

/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{

}

<?php

namespace Moip\Tests;

use Moip\Tests\MoipTestCase;

/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{
	/**
	 * Test if endpoint production is valid.
	 */
	public function testShouldReceiveEndpointProductionIsValid()
	{
		$endpoint_production = 'api.moip.com.br';
		$const_endpoint_production = constant('\Moip\Moip::ENDPOINT_PRODUCTION');

		$this->assertEquals($endpoint_production, $const_endpoint_production);
	}
}

Test if endpoint production is valid

Test if endpoint production is valid


<?php if ($manga->completed === '1'): ?>
    completed
<?php endif; ?>
<?php if ((int)$manga->rankings < 100 && $manga->rankings != '0'): ?>
    hot
<?php endif; ?>
<?php if (time()-(int)$manga->added_at < 604800): ?>
    new
<?php elseif (time()-(int)$manga->update_at < 604800): ?>
    updated
<?php endif; ?>

Remove tag completed for now

Remove tag completed for now


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observation;
use mcordingley\Regression\Observations;

final class Stochastic extends GradientDescent
{
    /** @var array */
    private $shuffled;

    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $observation = $this->getObservation($observations);

        return $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());
    }

    /**
     * @param Observations $observations
     * @return Observation
     */
    private function getObservation(Observations $observations)
    {
        if (!$this->shuffled) {
            $this->shuffled = range(0, count($observations) - 1);
            shuffle($this->shuffled);
        }

        return $observations->getObservation(array_pop($this->shuffled));
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observations;

final class Stochastic extends GradientDescent
{
    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $observation = $observations->getObservation(mt_rand(0, count($observations) - 1));

        return $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());
    }
}

Simplify back down to simply getting a single random element.


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class DefaultNamingStrategy implements NamingStrategyInterface
{
    /**
     * {@inheritdoc}
     */
    public function fixtureName(ClassMetadata $metadata)
    {
        return ClassUtils::getClassName($metadata->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function modelName($model, ClassMetadata $metadata)
    {
        $identifiers = $metadata->getIdentifierValues($model);
        $className = lcfirst(ClassUtils::getClassName($metadata->getName()));

        return $className . implode('_', $identifiers);
    }

}

<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class DefaultNamingStrategy implements NamingStrategyInterface
{
    /**
     * {@inheritdoc}
     */
    public function fixtureName(ClassMetadata $metadata)
    {
        return ClassUtils::getClassName($metadata->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function modelName($model, ClassMetadata $metadata)
    {
        $identifiers = $metadata->getIdentifierValues($model);
        $className = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst(ClassUtils::getClassName($metadata->getName()))));

        return $className . ($identifiers ? '_' : '') . implode('_', $identifiers);
    }
}

Change default naming strating to use fixture name with underscore


<?php

namespace Tests\AppBundle\API\Details;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;

class OrganismTest extends WebTestCase
{

    public function testExecute()
    {
        $client = static::createClient();
        $default_db = $client->getContainer()->getParameter('default_db');
        $session = null;
        $organisms = $client->getContainer()->get('app.api.webservice')->factory('details', 'organism');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "organism_id" => 42,
            "scientific_name" => "Artocarpus pithecogallus",
            "rank" => "species",
            "common_name" => null,
            "eol_accession" => "",
            "ncbi_accession" => "1679377"
        );
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace Tests\AppBundle\API\Details;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OrganismTest extends WebserviceTestCase
{

    public function testExecute()
    {
        $default_db = $this->default_db;
        $session = null;
        $organisms = $this->webservice->factory('details', 'organism');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "organism_id" => 42,
            "scientific_name" => "Artocarpus pithecogallus",
            "rank" => "species",
            "common_name" => null,
            "eol_accession" => "",
            "ncbi_accession" => "1679377"
        );
        $this->assertEquals($expected, $results);
    }
}

Use WebserviceTestCase as parent for details organism test


<?php

namespace Tests\AppBundle\API\Listing;

use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OverviewTest extends WebserviceTestCase
{
    const NICKNAME = 'listingOverviewTestUser';
    const USERID = 'listingOverviewTestUser';
    const PROVIDER = 'listingOverviewTestUser';

    public function testExecute()
    {
        //Test for overview if user is not logged in
        $default_db = $this->default_db;
        $overview = $this->webservice->factory('listing', 'overview');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db));
        $results = $overview->execute($parameterBag, null);
        $expected = array(
            "projects" => 0,
            "organisms" => 198102,
            "trait_entries" => 91494,
            "trait_types" => 7
        );
        $this->assertEquals($expected, $results);

        //Test of correct project if the user has only one project
        $this->user = new FennecUser(OverviewTest::USERID,OverviewTest::NICKNAME,OverviewTest::PROVIDER);
        $results = $overview->execute($parameterBag, $this->user);
        $expected['projects'] = 1;
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace Tests\AppBundle\API\Listing;

use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OverviewTest extends WebserviceTestCase
{
    const NICKNAME = 'listingOverviewTestUser';
    const USERID = 'listingOverviewTestUser';
    const PROVIDER = 'listingOverviewTestUser';

    public function testExecute()
    {
        //Test for overview if user is not logged in
        $default_db = $this->default_db;
        $overview = $this->webservice->factory('listing', 'overview');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db));
        $results = $overview->execute($parameterBag, null);
        $expected = array(
            "projects" => 0,
            "organisms" => 198102,
            "trait_entries" => 91494+7074,
            "trait_types" => 7
        );
        $this->assertEquals($expected, $results);

        //Test of correct project if the user has only one project
        $this->user = new FennecUser(OverviewTest::USERID,OverviewTest::NICKNAME,OverviewTest::PROVIDER);
        $results = $overview->execute($parameterBag, $this->user);
        $expected['projects'] = 1;
        $this->assertEquals($expected, $results);
    }
}

Update traits overview test and add counts of numerical traits


<?php

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

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

<?php

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

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

Read the https env var as well

Read the https env var as well


<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) 2013 PMG Worldwide
 *
 * @package     PMGQueue
 * @copyright   2013 PMG Worldwide
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue;

/**
 * Producers add jobs to the queue.
 *
 * @since   0.1
 * @author  Christopher Davis <chris@pmg.co>
 */
interface ProducerInterface
{
    /**
     * Add a job to the queue.  Only one argument is required: the job name.
     *
     * @since   0.1
     * @access  public
     * @param   string $name The job name
     * @param   array $args The args to pass to `JobInterface::work` Anything
     *          that's JsonSerializable will work just fine.
     * @throws  PMG\Queue\Exception\AddJobException if something goes wrong
     * @return  boolean True on success
     */
    public function addJob($name, array $args=array());
}

<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) 2013 PMG Worldwide
 *
 * @package     PMGQueue
 * @copyright   2013 PMG Worldwide
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue;

/**
 * Producers add jobs to the queue.
 *
 * @since   0.1
 * @author  Christopher Davis <chris@pmg.co>
 */
interface ProducerInterface
{
    /**
     * Add a job to the queue.  Only one argument is required: the job name.
     *
     * @since   0.1
     * @access  public
     * @param   string $name The job name
     * @param   int $ttr The allowed time for the job to run
     * @param   array $args The args to pass to `JobInterface::work` Anything
     *          that's JsonSerializable will work just fine.
     * @throws  PMG\Queue\Exception\AddJobException if something goes wrong
     * @return  boolean True on success
     */
    public function addJob($name, $ttr, array $args=array());
}

Add ttr to product interface

Add ttr to product interface


<?php

namespace Oro\Bundle\ImportExportBundle\Tests\Unit\Strategy\Stub;

class ImportEntity
{
    /**
     * @var int
     */
    protected $id;

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

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }
}

<?php

namespace Oro\Bundle\ImportExportBundle\Tests\Unit\Strategy\Stub;

class ImportEntity
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var
     */
    protected $twitter;

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

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getTwitter()
    {
        return $this->twitter;
    }

    /**
     * @param mixed $twitter
     */
    public function setTwitter($twitter)
    {
        $this->twitter = $twitter;
    }
}

BAP-4343: Refactor Contact AddOrReplace strategy to support new strategy logic
- remove excess implementation
- refactor contact normalizer
- update social url formatter


<?php namespace Illuminate\Queue\Console;

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

class RetryCommand extends Command {

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

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Retry a failed queue job';

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$failed = $this->laravel['queue.failer']->find($this->argument('id'));

		if ( ! is_null($failed))
		{
			$this->laravel['queue']->connection($failed->connection)->pushRaw($failed->payload, $failed->queue);

			$this->laravel['queue.failer']->forget($failed->id);

			$this->info('The failed job has been pushed back onto the queue!');
		}
		else
		{
			$this->error('No failed job matches the given ID.');
		}
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
			array('id', InputArgument::REQUIRED, 'The ID of the failed job'),
		);
	}

}

<?php namespace Illuminate\Queue\Console;

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

class RetryCommand extends Command {

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

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Retry a failed queue job';

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$failed = $this->laravel['queue.failer']->find($this->argument('id'));

		if ( ! is_null($failed))
		{
			$failed->payload = $this->resetAttempts($failed->payload);

			$this->laravel['queue']->connection($failed->connection)->pushRaw($failed->payload, $failed->queue);

			$this->laravel['queue.failer']->forget($failed->id);

			$this->info('The failed job has been pushed back onto the queue!');
		}
		else
		{
			$this->error('No failed job matches the given ID.');
		}
	}

	/**
	 * Reset the payload attempts.
	 *
	 * @param  string  $payload
	 * @return string
	 */
	protected function resetAttempts($payload)
	{
		$payload = json_decode($payload, true);

		if (isset($payload['attempts'])) $payload['attempts'] = 0;

		return json_encode($payload);
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
			array('id', InputArgument::REQUIRED, 'The ID of the failed job'),
		);
	}

}

Fix job retry bug with attempts.

Fix job retry bug with attempts.


<?php
/*
 * This file is part of prooph/link.
 * (c) 2014-2015 prooph software GmbH <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 4/4/15 - 4:39 PM
 */
namespace Prooph\Link\ProcessManager\Projection\Workflow;

use Doctrine\DBAL\Connection;
use Prooph\Link\Application\Service\ApplicationDbAware;
use Prooph\Link\ProcessManager\Model\Workflow\WorkflowWasCreated;

/**
 * Class WorkflowProjector
 *
 * @package Prooph\Link\ProcessManager\Projection\Workflow
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class WorkflowProjector implements ApplicationDbAware
{
    /**
     * @var Connection
     */
    private $connection;

    /**
     * @var string
     */
    private $workflowTable = "link_pm_read_workflow";

    /**
     * @param WorkflowWasCreated $event
     */
    public function onWorkflowWasCreated(WorkflowWasCreated $event)
    {
        $this->connection->insert($this->workflowTable, [
            'uuid' => $event->workflowId()->toString(),
            'name' => $event->workflowName()
        ]);
    }

    /**
     * @param Connection $connection
     * @return mixed
     */
    public function setApplicationDb(Connection $connection)
    {
        $this->connection = $connection;
    }
}

<?php
/*
 * This file is part of prooph/link.
 * (c) 2014-2015 prooph software GmbH <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 4/4/15 - 4:39 PM
 */
namespace Prooph\Link\ProcessManager\Projection\Workflow;

use Doctrine\DBAL\Connection;
use Prooph\Link\Application\Service\ApplicationDbAware;
use Prooph\Link\ProcessManager\Model\Workflow\WorkflowWasCreated;

/**
 * Class WorkflowProjector
 *
 * @package Prooph\Link\ProcessManager\Projection\Workflow
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class WorkflowProjector implements ApplicationDbAware
{
    /**
     * @var Connection
     */
    private $connection;

    /**
     * @var string
     */
    private $workflowTable = "link_pm_read_workflow";

    /**
     * @param WorkflowWasCreated $event
     */
    public function onWorkflowWasCreated(WorkflowWasCreated $event)
    {
        $this->connection->insert($this->workflowTable, [
            'uuid' => $event->workflowId()->toString(),
            'name' => $event->workflowName(),
            'node_name' => $event->processingNodeName()->toString()
        ]);
    }

    /**
     * @param Connection $connection
     * @return mixed
     */
    public function setApplicationDb(Connection $connection)
    {
        $this->connection = $connection;
    }
}

Store node name for workflow

Store node name for workflow


<?php

namespace App\Handlers\Events;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;

class SendBookingNotification
{
    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewBooking  $event
     * @return void
     */
    public function handle(NewBooking $event)
    {
        Log::info('Handle NewBooking.SendBookingNotification()');
        $locale = App::getLocale();

        $business_name = $event->appointment->business->name;
        Notifynder::category('appointment.reserve')
                   ->from('App\User', $event->user->id)
                   ->to('App\Business', $event->appointment->business->id)
                   ->url('http://localhost')
                   ->extra(compact('business_name'))
                   ->send();

        Mail::send("emails.{$locale}.appointments._new", ['user' => $event->user, 'appointment' => $event->appointment], function ($m) use ($event) {
            $m->to($event->user->email, $event->user->name)->subject(trans('emails.appointment.reserved.subject'));
        });
    }
}

<?php

namespace App\Handlers\Events;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;

class SendBookingNotification
{
    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewBooking  $event
     * @return void
     */
    public function handle(NewBooking $event)
    {
        Log::info('Handle NewBooking.SendBookingNotification()');

        $business_name = $event->appointment->business->name;
        Notifynder::category('appointment.reserve')
                   ->from('App\User', $event->user->id)
                   ->to('App\Business', $event->appointment->business->id)
                   ->url('http://localhost')
                   ->extra(compact('business_name'))
                   ->send();

        $locale = App::getLocale();
        Mail::send("emails.{$locale}.appointments._new", ['user' => $event->user, 'appointment' => $event->appointment], function ($m) use ($event) {
            $m->to($event->user->email, $event->user->name)->subject(trans('emails.appointment.reserved.subject'));
        });
    }
}

Move $locale closer to usage

Move $locale closer to usage


<?php

namespace Common\Doctrine\Entity;

use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;

class CreateSchema
{
    /** @var EntityManager */
    private $entityManager;

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

    /**
     * Adds a new doctrine entity in the database
     *
     * @param string $entityClass
     */
    public function forEntityClass($entityClass)
    {
        $this->forEntityClasses([$entityClass]);
    }

    /**
     * Adds new doctrine entities in the database
     *
     * @param array $entityClasses
     *
     * @throws ToolsException
     */
    public function forEntityClasses(array $entityClasses)
    {
        // create the database table for the given class using the doctrine SchemaTool
        $schemaTool = new SchemaTool($this->entityManager);

        try {
            $schemaTool->createSchema(
                array_map(
                    [$this->entityManager, 'getClassMetadata'],
                    $entityClasses
                )
            );
        } catch (TableExistsException $tableExists) {
            $schemaTool->updateSchema(
                array_map(
                    [$this->entityManager, 'getClassMetadata'],
                    $entityClasses
                )
            );
        } catch (ToolsException $toolsException) {
            if (!$toolsException->getPrevious() instanceof TableExistsException) {
                throw $toolsException;
            }
            $schemaTool->updateSchema(
                array_map(
                    [$this->entityManager, 'getClassMetadata'],
                    $entityClasses
                )
            );
        }
    }
}

<?php

namespace Common\Doctrine\Entity;

use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;

class CreateSchema
{
    /** @var EntityManager */
    private $entityManager;

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

    /**
     * Adds a new doctrine entity in the database
     *
     * @param string $entityClass
     */
    public function forEntityClass($entityClass)
    {
        $this->forEntityClasses([$entityClass]);
    }

    /**
     * Adds new doctrine entities in the database
     *
     * @param array $entityClasses
     *
     * @throws ToolsException
     */
    public function forEntityClasses(array $entityClasses)
    {
        // create the database table for the given class using the doctrine SchemaTool
        $schemaTool = new SchemaTool($this->entityManager);

        try {
            $schemaTool->createSchema(
                array_map(
                    [$this->entityManager, 'getClassMetadata'],
                    $entityClasses
                )
            );
        } catch (TableExistsException $tableExists) {
            // do nothing
        } catch (ToolsException $toolsException) {
            if (!$toolsException->getPrevious() instanceof TableExistsException) {
                throw $toolsException;
            }
            // do nothing
        }
    }
}

Remove updating the schema when it already exists

In some cases (I can't really pinpoint it) it removed all the tables except for those we tried to install


<?php
namespace Imtigger\LaravelCRUD;

use Illuminate\Support\ServiceProvider;

class LaravelCRUDGeneratorServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->commands('Imtigger\LaravelCRUD\Console\Commands\MakeCRUD');
    }

    public function boot()
    {

    }

}

<?php
namespace Imtigger\LaravelCRUD;

use Illuminate\Support\ServiceProvider;

class LaravelCRUDGeneratorServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->commands(\Imtigger\LaravelCRUD\Console\Commands\MakeCRUD::class);
        $this->commands(\Imtigger\LaravelCRUD\Console\Commands\MakeCRUDHeader::class);
        $this->commands(\Imtigger\LaravelCRUD\Console\Commands\MakeCRUDTranslations::class);
    }

    public function boot()
    {

    }

}

Load new commands from service provider

Load new commands from service provider


<?php declare(strict_types=1);

namespace League\Route\Middleware;

use Psr\Http\Server\MiddlewareInterface;

interface MiddlewareAwareInterface
{
    /**
     * Add a middleware to the stack.
     *
     * @param \Psr\Http\Server\MiddlewareInterface $middleware
     *
     * @return self
     */
    public function middleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface;

    /**
     * Add a middleware to the stack.
     *
     * @param \Psr\Http\Server\MiddlewareInterface[] $middlewares
     *
     * @return self
     */
    public function middlewares(array $middlewares) : MiddlewareAwareInterface;

    /**
     * Add a middleware to the stack.
     *
     * @param \Psr\Http\Server\MiddlewareInterface $middleware
     *
     * @return self
     */
    public function prependMiddleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface;

    /**
     * Shift middleware from beginning of stack.
     *
     * @return \Psr\Http\Server\MiddlewareInterface
     */
    public function shiftMiddleware() : MiddlewareInterface;

    /**
     * Get the stack of middleware
     *
     * @return \Psr\Http\Server\MiddlewareInterface[]
     */
    public function getMiddlewareStack() : iterable;
}

<?php declare(strict_types=1);

namespace League\Route\Middleware;

use Psr\Http\Server\MiddlewareInterface;

interface MiddlewareAwareInterface
{
    /**
     * Add a middleware to the stack
     *
     * @param \Psr\Http\Server\MiddlewareInterface $middleware
     *
     * @return static
     */
    public function middleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface;

    /**
     * Add multiple middleware to the stack
     *
     * @param \Psr\Http\Server\MiddlewareInterface[] $middlewares
     *
     * @return static
     */
    public function middlewares(array $middlewares) : MiddlewareAwareInterface;

    /**
     * Prepend a middleware to the stack
     *
     * @param \Psr\Http\Server\MiddlewareInterface $middleware
     *
     * @return static
     */
    public function prependMiddleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface;

    /**
     * Shift a middleware from beginning of stack
     *
     * @return \Psr\Http\Server\MiddlewareInterface|null
     */
    public function shiftMiddleware() : MiddlewareInterface;

    /**
     * Get the stack of middleware
     *
     * @return \Psr\Http\Server\MiddlewareInterface[]
     */
    public function getMiddlewareStack() : iterable;
}

Clean up middleware aware code docs

Clean up middleware aware code docs


<?php
class Json_Api_Wp_Exception extends Exception {
    public $response, $headers;

    public function __construct ( $response ) {
        $this->response = $response["response"];
        $this->headers = $response["headers"];
    }

    public function get_status_code() {
        return $this->response["code"];
    }
}

<?php
class Json_Api_Wp_Exception extends Exception {
    public $response, $headers;

    public function __construct ( $response ) {
        $this->response = $response["response"];
        $this->headers = $response["headers"];
    }

    public function get_status_code() {
        return $this->response["code"];
    }

    public function get_message() {
        return $this->response["message"];
    }
}

Add ability to get response message from exception


<?php

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;

class CanBuildBaseStringTest extends TestCase
{
    private $canBuildBaseStringStub;

    function setUp()
    {
        $this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class);
    }

    /** @test */
    function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
    {
        $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder());
    }

    /** @test */
    function can_build_base_string_trait_can_build_base_string()
    {
        $baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');

        $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $canBuildBaseStringStub);
    }
}

<?php

use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;

class CanBuildBaseStringTest extends TestCase
{
    private $canBuildBaseStringStub;

    function setUp()
    {
        $this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class);
    }

    /** @test */
    function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
    {
        $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder());
    }

    /** @test */
    function can_build_base_string_trait_can_build_base_string()
    {
        $baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');

        $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $baseString);
    }
}

:bug: Fix bug on CanBuildBaseString trait test.


<?php
namespace Concrete\Core\Routing;

use Concrete\Core\Foundation\Service\Provider;

class RoutingServiceProvider extends Provider
{
    /**
     * Registers the services provided by this provider.
     */
    public function register()
    {
        $this->app->singleton(RouterInterface::class);
        $this->app->bind(RouterInterface::class, Router::class);
    }
}

<?php
namespace Concrete\Core\Routing;

use Concrete\Core\Foundation\Service\Provider;

class RoutingServiceProvider extends Provider
{
    /**
     * Registers the services provided by this provider.
     */
    public function register()
    {
        $this->app->singleton(Router::class);
        $this->app->bind(RouterInterface::class, Router::class);
    }
}

Fix router service provider registration

Former-commit-id: 6a27337fce9a24fa084ae85af3e0503a74ac7652
Former-commit-id: d4243ae568bd0efb622f5b0bc3ed196ecbe769ce


<?php

namespace Dusterio\PlainSqs\Integrations;

use Dusterio\PlainSqs\Sqs\Connector;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Queue;
use Illuminate\Queue\Events\JobProcessed;

/**
 * Class CustomQueueServiceProvider
 * @package App\Providers
 */
class LaravelServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('sqs-plain.php')
        ]);

        Queue::after(function (JobProcessed $event) {
            $event->job->delete();
        });
    }

    /**
     * @return void
     */
    public function register()
    {
        $this->app['queue']->addConnector('sqs-plain', function () {
            return new Connector();
        });
    }
}

<?php

namespace Dusterio\PlainSqs\Integrations;

use Dusterio\PlainSqs\Sqs\Connector;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Queue;
use Illuminate\Queue\Events\JobProcessed;

/**
 * Class CustomQueueServiceProvider
 * @package App\Providers
 */
class LaravelServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('sqs-plain.php')
        ]);

        Queue::after(function (JobProcessed $event) {
            $event->job->delete();
        });
    }

    /**
     * @return void
     */
    public function register()
    {
         $this->app->booted(function () {
            $this->app['queue']->extend('sqs-plain', function () {
                return new Connector();
            });
        });
    }
}

Fix queue not found error

Fix queue not found error


<?php

namespace SilverStripe\ContentReview\Extensions;

use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ORM\DataExtension;

/**
 * Description of GroupContentReview.
 */
class ContentReviewOwner extends DataExtension
{
    /**
     * @var array
     */
    private static $many_many = [
        "SiteTreeContentReview" => SiteTree::class,
    ];
}

<?php

namespace SilverStripe\ContentReview\Extensions;

use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\DataExtension;

class ContentReviewOwner extends DataExtension
{
    /**
     * @var array
     */
    private static $many_many = [
        "SiteTreeContentReview" => SiteTree::class,
    ];

    public function updateCMSFields(FieldList $fields)
    {
        // Remove automatically scaffolded GridField in Member CMS fields
        $fields->removeByName('SiteTreeContentReview');
    }
}

FIX Remove automatically scaffolded GridField for Site Tree Content Review in Member fields


<?php

/**
 *
 * @copyright Copyright (c) 2017, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

trait ActorAware {

	/**
	 * @var Actor
	 */
	private $actor;

	/**
	 * @param Actor $actor
	 */
	public function setCurrentActor(Actor $actor) {
		$this->actor = $actor;
	}

}

<?php

/**
 *
 * @copyright Copyright (c) 2017, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

trait ActorAware {

	/**
	 * @var Actor
	 */
	protected $actor;

	/**
	 * @param Actor $actor
	 */
	public function setCurrentActor(Actor $actor) {
		$this->actor = $actor;
	}

}

Allow Context subclasses in acceptance tests to access parent actor

Although uncommon, in some cases a Context may need to be extended (for
example, to override a step defined in the server with a specific
behaviour in the acceptance tests of an app); in those cases the
subclass should be able to access the actor attribute defined in the
Context it is extending.

Signed-off-by: Daniel Calviño Sánchez <bd7629e975cc0e00ea7cda4ab6a120f2ee42ac1b@gmail.com>


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

namespace Darvin\AdminBundle\Security\Configuration;

use Darvin\ConfigBundle\Configuration\ConfigurationInterface;
use Darvin\Utils\Security\SecurableInterface;

/**
 * Security configuration
 */
interface SecurityConfigurationInterface extends ConfigurationInterface, SecurableInterface
{
    /**
     * @return \Darvin\AdminBundle\Security\Permissions\ObjectPermissions[]
     */
    public function getPermissions();
}

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

namespace Darvin\AdminBundle\Security\Configuration;

use Darvin\ConfigBundle\Configuration\ConfigurationInterface;
use Darvin\Utils\Security\SecurableInterface;

/**
 * Security configuration
 */
interface SecurityConfigurationInterface extends ConfigurationInterface, SecurableInterface
{
    /**
     * @return \Darvin\AdminBundle\Security\Permissions\ObjectPermissions[]
     */
    public function getPermissions(): array;
}

Enable strict types in security config interface.