<?php
return array(
		'controllers' => array(
				'invokables' => array(
						'Album\Controller\Album' => 'Album\Controller\AlbumController',
				),
		),
		'router' => array(
				'routes' => array(
						'album' => array(
								'type'    => 'segment',
								'options' => array(
										'route'    => '/album[/][:action][/:id]',
										'constraints' => array(
												'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
												'id'     => '[0-9]+',
										),
										'defaults' => array(
												'controller' => 'Album\Controller\Album',
												'action'     => 'index',
										),
								),
						),
				),
		),
		'view_manager' => array(
				'template_path_stack' => array(
						'album' => __DIR__ . '/../view',
				),
		),
);

<?php
return array(
		'controllers' => array(
				'invokables' => array(
						'Album\Controller\Album' => 'Album\Controller\AlbumController',
				),
		),
		'router' => array(
				'routes' => array(
						'album' => array(
								'type'    => 'segment',
								'options' => array(
										'route'    => '/album[/:action][/:id]',
										'constraints' => array(
												'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
												'id'     => '[0-9]+',
										),
										'defaults' => array(
												'controller' => 'Album\Controller\Album',
												'action'     => 'index',
										),
								),
						),
				),
		),
		'view_manager' => array(
				'template_path_stack' => array(
						'album' => __DIR__ . '/../view',
				),
		),
);

Change the default route of Album to not show / when no action


<?php

declare(strict_types=1);

namespace WoohooLabs\Zen;

use Closure;
use Psr\Container\ContainerInterface;
use WoohooLabs\Zen\Exception\NotFoundException;

use function array_key_exists;

abstract class AbstractCompiledContainer implements ContainerInterface
{
    /** @var array<string, object> */
    protected $singletonEntries = [];
    /** @var array<string, string> */
    protected static array $entryPoints = [];

    /**
     * @param string $id
     */
    public function has($id): bool
    {
        return array_key_exists($id, static::$entryPoints);
    }

    /**
     * @param string $id
     * @return mixed
     * @throws NotFoundException
     */
    public function get($id)
    {
        return $this->singletonEntries[$id] ?? $this->{static::$entryPoints[$id] ?? "throwNotFoundException"}($id);
    }

    /**
     * @return mixed
     */
    protected function throwNotFoundException(string $id)
    {
        throw new NotFoundException($id);
    }

    /**
     * @param object $object
     * @param array<string, mixed> $properties
     * @return object
     */
    protected function setClassProperties($object, $properties)
    {
        Closure::bind(
            static function () use ($object, $properties): void {
                foreach ($properties as $name => $value) {
                    $object->$name = $value;
                }
            },
            null,
            $object
        )->__invoke();

        return $object;
    }
}

<?php

declare(strict_types=1);

namespace WoohooLabs\Zen;

use Closure;
use Psr\Container\ContainerInterface;
use WoohooLabs\Zen\Exception\NotFoundException;

use function array_key_exists;

abstract class AbstractCompiledContainer implements ContainerInterface
{
    /** @var array<string, object> */
    protected array $singletonEntries = [];
    /** @var array<string, string> */
    protected static array $entryPoints = [];

    /**
     * @param string $id
     */
    public function has($id): bool
    {
        return array_key_exists($id, static::$entryPoints);
    }

    /**
     * @param string $id
     * @return mixed
     * @throws NotFoundException
     */
    public function get($id)
    {
        return $this->singletonEntries[$id] ?? $this->{static::$entryPoints[$id] ?? "throwNotFoundException"}($id);
    }

    /**
     * @return mixed
     */
    protected function throwNotFoundException(string $id)
    {
        throw new NotFoundException($id);
    }

    /**
     * @param object $object
     * @param array<string, mixed> $properties
     * @return object
     */
    protected function setClassProperties($object, $properties)
    {
        Closure::bind(
            static function () use ($object, $properties): void {
                foreach ($properties as $name => $value) {
                    $object->$name = $value;
                }
            },
            null,
            $object
        )->__invoke();

        return $object;
    }
}

Add even more property type declaration to the container


<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_top_visited_faqs_info()
{
	return array(
		'name' => tra('Most-Read FAQs'),
		'description' => tra('Displays the specified number of FAQs with links to them, from the most visited one to the least.'),
		'prefs' => array('feature_faqs'),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_top_visited_faqs($mod_reference, $module_params)
{
	global $smarty;

	$faqlib = TikiLib::lib('faq');
	$ranking = $faqlib->list_faqs(0, $mod_reference["rows"], 'hits_desc', '');

	$smarty->assign('modTopVisitedFaqs', $ranking["data"]);
}

<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_top_visited_faqs_info()
{
	return array(
		'name' => tra('Top Visited FAQs'),
		'description' => tra('Display the specified number of FAQs with links to them, from the most visited one to the least.'),
		'prefs' => array('feature_faqs'),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_top_visited_faqs($mod_reference, $module_params)
{
	global $smarty;

	$faqlib = TikiLib::lib('faq');
	$ranking = $faqlib->list_faqs(0, $mod_reference["rows"], 'hits_desc', '');

	$smarty->assign('modTopVisitedFaqs', $ranking["data"]);
}

Tidy up info a little for the PluginModule popup edit form

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40390 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace Bolt\Tests\Nut;

use Bolt\Nut\ExtensionsSetup;
use Bolt\Tests\BoltUnitTest;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class to test Bolt\Nut\ExtensionsSetup class.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class ExtensionsSetupTest extends BoltUnitTest
{
    public function testRun()
    {
        $app = $this->getApp();
        $app['extend.action.options']->set('optimize-autoloader', true);

        $command = new ExtensionsSetup($app);
        $tester = new CommandTester($command);

        $tester->execute([]);
        $result = $tester->getDisplay();

        $this->assertRegExp('/Creating\/updating composer.json… \[DONE\]/', $result);

        $this->assertRegExp('/Updating autoloaders… \[DONE\]/', $result);
        $this->assertRegExp('/Generating optimized autoload files/', $result);
        $this->assertRegExp('/PackageEventListener::dump/', $result);
    }

    public function testRunWithLocal()
    {
        $app = $this->getApp();
        $app['extend.action.options']->set('optimize-autoloader', true);
        $app['filesystem']->createDir('extensions://local');

        $command = new ExtensionsSetup($app);
        $tester = new CommandTester($command);

        $tester->execute([]);
        $result = $tester->getDisplay();

        $app['filesystem']->deleteDir('extensions://local');

        $this->assertRegExp('/Creating\/updating composer.json… \[DONE\]/', $result);

        $this->assertRegExp('/Updating autoloaders… \[DONE\]/', $result);
        $this->assertRegExp('/Generating optimized autoload files/', $result);
        $this->assertRegExp('/PackageEventListener::dump/', $result);
    }
}

<?php

namespace Bolt\Tests\Nut;

use Bolt\Nut\ExtensionsSetup;
use Bolt\Tests\BoltUnitTest;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class to test Bolt\Nut\ExtensionsSetup class.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class ExtensionsSetupTest extends BoltUnitTest
{
    public function testRun()
    {
        $app = $this->getApp();
        $app['extend.action.options']->set('optimize-autoloader', true);

        $command = new ExtensionsSetup($app);
        $tester = new CommandTester($command);

        $tester->execute([]);
        $result = $tester->getDisplay();

        $this->assertRegExp('/Creating\/updating composer.json… \[DONE\]/', $result);

        $this->assertRegExp('/Updating autoloaders… \[DONE\]/', $result);
        $this->assertRegExp('/Generating optimized autoload files/', $result);
        $this->assertRegExp('/PackageEventListener::dump/', $result);
    }
}

Remove left-over local extension test

[Tests] Remove left-over local extension test


<?php

namespace Concrete\Core\Support\Symbol;

use Core;

class MetadataGenerator
{
    public function render()
    {
        $file = '<?php namespace PHPSTORM_META { $STATIC_METHOD_TYPES = array(\\Core::make(\'\') => array(' . PHP_EOL;

        $bindings = Core::getBindings();
        foreach ($bindings as $name => $binding) {
            /** @var \Closure $binding */
            $reflection = new \ReflectionFunction($binding['concrete']);
            $static = $reflection->getStaticVariables();
            $className = null;
            if (!isset($static['concrete'])) {
                try {
                    $class = Core::make($name);
                    $className = get_class($class);
                } catch (\Exception $e) {}
            } else {
                $className = $static['concrete'];
            }

            if ($className !== null && $className !== get_class($this)) {
                if ($className[0] !== '\\') {
                    $className = '\\' . $className;
                }

                $file .= '\'' . $name . '\' instanceof ' . $className . ',' . PHP_EOL;
            }
        }
        $file .= '));}';

        return $file;
    }
}

<?php

namespace Concrete\Core\Support\Symbol;

use Core;

class MetadataGenerator
{
    public function render()
    {
        $file = '<?php namespace PHPSTORM_META { $STATIC_METHOD_TYPES = array(\\Core::make(\'\') => array(' . PHP_EOL;

        $bindings = Core::getBindings();
        foreach ($bindings as $name => $binding) {
            /** @var \Closure $binding */
            $reflection = new \ReflectionFunction($binding['concrete']);
            $static = $reflection->getStaticVariables();
            $className = null;
            if (!isset($static['concrete'])) {
                try {
                    $class = Core::make($name);
                    $className = get_class($class);
                } catch (\Exception $e) {}
            } else {
                $className = $static['concrete'];
            }

            if ($className !== null && $className !== get_class($this)) {
                if ($className[0] !== '\\') {
                    $className = '\\' . $className;
                }

                $file .= '\'' . $name . '\' instanceof ' . $className . ',' . PHP_EOL;
            }
        }

        $file .= '), \Package::getByHandle(\'\') => array(';
        $packages = \Package::getAvailablePackages(false);
        foreach ($packages as $package) {
            /** @var \Package $package */
            $file .= '\'' . $package->getPackageHandle() . '\' instanceof \\' . get_class($package) . ',' . PHP_EOL;
        }

        $file .= '));}';

        return $file;
    }
}

Add phpstorm meta for packages

Add phpstorm meta for packages

Former-commit-id: 2d54f8adf92c1a82f7c3d5a02fd0fd18af88ca26


<?php declare(strict_types=1);

namespace Rector\Console;

use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;

final class Application extends SymfonyApplication
{
    /**
     * @var string
     */
    private const NAME = 'Rector';

    public function __construct()
    {
        parent::__construct(self::NAME, PrettyVersions::getVersion('rector/rector')->getPrettyVersion());
    }

    protected function getDefaultInputDefinition(): InputDefinition
    {
        $defaultInputDefinition = parent::getDefaultInputDefinition();

        $this->removeUnusedOptions($defaultInputDefinition);
        $this->addCustomOptions($defaultInputDefinition);

        return $defaultInputDefinition;
    }

    private function removeUnusedOptions(InputDefinition $inputDefinition): void
    {
        $options = $inputDefinition->getOptions();

        unset($options['quiet'], $options['version'], $options['no-interaction']);

        $inputDefinition->setOptions($options);
    }

    private function addCustomOptions(InputDefinition $inputDefinition): void
    {
        $inputDefinition->addOption(new InputOption(
            'config',
            null,
            InputOption::VALUE_REQUIRED,
            'Path to config file.',
            getcwd() . '/rector.yml'
        ));

        $inputDefinition->addOption(new InputOption(
            'level',
            null,
            InputOption::VALUE_REQUIRED,
            'Finds config by shortcut name.'
        ));
    }
}

<?php declare(strict_types=1);

namespace Rector\Console;

use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;

final class Application extends SymfonyApplication
{
    /**
     * @var string
     */
    private const NAME = 'Rector';

    public function __construct()
    {
        parent::__construct(self::NAME, PrettyVersions::getVersion('rector/rector')->getPrettyVersion());
    }

    protected function getDefaultInputDefinition(): InputDefinition
    {
        $defaultInputDefinition = parent::getDefaultInputDefinition();

        $this->removeUnusedOptions($defaultInputDefinition);
        $this->addCustomOptions($defaultInputDefinition);

        return $defaultInputDefinition;
    }

    private function removeUnusedOptions(InputDefinition $inputDefinition): void
    {
        $options = $inputDefinition->getOptions();

        unset($options['quiet'], $options['version'], $options['no-interaction']);

        $inputDefinition->setOptions($options);
    }

    private function addCustomOptions(InputDefinition $inputDefinition): void
    {
        $inputDefinition->addOption(new InputOption(
            'config',
            'c',
            InputOption::VALUE_REQUIRED,
            'Path to config file.',
            getcwd() . '/rector.yml'
        ));

        $inputDefinition->addOption(new InputOption(
            'level',
            'l',
            InputOption::VALUE_REQUIRED,
            'Finds config by shortcut name.'
        ));
    }
}

Add shortcuts for levels and config

Add shortcuts for levels and config


<?php

namespace SocialiteProviders\Manager;

use SocialiteProviders\Manager\Contracts\ConfigInterface;

trait ConfigTrait
{
    protected $config;

    public function setConfig(ConfigInterface $config)
    {
        $config = $config->get();

        $this->config = $config;
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->redirectUrl = $config['redirect'];

        return $this;
    }

    protected function getConfig($key = null, $default = null)
    {
        return $key ? array_get($this->config, $key, $default) : $this->config;
    }

    public static function additionalConfigKeys()
    {
        return [];
    }
}

<?php

namespace SocialiteProviders\Manager;

use SocialiteProviders\Manager\Contracts\ConfigInterface;

trait ConfigTrait
{
    protected $config;

    public function setConfig(ConfigInterface $config)
    {
        $config = $config->get();

        $this->config = $config;
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->redirectUrl = $config['redirect'];

        return $this;
    }

    protected function getConfig($key = null, $default = null)
    {
        // check manually if a key is given and if it exists in the config
        // this has to be done to check for spoofed additional config keys so that null isn't returned
        if(!empty($key) && empty($this->config[$key])) {
            return $default;
        }

        return $key ? array_get($this->config, $key, $default) : $this->config;
    }

    public static function additionalConfigKeys()
    {
        return [];
    }
}

Check for spoofed additional config keys


<?
require_once('config.inc.php');

function crash($string){
	ob_end_clean();
	die($string);
}

$db_connection = mysqli_connect($db_host,$db_user,$db_passwd, $db_name) or crash('No s\'ha pogut connectar a la BD');

unset($db_host, $db_name, $db_user, $db_passwd);

mysqli_query($db_connection, "SET NAMES 'utf8'") or crash(mysqli_error($db_connection));
mysqli_query($db_connection, "SET CHARACTER SET 'utf8'") or crash(mysqli_error($db_connection));
?>

<?
require_once('config.inc.php');

function crash($string){
	ob_end_clean();
	die($string);
}

$db_connection = mysqli_connect($db_host,$db_user,$db_passwd, $db_name) or crash('No s\'ha pogut connectar a la BD');

unset($db_host, $db_name, $db_user, $db_passwd);

mysqli_set_charset($db_connection, 'utf8') or crash(mysqli_error($db_connection));
?>

Set UTF-8 connection the proper way

Set UTF-8 connection the proper way


<?php

namespace Mapbender\DataSourceBundle\Element\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class DataBaseType
 *
 * @package Mapbender\DataSourceBundle\Element\Type
 * @author  Andriy Oblivantsev <eslider@gmail.com>
 */
class DataBaseType extends AbstractType
{

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        /** Name binding? */
        return "source";
    }

    /**
     * @inheritdoc
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array());
    }

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $fields = array();
        for ($i = 0; $i < rand(3, 12); $i++) {
            $id       = rand(1, 1000);
            $key      = "field" . $id;
            $fields[] = array($key => "Field #" . $id);
        }
        $builder
            ->add('sqlField', 'choice', array(
                    'choices'  => $fields,
                    'required' => true,
                )
            );
    }
}

<?php

namespace Mapbender\DataSourceBundle\Element\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class DataBaseType
 *
 * @package Mapbender\DataSourceBundle\Element\Type
 * @author  Andriy Oblivantsev <eslider@gmail.com>
 */
class DataBaseType extends AbstractType
{

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        /** Name binding? */
        return "source";
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array());
    }

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $fields = array();
        for ($i = 0; $i < rand(3, 12); $i++) {
            $id       = rand(1, 1000);
            $key      = "field" . $id;
            $fields[] = array($key => "Field #" . $id);
        }
        $builder
            ->add('sqlField', 'choice', array(
                    'choices'  => $fields,
                    'required' => true,
                )
            );
    }
}

Update deprecated form type api

Update deprecated form type api


<?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\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    const ANTI_SPAM_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'label'       => false,
            'attr'        => [
                'class' => 'title_field',
            ],
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\TextType';
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'darvin_utils_anti_spam';
    }
}

<?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\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    const ANTI_SPAM_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'label'       => false,
            'attr'        => [
                'class' => 'title_field',
            ],
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\TextType';
    }
}

Remove redundant "getBlockPrefix()" method from child form type classes.


<?php
namespace CfdiUtils\Nodes;

use DOMDocument;
use DOMElement;
use SimpleXMLElement;

class XmlNodeUtils
{
    public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
    {
        return (new XmlNodeExporter($document))->export($node);
    }

    public static function nodeToXmlString(NodeInterface $node, DOMDocument $document = null): string
    {
        $element = static::nodeToXmlElement($node, $document);
        return $element->ownerDocument->saveXML($element);
    }

    public static function nodeToSimpleXmlElement(NodeInterface $node, DOMDocument $document = null): SimpleXMLElement
    {
        $element = static::nodeToXmlElement($node, $document);
        $simpleXmlElement = simplexml_import_dom($element);
        if (false === $simpleXmlElement) {
            throw new \InvalidArgumentException('Cannot convert to SimpleXmlElement');
        }
        return $simpleXmlElement;
    }

    public static function nodeFromXmlElement(DOMElement $element): NodeInterface
    {
        return (new XmlNodeImporter())->import($element);
    }

    public static function nodeFromXmlString(string $content): NodeInterface
    {
        $document = new DOMDocument();
        $document->formatOutput = true;
        $document->preserveWhiteSpace = false;
        $document->loadXML($content);
        return static::nodeFromXmlElement($document->documentElement);
    }

    public static function nodeFromSimpleXmlElement(SimpleXMLElement $element): NodeInterface
    {
        return static::nodeFromXmlString($element->asXML());
    }
}

<?php
namespace CfdiUtils\Nodes;

use DOMDocument;
use DOMElement;
use SimpleXMLElement;

class XmlNodeUtils
{
    public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
    {
        return (new XmlNodeExporter($document))->export($node);
    }

    public static function nodeToXmlString(NodeInterface $node, DOMDocument $document = null): string
    {
        $element = static::nodeToXmlElement($node, $document);
        return $element->ownerDocument->saveXML($element);
    }

    public static function nodeToSimpleXmlElement(NodeInterface $node, DOMDocument $document = null): SimpleXMLElement
    {
        $element = static::nodeToXmlElement($node, $document);
        $simpleXmlElement = simplexml_import_dom($element);
        if (false === $simpleXmlElement) {
            throw new \InvalidArgumentException('Cannot convert to SimpleXmlElement');
        }
        return $simpleXmlElement;
    }

    public static function nodeFromXmlElement(DOMElement $element): NodeInterface
    {
        return (new XmlNodeImporter())->import($element);
    }

    public static function nodeFromXmlString(string $content): NodeInterface
    {
        $document = new DOMDocument();
        $document->formatOutput = true;
        $document->preserveWhiteSpace = false;
        $document->loadXML($content);
        return static::nodeFromXmlElement($document->documentElement);
    }

    public static function nodeFromSimpleXmlElement(SimpleXMLElement $element): NodeInterface
    {
        return static::nodeFromXmlString((string) $element->asXML());
    }
}

Fix SimpleXMLElement::asXML() can also be of type false


<?php

namespace App\Http\Livewire\Files;

use App\Models\File;
use Livewire\Component;
use Livewire\WithFileUploads;

class UploadFileModalForm extends Component
{
    use WithFileUploads;

    /**
     * Determines if the modal should be shown to the user.
     *
     * @var boolean
     */
    public $showModal = false;

    /**
     * The file that should be uploaded.
     *
     * @var mixed
     */
    public $file = null;

    /**
     * Handle state changes when the model is toggled.
     *
     * @param  bool $state
     * @return void
     */
    public function updatedShowModal($state)
    {
        if (!$state) {
            $this->resetErrorBag();
        }
    }

    /**
     * Handles uploading and saving the file.
     *
     * @return
     */
    public function save()
    {
        if ($this->file) {
            $file = File::createAndSave($this->file);

            session()->flash('upload-url', $file->resource_url);
        }

        $this->reset('file');
    }

    /**
     * Render the component.
     *
     * @return \Illuminate\View\View
     */
    public function render()
    {
        return view('files.upload-file-modal-form');
    }
}

<?php

namespace App\Http\Livewire\Files;

use App\Models\File;
use Livewire\Component;
use Livewire\WithFileUploads;

class UploadFileModalForm extends Component
{
    use WithFileUploads;

    /**
     * Determines if the modal should be shown to the user.
     *
     * @var boolean
     */
    public $showModal = false;

    /**
     * The file that should be uploaded.
     *
     * @var mixed
     */
    public $file = null;

    /**
     * Hydrates the component.
     *
     * @return void
     */
    public function hydrate()
    {
        $this->resetErrorBag();
    }

    /**
     * Handle state changes when the model is toggled.
     *
     * @param  bool $state
     * @return void
     */
    public function updatedShowModal($state)
    {
        if (!$state) {
            $this->resetErrorBag();
        }
    }

    /**
     * Handles uploading and saving the file.
     *
     * @return
     */
    public function save()
    {
        $this->resetErrorBag();

        if ($this->file) {
            $file = File::createAndSave($this->file);

            session()->flash('upload-url', $file->resource_url);
        }

        $this->reset('file');
    }

    /**
     * Render the component.
     *
     * @return \Illuminate\View\View
     */
    public function render()
    {
        return view('files.upload-file-modal-form');
    }
}

Reset error bag on file upload hydration

This helps get rid of error messages between file uploads so you don't see an error message if the file was uploaded successfully.


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        // Delete rows with non-existent entities so that we will be able to create
        // foreign keys without any issues.
        $schema->getConnection()
            ->table('post_likes')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id');
            })
            ->orWhereNotExists(function ($query) {
                $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id');
            })
            ->delete();

        $schema->table('post_likes', function (Blueprint $table) {
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('post_likes', function (Blueprint $table) {
            $table->dropForeign(['post_id', 'user_id']);
        });
    }
];

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        // Delete rows with non-existent entities so that we will be able to create
        // foreign keys without any issues.
        $schema->getConnection()
            ->table('post_likes')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id');
            })
            ->orWhereNotExists(function ($query) {
                $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id');
            })
            ->delete();

        $schema->table('post_likes', function (Blueprint $table) use ($schema) {
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('post_likes', function (Blueprint $table) use ($schema) {
            $table->dropForeign(['post_id', 'user_id']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


<?php

namespace app\models;

use Yii;
use app\models\Config;
use yii\console\Application;

class ApplicationConsole extends Application {
	public function __construct($config) {
		parent::__construct($config);

		// Set name from database if not set by config file.
		if (!isset($config['name'])) {
			if (($name = Config::setting('application.name'))) {
				$this->name = $name;
			}
		}

		// Set email from database if not set by config file.
		if (!isset(Yii::$app->params['adminEmail'])) {
			Yii::$app->params['adminEmail'] = null;
			if (($email = Config::setting('application.admin.email'))) {
				Yii::$app->params['adminEmail'] = $email;
			}
		}
	}
}

<?php

namespace app\models;

use Yii;
use app\models\Config;
use yii\console\Application;
use yii\db\Exception as DBException;

class ApplicationConsole extends Application {
	public function __construct($config) {
		parent::__construct($config);

		// If database if unavailable skip settings (initital install).
		try {
			// Set name from database if not set by config file.
			if (!isset($config['name'])) {
				if (($name = Config::setting('application.name'))) {
					$this->name = $name;
				}
			}

			// Set email from database if not set by config file.
			if (!isset(Yii::$app->params['adminEmail'])) {
				Yii::$app->params['adminEmail'] = null;
				if (($email = Config::setting('application.admin.email'))) {
					Yii::$app->params['adminEmail'] = $email;
				}
			}
		}
		catch (DBException $e) {
			// Do nothing.
		}
	}
}

Make console work before initial install.


<?php
/**
 * @package BaseX
 *
 * @copyright Copyright (c) 2012, Alexandors Sigalas
 * @author Alexandros Sigalas <alxarch@gmail.com>
 * @license BSD License
 */
namespace BaseX\Database;

use BaseX\Query\Result\MapperInterface;
use BaseX\Query;
use BaseX\Database;

/**
 * Maps query result data to Backup class.
 *
 * @author alxarch
 */
class BackupProvider implements MapperInterface
{
  /**
   *
   * @var \BaseX\Database
   */
  protected $db;

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

  public function supportsType($type) {
     return $type === Query::TYPE_ELEMENT;
  }

  public function getResult($data, $type) {
    $backup = new Backup();
    $backup->unserialize($data);
    return $backup;
  }

  /**
   * @todo implement date filters.
   */
  public function get()
  {
    $xql = "db:backups('$this->db')";
    return $this->db->getSession()->query($xql)->getResults($this);
  }
}

<?php
/**
 * @package BaseX
 *
 * @copyright Copyright (c) 2012, Alexandors Sigalas
 * @author Alexandros Sigalas <alxarch@gmail.com>
 * @license BSD License
 */
namespace BaseX\Database;

use BaseX\Query\Result\MapperInterface;
use BaseX\Query;
use BaseX\Database;

/**
 * Maps query result data to Backup class.
 *
 * @author alxarch
 */
class BackupProvider implements MapperInterface
{
  /**
   *
   * @var \BaseX\Database
   */
  protected $db;

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

  public function supportsType($type) {
     return $type === Query::TYPE_ELEMENT;
  }

  public function getResult($data, $type) {
    $backup = new Backup();
    $backup->unserialize($data);
    return $backup;
  }

  /**
   * @todo implement date filters.
   */
  public function get()
  {
    $xql = "for \$d in db:backups('$this->db') order by \$d descending return \$d";
    return $this->db->getSession()->query($xql)->getResults($this);
  }
}

Order backups by date descending

Order backups by date descending


<?php

/**
 * This class provides the "Cpatcha" field type
 *
 * @package     Nails
 * @subpackage  module-form-builder
 * @category    Controller
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\FormBuilder\FormBuilder\FieldType;

use Nails\Common\Exception\FactoryException;
use Nails\Common\Exception\ViewNotFoundException;
use Nails\Factory;
use Nails\FormBuilder\FieldType\Base;

/**
 * Class Captcha
 *
 * @package Nails\FormBuilder\FormBuilder\FieldType
 */
class Captcha extends Base
{
    const LABEL             = 'Captcha';
    const SUPPORTS_OPTIONS  = false;
    const SUPPORTS_DEFAULTS = false;
    const IS_SELECTABLE     = false;
    const RENDER_VIEWS      = [
        'formbuilder/fields/open',
        'formbuilder/fields/body-captcha',
        'formbuilder/fields/close',
    ];

    // --------------------------------------------------------------------------

    /**
     * Renders the field's HTML
     *
     * @param array $aConfig The field's data
     *
     * @return string
     * @throws FactoryException
     * @throws ViewNotFoundException
     */
    public function render(array $aConfig): string
    {
        if (empty($aConfig['captcha'])) {
            return '';
        }

        return parent::render($aConfig);
    }
}

<?php

/**
 * This class provides the "Cpatcha" field type
 *
 * @package     Nails
 * @subpackage  module-form-builder
 * @category    Controller
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\FormBuilder\FormBuilder\FieldType;

use Nails\Common\Exception\FactoryException;
use Nails\Common\Exception\ViewNotFoundException;
use Nails\Common\Service\View;
use Nails\Factory;
use Nails\FormBuilder\FieldType\Base;

/**
 * Class Captcha
 *
 * @package Nails\FormBuilder\FormBuilder\FieldType
 */
class Captcha extends Base
{
    const LABEL             = 'Captcha';
    const SUPPORTS_OPTIONS  = false;
    const SUPPORTS_DEFAULTS = false;
    const IS_SELECTABLE     = false;
    const RENDER_VIEWS      = [
        'formbuilder/fields/open',
        'formbuilder/fields/body-captcha',
        'formbuilder/fields/close',
    ];

    // --------------------------------------------------------------------------

    /**
     * Renders the field's HTML
     *
     * @param array $aConfig The field's data
     *
     * @return string
     * @throws FactoryException
     * @throws ViewNotFoundException
     */
    public function render(array $aConfig): string
    {
        if (empty($aConfig['captcha'])) {
            return '';
        }

        $aViews = $aConfig['captcha']->isInvisible()
            ? [
                'formbuilder/fields/body-captcha',
            ]
            : [
                'formbuilder/fields/open',
                'formbuilder/fields/body-captcha',
                'formbuilder/fields/close',
            ];

        /** @var View $oView */
        $oView = Factory::service('View');
        return $oView
            ->load($aViews, $aConfig, true);
    }
}

Add support for invisible captchas

Add support for invisible captchas


<?php

namespace OmnipayAuthorizeNet\Message;

use Omnipay\Common\CreditCard;

/**
 * Authorize.Net AIM Capture Only Request
 */
class AIMCaptureOnlyRequest extends AIMAuthorizeRequest
{
    protected $action = 'captureOnlyTransaction';

    public function getData()
    {
        $data = parent::getData();

        $data->transactionRequest->authCode = $this->getAuthCode();

        return $data;
    }
}

<?php

namespace Omnipay\AuthorizeNet\Message;

use Omnipay\Common\CreditCard;

/**
 * Authorize.Net AIM Capture Only Request
 */
class AIMCaptureOnlyRequest extends AIMAuthorizeRequest
{
    protected $action = 'captureOnlyTransaction';

    public function getData()
    {
        $this->validate('amount');
        $data = $this->getBaseData();
        $data->transactionRequest->amount = $this->getAmount();
        $this->addPayment($data);
        $data->transactionRequest->authCode = $this->getAuthCode();
        $this->addSolutionId($data);
        $this->addBillingData($data);
        $this->addCustomerIP($data);
        $this->addTransactionSettings($data);

        return $data;
           }
}

Update capture only request field order

Update capture only request field order


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

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

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
    'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
    'files' => array('src', 'tests', 'build.php'),
    'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

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

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

echo "Code coverage was 100%\n";

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

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

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
    'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
    'files' => array('src', 'tests', 'build.php'),
    'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

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

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

echo "Code coverage was 100%\n";

Use the full path to the code coverage.

Use the full path to the code coverage.


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

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

require 'vendor/autoload.php';

$phpcsCommand = './vendor/bin/phpcs --standard=' . __DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS -n src tests *.php';
passthru($phpcsCommand, $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

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

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

echo "Code coverage was 100%\n";

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

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

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
    'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
    'files' => array('src', 'tests', 'build.php'),
    'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

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

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

echo "Code coverage was 100%\n";

Convert usage of phpcs to a library.

Convert usage of phpcs to a library.


#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

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

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

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

file_put_contents('php://stderr', "Code coverage was 100%\n");

#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

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

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

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

file_put_contents('php://stderr', "Code coverage was 100%\n");

Add bin to the phpcs path.

Add bin to the phpcs path.


<?php

namespace Core\LayoutBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('CoreLayoutBundle:Default:index.html.twig');
    }

    public function getUrlAction()
    {
        $urlHelper = $this->container->get('url_helper');
        $url = $this->container->get('request_stack')->getMasterRequest()->get('url');

        $result = $urlHelper->getContentUrl($url);

        if (array_key_exists('error', $result) && $result['error']) {
            print($result['error']);
            exit();
        }

        if (array_key_exists('header', $result)
            && is_array($result['header'])
            && !empty($result['header'])
        ) {
            foreach ($result['header'] as $header) {
                header($header);
            }
        }

        print($result['content']);
        exit();
    }
}

<?php

namespace Core\LayoutBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('CoreLayoutBundle:Default:index.html.twig');
    }

    public function getUrlAction()
    {
        $urlHelper = $this->container->get('url_helper');
        $url = $this->container->get('request_stack')->getMasterRequest()->get('url');

        $result = $urlHelper->getContentUrl($url);

        $response = new Response();

        if (array_key_exists('error', $result) && $result['error']) {
            $response->setContent($result['error']);
        }
        else {
            $response->setContent($result['content']);
            if (array_key_exists('header', $result)
                && is_array($result['header'])
                && !empty($result['header'])
            ) {
                $response->headers->add($result['header']);
            }

        }

        return $response;
    }
}

Adjust to return Response object

Adjust to return Response object


<?php

namespace App\Transformers;

use League\Fractal\TransformerAbstract;
use App\Entities\Game;

/**
 * Class GameTransformer
 * @package namespace App\Transformers;
 */
class GameTransformer extends TransformerAbstract
{
	/**
     * List of resources possible to include
     *
     * @var array
     */
    protected $availableIncludes = [
        'database',
    ];

    /**
     * Transform the \Game entity
     * @param \Game $model
     *
     * @return array
     */
    public function transform(Game $model)
    {
        return array_filter([
            'id'         => isset($model->id)         ? (int) $model->id                      : null,
			'database_id'=> isset($model->database_id) ? $model->database_id                  : null,
			'jcf'        => isset($model->game)       ? $model->game->getJCF()                : null,
            'created_at' => isset($model->created_at) ? $model->created_at->toIso8601String() : null,
            'updated_at' => isset($model->updated_at) ? $model->updated_at->toIso8601String() : null
        ]);
    }

	/**
	 * Include Database
	 *
	 * @param Game $game
	 * @return League\Fractal\ItemResource
	 */
	public function includeDatabase(Game $game)
	{
		return $this->item($game->database, new DatabaseTransformer);
	}
}

<?php

namespace App\Transformers;

use League\Fractal\TransformerAbstract;
use App\Entities\Game;

/**
 * Class GameTransformer
 * @package namespace App\Transformers;
 */
class GameTransformer extends TransformerAbstract
{
	/**
     * List of resources possible to include
     *
     * @var array
     */
    protected $availableIncludes = [
        'database',
    ];

    /**
     * Transform the \Game entity
     * @param \Game $model
     *
     * @return array
     */
    public function transform(Game $model)
    {
        return array_filter([
            'id'         => isset($model->id)         ? (int) $model->id                      : null,
			'database_id'=> isset($model->database_id) ? $model->database_id                  : null,
			'jcf'        => isset($model->game)       ? $model->game->jsonSerialize()         : null,
            'created_at' => isset($model->created_at) ? $model->created_at->toIso8601String() : null,
            'updated_at' => isset($model->updated_at) ? $model->updated_at->toIso8601String() : null
        ]);
    }

	/**
	 * Include Database
	 *
	 * @param Game $game
	 * @return League\Fractal\ItemResource
	 */
	public function includeDatabase(Game $game)
	{
		return $this->item($game->database, new DatabaseTransformer);
	}
}

Return JCF as JSON object instead of string


#!/usr/local/bin/php -f

<?php

echo "Starting the pfSense shell system";

echo ".";
require("globals.inc");
$g['booting'] = true;
require("functions.inc");
echo ".";
require("config.inc");
echo ".";
$g['booting'] = false;

$fp = fopen('php://stdin', 'r');

echo ".\n\n";

$shell_active = true;

echo "Example commands:\n\n";
echo "    print_r(\$config);\n";
echo "    \$config['interfaces']['lan']['ipaddr'] = \"192.168.1.1\";\n";
echo "    write_config();\n";
echo "    exit\n";

while($shell_active == true) {
        echo "\n\npfSense shell> ";
        $command = chop(fgets($fp));
        if($command == "exit") {
                $shell_active = false;
                echo "\n";
                break;
		}
        eval($command);
}

#!/usr/local/bin/php -f

<?php

echo "Starting the pfSense shell system";

echo ".";
require("globals.inc");
$g['booting'] = true;
require("functions.inc");
echo ".";
require("config.inc");
echo ".";
$g['booting'] = false;

$fp = fopen('php://stdin', 'r');

echo ".\n\n";

$shell_active = true;

echo "Example commands:\n\n";
echo "    print_r(\$config);\n";
echo "    \$config['interfaces']['lan']['ipaddr'] = \"192.168.1.1\";\n";
echo "    write_config();\n";
echo "    multiline\n";
echo "    exit";

while($shell_active == true) {
        echo "\n\npfSense shell> ";
        $command = chop(fgets($fp));
        if($command == "exit") {
                $shell_active = false;
                echo "\n";
                break;
		}
		if($command == "multiline" or $command == "ml") {
			echo "\nmultiline mode enabled.  enter EOF on a blank line to execute.\n\n";
			$command = "";
			$mlcommand = "";
			$xxxyzyz = 0;
			while($command <> "EOF") {
				echo "pfSense multiline shell[$xxxyzyz]> ";
		        $command = chop(fgets($fp));
		        if($command == "exit")
		        	die;
		        if($command <> "EOF")
		        	$mlcommand .= $command;
		        $xxxyzyz++;
			}
			$command = $mlcommand;
		}
		if($command) {
			echo "\n";
	        eval($command);
	    }
}

Add multiline support for multi-line mini programs/scripts.


<?php
class Email {
	public $db = null;
	public $email = '';
	public $from = 'luke@lcahill.co.uk';
	public $subject = 'Note Keeper - please confirm your email.';
	public $message = '';
	public $userId = '';

	function __construct($email, $userId, $db) {
		$this->email = $email;
		$this->userId = $userId;
		$this->db = $db;
	}

	function constructConfirmLink() {
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$confirm = md5($timestamp);

		$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
		$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));

		$url = $_SERVER['SERVER_NAME'];
		$link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId;
		$this->message = 'Please follow this link to confirm your account ' . $link . '';
		$this->sendEmail();
	}

	function sendEmail() {
		mail($this->email, $this->subject, $this->message);
	}
}

?>

<?php
class Email {
	public $db = null;
	public $email = '';
	public $from = 'luke@lcahill.co.uk';
	public $subject = 'Note Keeper - please confirm your email.';
	public $message = '';
	public $userId = '';
	public $headers = 'From: luke@lcahill.co.uk' . "\r\n" . 'Reply-To: luke@lcahill.co.uk' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

	function __construct($email, $userId, $db) {
		$this->email = $email;
		$this->userId = $userId;
		$this->db = $db;
	}

	function constructConfirmLink() {
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$confirm = md5($timestamp);

		$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
		$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));

		$url = $_SERVER['SERVER_NAME'];
		$link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId;
		$this->message = 'Please follow this link to confirm your account ' . $link;
		$this->sendEmail();
	}

	function sendEmail() {
		mail($this->email, $this->subject, $this->message, $this->headers);
	}
}

?>

Add headers and change the email which is generated when registering.


<?php

namespace PhpAbac\Comparison;

class BooleanComparison extends AbstractComparison
{
    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolAnd($expected, $value)
    {
        return $expected && $value;
    }

    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolOr($expected, $value)
    {
        return $expected || $value;
    }

    /**
     * @param mixed $expected
     * @param mixed $value
     */
    public function isNull($expected, $value)
    {
        return $value === null;
    }
}

<?php

namespace PhpAbac\Comparison;

class BooleanComparison extends AbstractComparison
{
    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolAnd($expected, $value)
    {
        return $expected && $value;
    }

    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolOr($expected, $value)
    {
        return $expected || $value;
    }

    /**
     * @param mixed $expected
     * @param mixed $value
     */
    public function isNull($expected, $value)
    {
        return $value === null;
    }

    /**
     * @param mixed $expected
     * @param mixed $value
     */
    public function isNotNull($expected, $value) {
        return $value !== null;
    }
}

Implement comparison method to check if an attribute is not null


<?php

namespace GrooveHQ\Service;

class MailboxesDescription extends BasicServiceDescription
{

    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'mailboxes' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [],
                ],
                'folders' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [
                        'mailbox' => [
                            'description' => 'The ID or email address of a Mailbox to filter by',
                            'type' => 'string',
                            'required' => false,
                            'location' => 'query'
                        ],
                    ],
                ]
            ]
        ];
    }

}

<?php

namespace GrooveHQ\Service;

class MailboxesDescription extends BasicServiceDescription
{

    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'mailboxes' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [],
                ],
                'folders' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/folders',
                    'parameters' => [
                        'mailbox' => [
                            'description' => 'The ID or email address of a Mailbox to filter by',
                            'type' => 'string',
                            'required' => false,
                            'location' => 'query'
                        ],
                    ],
                ]
            ]
        ];
    }

}

Fix typo in folders service description

Fix typo in folders service description


<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;
use CdliTwoStageSignupTest\Framework\TestCase;
use CdliTwoStageSignupTest\Framework\TestCaseOptions;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$serviceManager->get('ModuleManager')->loadModules();
#$serviceManager->get('Application')->bootstrap();

TestCase::setServiceLocator($serviceManager);

$config = $serviceManager->get('Configuration');
TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));

<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfig;
use CdliTwoStageSignupTest\Framework\TestCase;
use CdliTwoStageSignupTest\Framework\TestCaseOptions;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfig(@$configuration['service_manager'] ?: array()));
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->get('ModuleManager')->loadModules();

TestCase::setServiceLocator($serviceManager);

$config = $serviceManager->get('Configuration');
TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));

Update test bootstrap to work with latest ZF2 master


<?php

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

$testsDir = getenv('WP_TESTS_DIR');
if (!$testsDir) {
    $testsDir = '/tmp/wordpress-tests-lib';
}

require_once "{$testsDir}/includes/functions.php";

tests_add_filter('plugins_loaded', function() {
    require_once __DIR__.'/../wp-tweaks.php';
});
tests_add_filter('muplugins_loaded', function() {
    // Require main mu-plugin files here
});

require_once "{$testsDir}/includes/bootstrap.php";

<?php

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

$testsDir = '/tmp/wordpress-tests-lib';

require_once "{$testsDir}/includes/functions.php";

tests_add_filter('plugins_loaded', function() {
    require_once __DIR__.'/../wp-tweaks.php';
});
tests_add_filter('muplugins_loaded', function() {
    // Require main mu-plugin files here
});

require_once "{$testsDir}/includes/bootstrap.php";

Remove unnecessary temporary directory customizability


<?php

/** @var array $organizationStatistics */

?>

      Organization:
      Manifests:

    <?php

    foreach ($organizationStatistics as $organization => $manifestCount) {
        ?>

            <a href="organizations/<?=$this->e($organization)?>.html"><?=$this->e($organization)?>

              <?=$manifestCount?>

        <?php
    }

    ?>

<?php

/** @var array $organizationStatistics */

?>

      Name:
      Manifests:

    <?php

    foreach ($organizationStatistics as $organization => $manifestCount) {
        ?>

            <a href="organizations/<?=$this->e($organization)?>.html"><?=$this->e($organization)?>

              <?=$manifestCount?>

        <?php
    }

    ?>

Rename "Organization" to "Name" in the manifests table


<?php

namespace Illuminate\Tests\Foundation;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;

class LoadEnvironmentVariablesTest extends TestCase
{
    protected function tearDown(): void
    {
        m::close();
    }

    protected function getAppMock($file)
    {
        $app = m::mock(Application::class);

        $app->shouldReceive('configurationIsCached')
            ->once()->with()->andReturn(false);
        $app->shouldReceive('runningInConsole')
            ->once()->with()->andReturn(false);
        $app->shouldReceive('environmentPath')
            ->once()->with()->andReturn(__DIR__.'/../fixtures');
        $app->shouldReceive('environmentFile')
            ->once()->with()->andReturn($file);

        return $app;
    }

    public function testCanLoad()
    {
        $this->expectOutputString('');

        (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('.env'));

        $this->assertSame('BAR', env('FOO'));
    }

    public function testCanFailSilent()
    {
        $this->expectOutputString('');

        (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('BAD_FILE'));
    }
}

<?php

namespace Illuminate\Tests\Foundation;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;

class LoadEnvironmentVariablesTest extends TestCase
{
    protected function tearDown(): void
    {
        m::close();
    }

    protected function getAppMock($file)
    {
        $app = m::mock(Application::class);

        $app->shouldReceive('configurationIsCached')
            ->once()->with()->andReturn(false);
        $app->shouldReceive('runningInConsole')
            ->once()->with()->andReturn(false);
        $app->shouldReceive('environmentPath')
            ->once()->with()->andReturn(__DIR__.'/../fixtures');
        $app->shouldReceive('environmentFile')
            ->once()->with()->andReturn($file);

        return $app;
    }

    public function testCanLoad()
    {
        $this->expectOutputString('');

        (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('.env'));

        $this->assertSame('BAR', env('FOO'));
        $this->assertSame('BAR', getenv('FOO'));
        $this->assertSame('BAR', $_ENV['FOO']);
        $this->assertSame('BAR', $_SERVER['FOO']);
    }

    public function testCanFailSilent()
    {
        $this->expectOutputString('');

        (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('BAD_FILE'));
    }
}

Test env variables are loaded into $_ENV, $_SERVER, and getenv


<?php namespace Tuxion\DoctrineRest\Responder;

use Aura\Web\Response;
use Tuxion\DoctrineRest\Domain\Result\ResultInterface;

interface ResponderInterface
{

  public function getResult();
  public function getResponse();
  public function setResult(ResultInterface $result);
  public function __construct(Response $response, StatusCodes $statusCodes);
  public function __invoke();

}

<?php namespace Tuxion\DoctrineRest\Responder;

use Aura\Web\Response;
use Tuxion\DoctrineRest\Domain\Result\ResultInterface;

/**
 * An interface to make sure that responders always accept results and can be invoked.
 */
interface ResponderInterface
{

  /**
   * Returns the ResultInterface that holds the final state of the application to communicate to the user.
   * @return ResultInterface
   */
  public function getResult();

  /**
   * Sets the ResultInterface that holds the final state of the application to communicate to the user.
   * @param ResultInterface $result
   * @return void
   */
  public function setResult(ResultInterface $result);

  /**
   * Sets the response on an Aura Response object and returns it.
   * @return Response
   */
  public function __invoke();

}

Remove implementation specific methods from the interface.


<?php
/**
 * Check/resumes the current user's session
 */

require_once __DIR__ . '/../bootstrap.php';

Authenticate();

$result = new Entity(['success'=>'You have been logged in successfully!']);
echo $result->toJSON();

<?php
/**
 * Check/resumes the current user's session
 */

require_once __DIR__ . '/../bootstrap.php';

$person = Person::user();
echo $person->toJSON();

Return person information when resuming a session


<?
include '../scat.php';
include '../lib/item.php';

$vendor= (int)$_REQUEST['vendor'];
if (!$vendor)
  die_jsonp("You need to specify a vendor.");

$sql_criteria= "1=1";
if (($items= $_REQUEST['items'])) {
  list($sql_criteria, $x)= item_terms_to_sql($db, $items, FIND_OR);
}

$q= "UPDATE item
        SET retail_price = (SELECT retail_price
                              FROM vendor_item
                             WHERE vendor_item.item = item.id
                               AND vendor = $vendor
                             LIMIT 1)
     WHERE $sql_criteria";

$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('message' => "Updated items"));

<?
include '../scat.php';
include '../lib/item.php';

$vendor= (int)$_REQUEST['vendor'];
if (!$vendor)
  die_jsonp("You need to specify a vendor.");

$sql_criteria= "1=1";
$items= $_REQUEST['items'];
if (!empty($items)) {
  list($sql_criteria, $x)= item_terms_to_sql($db, $items, FIND_OR);
}

$q= "UPDATE item, vendor_item
        SET item.retail_price = vendor_item.retail_price
     WHERE item.id = vendor_item.item
       AND vendor = $vendor
       AND $sql_criteria";

$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('message' => "Updated items"));

Fix query to handle all items for vendor


<?php
    require_once __DIR__ . "/../class/autoload.php";

    use \html\Page as Page;
    use \html\AdministratorMenu as AdministratorMenu;
    use \html\Forms as Forms;
    use \configuration\Globals as Globals;
    use \utilities\Session as Session;

    Page::header(Globals::ENTERPRISE_NAME);

    $session = new Session();
    $session->verifyIfSessionIsStarted();

    $menu = new AdministratorMenu();
    $menu->construct();
?>

<<<<<<< HEAD

Edição de Página

      <form action="<?php echo PROJECT_ROOT;?>controller/updatePage.php" method="POST">
        <fieldset>
          <?php Forms::updatePageForm($_GET['pages']); ?>
        </fieldset>
        <input type="hidden" value="<?php echo $_GET['pages']?>" id="page_code">
        <input type="button" value="Excluir Imagem" id="delete_image">
        <input type="submit" value="Atualizar">
      </form>

<?php
    Page::footer();
    Page::closeBody();
?>

<?php
    require_once __DIR__ . "/../class/autoload.php";

    use \html\Page as Page;
    use \html\AdministratorMenu as AdministratorMenu;
    use \html\Forms as Forms;
    use \configuration\Globals as Globals;
    use \utilities\Session as Session;

    Page::header(Globals::ENTERPRISE_NAME);

    $session = new Session();
    $session->verifyIfSessionIsStarted();

    $menu = new AdministratorMenu();
    $menu->construct();
?>

<<<<<<< HEAD

Edição de Página

      <form action="<?php echo PROJECT_ROOT;?>controller/updatePage.php" method="POST">
        <fieldset>
          <?php Forms::updatePageForm($_GET['pages']); ?>
        </fieldset>
        <input type="hidden" value="<?php echo $_GET['pages']?>" id="page_code">
        <input type="submit" value="Atualizar">
      </form>

<?php
    Page::footer();
    Page::closeBody();
?>

Remove deleteIamge button and associeted javascript


<?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\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder(): TreeBuilder
    {
        if (method_exists(TreeBuilder::class, 'getRootNode')) {
            $treeBuilder = new TreeBuilder('sylius_admin');
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $treeBuilder = new TreeBuilder();
            $rootNode = $treeBuilder->root('sylius_admin');
        }

        $rootNode
            ->children()
                ->arrayNode('notifications')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('enabled')
                            ->defaultTrue()
                        ->end()
                        ->integerNode('frequency')
                            ->defaultValue(60)
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?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\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder(): TreeBuilder
    {
        $treeBuilder = new TreeBuilder('sylius_admin');
        $rootNode = $treeBuilder->getRootNode();

        $rootNode
            ->children()
                ->arrayNode('notifications')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('enabled')
                            ->defaultTrue()
                        ->end()
                        ->integerNode('frequency')
                            ->defaultValue(60)
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Remove usage of deprecated "Symfony\Component\Config\Definition\Builder\TreeBuilder::root()"


<?php
/**
 * This file is part of the P2SecurityBundle.
 *
 * (c) 2013 Philipp Boes <mostgreedy@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace P2\Bundle\SecurityBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Class Configuration
 * @package P2\Bundle\SecurityBundle\DependencyInjection
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('p2_security');

        $rootNode
            ->children()
                ->scalarNode('manager')->cannotBeEmpty()->end()
                ->scalarNode('encoder')->defaultValue('sha256')->end()
            ->end();

        return $treeBuilder;
    }
}

<?php
/**
 * This file is part of the P2SecurityBundle.
 *
 * (c) 2013 Philipp Boes <mostgreedy@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace P2\Bundle\SecurityBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Class Configuration
 * @package P2\Bundle\SecurityBundle\DependencyInjection
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('p2_security');

        $rootNode
            ->children()
                ->scalarNode('document')->cannotBeEmpty()->end()
                ->scalarNode('manager')->cannotBeEmpty()->end()
                ->scalarNode('encoder')->defaultValue('sha256')->end()
            ->end();

        return $treeBuilder;
    }
}

Fix bug with missing config value

Fix bug with missing config value


<?php

namespace WorkerBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('worker');

        $rootNode
            ->children()
                ->arrayNode('providers')
                    ->useAttributeAsKey('key')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('class')->isRequired()->end()
                            ->arrayNode('arguments')
                                ->defaultValue(array())
                                ->performNoDeepMerging()
                                ->prototype('variable')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('queues')
                    ->useAttributeAsKey('key')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('name')->isRequired()->end()
                            ->scalarNode('provider')->isRequired()->end()
                        ->end()
                    ->end()
                ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace WorkerBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
	/**
	 * {@inheritDoc}
	 */
	public function getConfigTreeBuilder()
	{
		$treeBuilder = new TreeBuilder();
		$rootNode = $treeBuilder->root('worker');

		$rootNode
		->children()
			->arrayNode('providers')
				->useAttributeAsKey('key')
				->prototype('array')
					->children()
					->scalarNode('class')->isRequired()->end()
					->arrayNode('arguments')
						->defaultValue(array())
						->performNoDeepMerging()
						->prototype('variable')->end()
					->end()
				->end()
			->end()
		->end()
		->arrayNode('queues')
			->useAttributeAsKey('key')
			->prototype('array')
				->children()
					->scalarNode('name')->isRequired()->end()
					->scalarNode('provider')->isRequired()->end()
					->arrayNode('tags')
						->defaultValue(array())
						->performNoDeepMerging()
						->prototype('variable')->end()
					->end()
				->end()
			->end()
		->end()
		;

		return $treeBuilder;
	}
}

Add tags list on queues

[QUEUE] Add tags list on queues


<?php
namespace Janitor\Services\Analyzers;

use Janitor\Abstracts\AbstractAnalyzer;
use Janitor\Entities\Route;
use Janitor\Interfaces\AnalyzerInterface;

class RoutesAnalyzer extends AbstractAnalyzer implements AnalyzerInterface
{
	/**
	 * Compute the entities from the information
	 * that was passed to the analyzed
	 *
	 * @return \Janitor\Abstracts\AbstractAnalyzedEntity[]
	 */
	protected function createEntities()
	{
		$entities         = [];
		$routesCollection = $this->codebase->getRoutes();

		foreach ($routesCollection as $route) {
			$entity = new Route($this->folder, $route->getUri());
			$entity->setRoute($route);

			$entities[] = $entity;
		}

		return $entities;
	}
}

<?php
namespace Janitor\Services\Analyzers;

use Janitor\Abstracts\AbstractAnalyzer;
use Janitor\Entities\Route;
use Janitor\Interfaces\AnalyzerInterface;

class RoutesAnalyzer extends AbstractAnalyzer implements AnalyzerInterface
{
	/**
	 * Compute the entities from the information
	 * that was passed to the analyzed
	 *
	 * @return \Janitor\Abstracts\AbstractAnalyzedEntity[]
	 */
	protected function createEntities()
	{
		$entities         = [];
		$routesCollection = $this->codebase->getRoutes();

		/** @type \Illuminate\Routing\Route $route */
		foreach ($routesCollection as $route) {
			$name   = $route->getMethods()[0].' '.$route->getUri();
			$entity = new Route($this->folder, $name);
			$entity->setRoute($route);

			$entities[] = $entity;
		}

		return $entities;
	}
}

Add method to Route entity name

Add method to Route entity name


<?php namespace Autumn\Tools\Transformers;

use RainLab\Blog\Models\Post;
use League\Fractal\TransformerAbstract;

class BlogPostTransformer extends TransformerAbstract
{
    protected $defaultIncludes = [
        'featured_images',
    ];

    public function transform(Post $post)
    {
        return [
            'id' => $post->id,
            'title' => $post->title,
            'slug' => $post->slug,
            'excerpt' => $post->excerpt,
            'content' => $post->content,
            'published' => $post->published,
            'published_at' => $post->published_at,
            'categories' => $post->categories
        ];
    }

    public function includeFeaturedImages(Post $post)
    {
        $images = $post->featured_images;

        return $this->collection($images, new SystemFileTransformer);
    }
}

<?php namespace Autumn\Tools\Transformers;

use RainLab\Blog\Models\Post;
use League\Fractal\TransformerAbstract;

class BlogPostTransformer extends TransformerAbstract
{
    protected $defaultIncludes = [
        'featured_images',
    ];

    public function transform(Post $post)
    {
        return [
            'id' => $post->id,
            'title' => $post->title,
            'slug' => $post->slug,
            'excerpt' => $post->excerpt,
            'content' => $post->content,
            'published' => $post->published,
            'published_at' => $post->published_at->toDateTimeString(),
            'categories' => $post->categories()->get(['id', 'name', 'slug']),
            'author' => $post->user()->get(['id', 'first_name', 'last_name', 'login', 'email'])
        ];
    }

    public function includeFeaturedImages(Post $post)
    {
        return $this->collection($post->featured_images, new SystemFileTransformer);
    }
}

Add author to post transformer

Add author to post transformer


<?php

abstract class Loader{

    private $debugMode = false;

    protected $directedEdges = false;

    public abstract function createGraph();

    public function setEnableDirectedEdges($directedEdges){
        $this->directedEdges = $directedEdges;
    }

    private function writeDebugMessage($messageString){
        if($this->debugMode){
            echo $messageString;
        }

    }
}

<?php

abstract class Loader{

    private $debugMode = false;

    protected $directedEdges = false;

    public abstract function createGraph();

    public function setEnableDirectedEdges($directedEdges){
        $this->directedEdges = $directedEdges;
    }

    protected function writeDebugMessage($messageString){
        if($this->debugMode){
            echo $messageString;
        }

    }
}

Make debug method accessible to inherited classes


<?php

namespace WyriHaximus\React\ChildProcess\Pool;

use Evenement\EventEmitterInterface;
use React\ChildProcess\Process;
use React\EventLoop\LoopInterface;
use React\Promise\PromiseInterface;
use WyriHaximus\React\ChildProcess\Messenger\Messages\Call;

interface PoolInterface extends EventEmitterInterface
{
    /**
     * @param Process $process
     * @param LoopInterface $loop
     * @param array $options
     */
    public function __construct(Process $process, LoopInterface $loop, array $options = []);

    /**
     * @param Call $message
     * @return PromiseInterface
     */
    public function rpc(Call $message);

    /**
     * @return array
     */
    public function info();
}

<?php

namespace WyriHaximus\React\ChildProcess\Pool;

use Evenement\EventEmitterInterface;
use React\ChildProcess\Process;
use React\EventLoop\LoopInterface;
use React\Promise\PromiseInterface;
use WyriHaximus\React\ChildProcess\Messenger\Messages\Call;

interface PoolInterface extends EventEmitterInterface
{
    /**
     * @param Process $process
     * @param LoopInterface $loop
     * @param array $options
     */
    public function __construct(Process $process, LoopInterface $loop, array $options = []);

    /**
     * @param Call $message
     * @return PromiseInterface
     */
    public function rpc(Call $message);

    /**
     * @param string $message
     * @param int $timeout
     * @param null $signal
     * @return mixed
     */
    public function terminate($message, $timeout = 5, $signal = null);

    /**
     * @return array
     */
    public function info();
}

Terminate method to stop the pool

Terminate  method to stop the pool


<!DOCTYPE html>

        <title>Be right back.</title>

        <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>

Be right back.

@extends('layouts.default')

@section('content')

503

Our service is currently unavailable

@stop

Duplicate 404 error page for 503 error page


<?php namespace App\Presenters;

use Prettus\Repository\Presenter\FractalPresenter;

abstract class ExtendedFractalPresenter extends FractalPresenter
{
    public function parseIncludes($includes = array())
    {
        $request        = app('Illuminate\Http\Request');
        $paramIncludes  = config('repository.fractal.params.include','include');

        if ( $request->has( $paramIncludes ) ) {
            $includes = array_merge($includes, explode(',', $paramIncludes));
        }

        $this->fractal->parseIncludes($includes);

        return $this;
    }
}

<?php namespace App\Presenters;

use Request;
use Prettus\Repository\Presenter\FractalPresenter;

abstract class ExtendedFractalPresenter extends FractalPresenter
{
    public function parseIncludes($includes = array())
    {
        $request        = app('Illuminate\Http\Request');
        $paramIncludes  = config('repository.fractal.params.include','include');

        if ( $request->has( $paramIncludes ) ) {
            $includes = array_merge($includes, explode(',', Request::input($paramIncludes)));
        }

        $this->fractal->parseIncludes($includes);

        return $this;
  	}
}

Fix bug concerning include parameter

Fix bug concerning include parameter

The ExtendedFractalPresenter had a bug causing it to ignore the content
of the include uri parameter.

Now you can call /api/{some resource}?include={relation1},{relation2}
and the relations will be included in the response.


<?php

namespace actsmart\actsmart\Conversations;

/**
 * Class Message
 * @package actsmart\actsmart\Conversations
 *
 * A message is a structure piece of information that an Utterance will
 * carry from one conversation participant in a scene to another.
 *
 * @todo - we probably want to bring the Slack Message structure here.
 */
class Message
{
    public $text_response;

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

    public function getResponse()
    {
        return $this->text_response;
    }
}

<?php

namespace actsmart\actsmart\Conversations;

/**
 * Class Message
 * @package actsmart\actsmart\Conversations
 *
 * A message is a structure piece of information that an Utterance will
 * carry from one conversation participant in a scene to another.
 *
 * @todo - we probably want to bring the Slack Message structure here.
 */
class Message
{
    public $text_response;

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

    public function getResponse()
    {
        return $this->text_response;
    }
}

Make the text response in a message optional.


<?php

namespace Eschmar\CssInlinerBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('eschmar_css_inliner');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace Eschmar\CssInlinerBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('eschmar_css_inliner');
        // BC layer for symfony/config 4.1 and older
        if (! \method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->root('eschmar_css_inliner');
        } else {
            $rootNode = $treeBuilder->getRootNode();
        }

        return $treeBuilder;
    }
}

Fix symfony 5 BC deprecation alert on TreeBuilder

fix symfony v5.*  breaking change on TreeBuilder::root()


<?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\ContentBundle\Sluggable;

use Darvin\Utils\Strings\Transliterator\TransliteratorInterface;

/**
 * Sluggable transliterator
 */
class SluggableTransliterator
{
    /**
     * @var \Darvin\Utils\Strings\Transliterator\TransliteratorInterface
     */
    private $transliterator;

    /**
     * @param \Darvin\Utils\Strings\Transliterator\TransliteratorInterface $transliterator Transliterator
     */
    public function __construct(TransliteratorInterface $transliterator)
    {
        $this->transliterator = $transliterator;
    }

    /**
     * @param string $string String to transliterate
     *
     * @return string
     */
    public function transliterate($string)
    {
        return $this->transliterator->transliterate($string);
    }
}

<?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\ContentBundle\Sluggable;

use Darvin\Utils\Transliteratable\TransliteratorInterface;

/**
 * Sluggable transliterator
 */
class SluggableTransliterator
{
    /**
     * @var \Darvin\Utils\Transliteratable\TransliteratorInterface
     */
    private $transliterator;

    /**
     * @param \Darvin\Utils\Transliteratable\TransliteratorInterface $transliterator Transliterator
     */
    public function __construct(TransliteratorInterface $transliterator)
    {
        $this->transliterator = $transliterator;
    }

    /**
     * @param string $string String to transliterate
     *
     * @return string
     */
    public function transliterate($string)
    {
        return $this->transliterator->transliterate($string);
    }
}

Move transliterator to Transliteratable namespace.


<?php

namespace CascadeEnergy\DistributedOperations\Elasticsearch;

use CascadeEnergy\DistributedOperations\Elasticsearch\Interfaces\ReadOnlyInterface;
use CascadeEnergy\DistributedOperations\Elasticsearch\Traits\ReadOnlyTrait;
use CascadeEnergy\DistributedOperations\Utility\ProviderInterface;
use Elasticsearch\Helper\Iterators\SearchResponseIterator;

class Provider implements ProviderInterface, ReadOnlyInterface
{
    use ReadOnlyTrait;

    /** @var string */
    private $scrollTime = '1m';

    /** @var string */
    private $type;

    public function setScrollTime($scrollTime)
    {
        $this->scrollTime = $scrollTime;
    }

    public function setType($type)
    {
        $this->type = $type;
    }

    public function begin()
    {
        $searchParams = [
            'index' => $this->indexName,
            'scroll' => $this->scrollTime,
            'body' => ['query' => ['bool' => ['must' => ['term' => ['state' => 'new']]]]]
        ];

        if (!empty($this->type)) {
            $searchParams['type'] = $this->type;
        }

        $responseIterator = new SearchResponseIterator($this->client, $searchParams);

        return new ProviderIterator($responseIterator);
    }

    public function end(\Traversable $providerIterator)
    {
        if ($providerIterator instanceof ProviderIterator) {
            $providerIterator->end();
        }
    }
}

<?php

namespace CascadeEnergy\DistributedOperations\Elasticsearch;

use CascadeEnergy\DistributedOperations\Elasticsearch\Interfaces\ReadOnlyInterface;
use CascadeEnergy\DistributedOperations\Elasticsearch\Traits\ReadOnlyTrait;
use CascadeEnergy\DistributedOperations\Utility\ProviderInterface;
use Elasticsearch\Helper\Iterators\SearchResponseIterator;

class Provider implements ProviderInterface, ReadOnlyInterface
{
    use ReadOnlyTrait;

    /** @var string */
    private $scrollTime = '1m';

    /** @var string */
    private $type;

    public function setScrollTime($scrollTime)
    {
        $this->scrollTime = $scrollTime;
    }

    public function setType($type)
    {
        $this->type = $type;
    }

    public function begin()
    {
        $searchParams = [
            'index' => $this->indexName,
            'scroll' => $this->scrollTime,
            'body' => [
                'query' => [
                    'function_score' => [
                        'query' => ['term' => ['state' => 'new']],
                        'random_score' => []
                    ]
                ]
            ]
        ];

        if (!empty($this->type)) {
            $searchParams['type'] = $this->type;
        }

        $responseIterator = new SearchResponseIterator($this->client, $searchParams);

        return new ProviderIterator($responseIterator);
    }

    public function end(\Traversable $providerIterator)
    {
        if ($providerIterator instanceof ProviderIterator) {
            $providerIterator->end();
        }
    }
}

Switch to random scoring for ES query

Switch to random scoring for ES query


<?php

return array(

	'default' => 'json',

	'supported_formats' => array(
	    'application/xml' => 'xml',
	    'application/json' => 'json',
	    'application/vnd.php.serialized' => 'serialize',
	    'application/x-www-form-urlencoded' => 'querystr'
	)
);

<?php

return array(

	'default' => 'json',

	'supported_formats' => array(
// XML
	    'application/xml' => 'xml',
	    'text/xml' => 'xml',
// JSON
	    'application/json' => 'json',
		'application/x-javascript' => 'json',
		'text/javascript' => 'json',
		'text/x-javascript' => 'json',
		'text/x-json' => 'json',
// YAML
	    'text/yaml' => 'yaml',
		'text/x-yaml' => 'yaml',
		'application/yaml' => 'yaml',
		'application/x-yaml' => 'yaml',
// MISC
		'application/vnd.php.serialized' => 'serialize',
	    'application/x-www-form-urlencoded' => 'querystr'
	)
);

Add additional variations of Content-Type values, plus add support for yaml.


<?php

namespace Rogue\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Rogue\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Rogue\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Rogue\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \Rogue\Http\Middleware\RedirectIfAuthenticated::class,
        'role' => \Rogue\Http\Middleware\CheckRole::class,
    ];
}

<?php

namespace Rogue\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Rogue\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Rogue\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'api' => [
            // 'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Rogue\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \Rogue\Http\Middleware\RedirectIfAuthenticated::class,
        'role' => \Rogue\Http\Middleware\CheckRole::class,
    ];
}

Add api middleware group back into Kernal.php