<?php

/*
 * This file is a part of dflydev/dot-access-data.
 *
 * (c) Dragonfly Development Inc.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Dflydev\DotAccessData;

class Util
{
    /**
     * Test if array is an associative array
     *
     * Note that this function will return true if an array is empty. Meaning
     * empty arrays will be treated as if they are associative arrays.
     *
     * @param array $arr
     *
     * @return boolean
     */
    public static function isAssoc(array $arr)
    {
        return (is_array($arr) && (!count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr)));
    }

    /**
     * Merge contents from one associtative array to another
     *
     * @param array $to
     * @param array $from
     * @param bool  $clobber
     */
    public static function mergeAssocArray($to, $from, $clobber = true)
    {
        if ( is_array($from) ) {
            foreach ($from as $k => $v) {
                if (!isset($to[$k])) {
                    $to[$k] = $v;
                } else {
                    $to[$k] = self::mergeAssocArray($to[$k], $v, $clobber);
                }
            }

            return $to;
        }

        return $clobber ? $from : $to;
    }
}

<?php

/*
 * This file is a part of dflydev/dot-access-data.
 *
 * (c) Dragonfly Development Inc.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Dflydev\DotAccessData;

class Util
{
    /**
     * Test if array is an associative array
     *
     * Note that this function will return true if an array is empty. Meaning
     * empty arrays will be treated as if they are associative arrays.
     *
     * @param array $arr
     *
     * @return boolean
     */
    public static function isAssoc(array $arr)
    {
        return !count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr);
    }

    /**
     * Merge contents from one associtative array to another
     *
     * @param array $to
     * @param array $from
     * @param bool  $clobber
     */
    public static function mergeAssocArray($to, $from, $clobber = true)
    {
        if ( is_array($from) ) {
            foreach ($from as $k => $v) {
                if (!isset($to[$k])) {
                    $to[$k] = $v;
                } else {
                    $to[$k] = self::mergeAssocArray($to[$k], $v, $clobber);
                }
            }

            return $to;
        }

        return $clobber ? $from : $to;
    }
}

Remove redundant array check found by Psalm


<?php

namespace Nestor\Entities;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class Executions extends Model implements Transformable
{
    use TransformableTrait;

    protected $fillable = ['test_run_id', 'test_case_version_id', 'execution_status_id'];

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'executions';

    public function testRun()
    {
        return $this->belongsTo('Nestor\\Entities\\TestRuns', 'test_run_id');
    }

    public function testCaseVersion()
    {
        return $this->belongsTo('Nestor\\Entities\\TestCasesVersions', 'test_case_version_id');
    }

    public function executionStatus()
    {
        return $this->belongsTo('Nestor\\Entities\\ExecutionStatuses', 'execution_status_id');
    }
}

<?php

namespace Nestor\Entities;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class Executions extends Model implements Transformable
{
    use TransformableTrait;

    protected $fillable = ['test_run_id', 'test_case_version_id', 'execution_status_id', 'notes'];

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'executions';

    public function testRun()
    {
        return $this->belongsTo('Nestor\\Entities\\TestRuns', 'test_run_id');
    }

    public function testCaseVersion()
    {
        return $this->belongsTo('Nestor\\Entities\\TestCasesVersions', 'test_case_version_id');
    }

    public function executionStatus()
    {
        return $this->belongsTo('Nestor\\Entities\\ExecutionStatuses', 'execution_status_id');
    }
}

Allow user to fill notes

Allow user to fill notes


<?php

namespace CarlBennett\MVC\Libraries;

use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;

final class Template {

  protected $context;
  protected $template;

  public function __construct(&$context, $template) {
    $this->additional_css = [];
    $this->opengraph      = new SplObjectStorage();
    $this->setContext($context);
    $this->setTemplate($template);
  }

  public function getContext() {
    return $this->context;
  }

  public function getTemplate() {
    return $this->template;
  }

  public function render() {
    $cwd = getcwd();
    try {
      chdir($cwd . "/templates");
      if (!file_exists($this->template)) {
        throw new TemplateNotFoundException($this);
      }
      require($this->template);
    } finally {
      chdir($cwd);
    }
  }

  public function setContext(&$context) {
    $this->context = $context;
  }

  public function setTemplate($template) {
    $this->template = "./" . $template . ".phtml";
    Logger::logMetric("template", $template);
  }

}

<?php

namespace CarlBennett\MVC\Libraries;

use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;

final class Template {

  protected $context;
  protected $template;

  public function __construct(&$context, $template) {
    $this->additional_css = [];
    $this->opengraph      = new SplObjectStorage();
    $this->setContext($context);
    $this->setTemplate($template);
  }

  public function getContext() {
    return $this->context;
  }

  public function getTemplate() {
    return $this->template;
  }

  public function render() {
    $cwd = getcwd();
    try {
      chdir($cwd . DIRECTORY_SEPARATOR . "templates");
      if (!file_exists($this->template)) {
        throw new TemplateNotFoundException($this);
      }
      require($this->template);
    } finally {
      chdir($cwd);
    }
  }

  public function setContext(&$context) {
    $this->context = $context;
  }

  public function setTemplate($template) {
    $this->template = "." . DIRECTORY_SEPARATOR
      . str_replace("/", DIRECTORY_SEPARATOR, $template) . ".phtml";
    Logger::logMetric("template", $template);
  }

}

Use DIRECTORY_SEPARATOR instead of '/'

Use DIRECTORY_SEPARATOR instead of '/'


<?php

namespace Limenius\Liform\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Forms;
use Limenius\Liform\Form\Extension\AddLiformExtension;

/**
 *
 * Common test utils
 *
 * @see TestCase
 */
class LiformTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FormFactoryInterface
     */
    protected $factory;

    protected function setUp()
    {
        $ext = new AddLiformExtension();
        $this->factory = Forms::createFormFactoryBuilder()
            ->addExtensions([])
            ->addTypeExtensions([$ext])
            ->getFormFactory();
    }
}

<?php

namespace Limenius\Liform\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Forms;
use Limenius\Liform\Form\Extension\AddLiformExtension;

/**
 *
 * Common test utils
 *
 * @see TestCase
 */
class LiformTestCase extends TestCase
{
    /**
     * @var FormFactoryInterface
     */
    protected $factory;

    protected function setUp()
    {
        $ext = new AddLiformExtension();
        $this->factory = Forms::createFormFactoryBuilder()
            ->addExtensions([])
            ->addTypeExtensions([$ext])
            ->getFormFactory();
    }
}

Update tests to phpunit 6

Update tests to phpunit 6


<?php

return array(
		'name' => 'Stupid Reborn Admin Theme',
		'description' => 'Flat Design Admin theme for the Reborn CMS',
		'author' => 'Reborn Development Team',
		'website' => 'http://www.reborncms.com',
		'version' => 1.0,
		'min-require' => 2.0
	);

<?php

return array(
		'name' => 'Reborn Admin Default Theme',
		'description' => 'Flat Design Admin theme for the Reborn CMS',
		'author' => 'Reborn Development Team',
		'website' => 'http://www.reborncms.com',
		'version' => 1.0,
		'min-require' => 2.0
	);

Update Admin Panel Theme Info.

Update Admin Panel Theme Info.


<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

// Stats Functions
include 'functions/loadAvg.php';
include 'memory.php';

echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
debug_collectionInterval($config['debug'], $config['updateinterval']);

while (true){
	debug_collectionInfoStart($config['debug']);

	collect_loadAvg($config['debug']);
    collect_memory();

    debug_collectionInfoEnd($config['debug']);
	sleep($config['updateinterval']);
}
?>

<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

// Stats Functions
include 'functions/loadAvg.php';
include 'functions/memory.php';

echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
debug_collectionInterval($config['debug'], $config['updateinterval']);

while (true){
	debug_collectionInfoStart($config['debug']);

	collect_loadAvg($config['debug']);
    collect_memory();

    debug_collectionInfoEnd($config['debug']);
	sleep($config['updateinterval']);
}
?>

Include the correct memory file (oops)

Include the correct memory file (oops)


<?php

namespace As3\Bundle\ModlrBundle\DependencyInjection\Compiler;

use As3\Bundle\ModlrBundle\DependencyInjection\Utility;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Adds event subscribers to the event dispatcher.
 *
 * @author  Jacob Bare <jacob.bare@gmail.com>
 */
class EventSubscribersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $dispatcher = $container->getDefinition(Utility::getAliasedName('event_dispatcher'));

        $tagged = $container->findTaggedServiceIds(Utility::getAliasedName('event_subscriber'));
        foreach ($tagged as $id => $tags) {
            $dispatcher->addMethodCall('addSubscriber', [new Reference($id)]);
        }
    }
}

<?php

namespace As3\Bundle\ModlrBundle\DependencyInjection\Compiler;

use As3\Bundle\ModlrBundle\DependencyInjection\Utility;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Adds event subscribers to the event dispatcher.
 *
 * @author  Jacob Bare <jacob.bare@gmail.com>
 */
class EventSubscribersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $dispatcher = $container->getDefinition(Utility::getAliasedName('event_dispatcher'));

        $sortFunc = function ($a, $b) {
            $a = isset($a['priority']) ? (Integer) $a['priority'] : 0;
            $b = isset($b['priority']) ? (Integer) $b['priority'] : 0;

            return $a > $b ? -1 : 1;
        };

        $tagged = $container->findTaggedServiceIds(Utility::getAliasedName('event_subscriber'));
        $subscribers = [];
        foreach ($tagged as $id => $tags) {
            foreach ($tags as $attributes) {
                $subscribers[$id] = $attributes;
            }
        }
        uasort($subscribers, $sortFunc);
        foreach ($subscribers as $id => $attrs) {
            $dispatcher->addMethodCall('addSubscriber', [new Reference($id)]);
        }
    }
}

Add prioritization to event subscriber tags


<?php

namespace EXSyst\Bundle\RestBundle\Controller;

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

/**
 * @author Ener-Getick <egetick@gmail.com>
 */
abstract class RestController extends Controller
{
    /**
     * @param mixed  $value   to be serialized
     * @param mixed  $context Serialization context
     * @param string $format
     *
     * @return string
     */
    protected function serializeView($value, $context, $format = null)
    {
        if ($format === null) {
            $format = $this->getParameter('exsyst_rest.serializer.default_format');
        }

        $serializer = $this->get('exsyst_rest.serializer');

        return $serializer->serialize($value, $format, $context);
    }

    /**
     * @param mixed  $value   to be serialized
     * @param mixed  $context Serialization context
     * @param string $format
     *
     * @return Response
     */
    protected function serialize($value, $context, $format = null, Response $response = null)
    {
        if ($response === null) {
            $response = new Response();
        }
        $serializedValue = $this->serializeView($value, $context, $format);
        $response->setContent($serializedValue);

        $etagGenerator = $this->get('exsyst_rest.etag_generator');
        $response->setEtag(
            $etagGenerator->generate($response->getContent())
        );

        $response->isNotModified(
            $this->get('request_stack')->getCurrentRequest()
        );

        return $response;
    }
}

<?php

namespace EXSyst\Bundle\RestBundle\Controller;

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

/**
 * @author Ener-Getick <egetick@gmail.com>
 */
abstract class RestController extends Controller
{
    /**
     * @param mixed  $value   to be serialized
     * @param mixed  $context Serialization context
     * @param string $format
     *
     * @return string
     */
    protected function serializeView($value, $context, $format = null)
    {
        if ($format === null) {
            $format = $this->getParameter('exsyst_rest.serializer.default_format');
        }

        $serializer = $this->get('exsyst_rest.serializer');

        return $serializer->serialize($value, $format, $context);
    }

    /**
     * @param mixed  $value   to be serialized
     * @param mixed  $context Serialization context
     * @param string $format
     *
     * @return Response
     */
    protected function serialize($value, $context, $format = null, Response $response = null)
    {
        if ($response === null) {
            $response = new Response();
        }
        $serializedValue = $this->serializeView($value, $context, $format);
        $response->setContent($serializedValue);

        $etagGenerator = $this->get('exsyst_rest.etag_generator');
        $etag = $etagGenerator->generate($response->getContent());
        if($etag !== false) {
            $response->setEtag($etag);
            $response->isNotModified(
                $this->get('request_stack')->getCurrentRequest()
            );
        }

        return $response;
    }
}

Set the etag only if it was generated

Set the etag only if it was generated


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Event;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * Deauthentication happens in case the user has changed when trying to refresh it.
 *
 * @author Hamza Amrouche <hamza.simperfit@gmail.com>
 */
class DeauthenticatedEvent extends Event
{
    private $originalToken;
    private $refreshedToken;

    public function __construct(TokenInterface $originalToken, TokenInterface $refreshedToken)
    {
        $this->originalToken = $originalToken;
        $this->refreshedToken = $refreshedToken;
    }

    public function getRefreshedToken(): TokenInterface
    {
        return $this->refreshedToken;
    }

    public function getOriginalToken(): TokenInterface
    {
        return $this->originalToken;
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Event;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * Deauthentication happens in case the user has changed when trying to refresh the token.
 *
 * @author Hamza Amrouche <hamza.simperfit@gmail.com>
 */
class DeauthenticatedEvent extends Event
{
    private $originalToken;
    private $refreshedToken;

    public function __construct(TokenInterface $originalToken, TokenInterface $refreshedToken)
    {
        $this->originalToken = $originalToken;
        $this->refreshedToken = $refreshedToken;
    }

    public function getRefreshedToken(): TokenInterface
    {
        return $this->refreshedToken;
    }

    public function getOriginalToken(): TokenInterface
    {
        return $this->originalToken;
    }
}

[Security] Change the phrasing of the deauthenticated event


<?php

namespace Vagrant\Shim\Command;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class InstallCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('install')
            ->setDescription('Symlink vagrant-shim to a directory in $PATH')
            ->addArgument('path', InputArgument::OPTIONAL, '<comment>Default</comment>: <info>/usr/local/bin</info>')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path') ?: '/usr/local/bin';

        if ($this->manager->isInstalled()) {
            $output->write(sprintf('Uninstalling from <info>%s</info>...', join('</info>, <info>', $this->manager->getInstalledPaths())));

            if ($this->manager->uninstall()) {
                $output->writeln('<comment>SUCCESS</comment>');
            } else {
                $output->writeln('<error>FAILED</error>');

                return 1;
            }
        }

        $output->write(sprintf('Installing to <info>%s</info>...', $path));

        if ($this->manager->install($path)) {
            $output->writeln('<comment>SUCCESS</comment>');
        } else {
            $output->writeln('<error>FAILED</error>');

            return 1;
        }

        // Run "shim"
        $command = $this->getApplication()->find('shim');
        $command->run(new ArrayInput(array('command' => 'shim')), $output);
    }
}

<?php

namespace Vagrant\Shim\Command;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class InstallCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('install')
            ->setDescription('Symlink vagrant-shim to a directory in $PATH')
            ->addArgument('path', InputArgument::OPTIONAL, '<comment>Default</comment>: <info>/usr/local/bin</info>')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path') ?: '/usr/local/bin';

        if ($this->manager->isInstalled()) {
            $output->write(sprintf('Uninstalling from <info>%s</info>...', join('</info>, <info>', $this->manager->getInstalledPaths())));

            if ($this->manager->uninstall()) {
                $output->writeln('<comment>SUCCESS</comment>');
            } else {
                $output->writeln('<error>FAILED</error>');

                return 1;
            }
        }

        $output->write(sprintf('Installing to <info>%s</info>...', $path));

        if ($this->manager->install($path)) {
            $output->writeln('<comment>SUCCESS</comment>');
        } else {
            $output->writeln('<error>FAILED</error>');

            return 1;
        }
    }
}

Install no longer runs shim

Install no longer runs shim


<?php

namespace App\Ship\Generator;

use Illuminate\Support\ServiceProvider;

class GeneratorsServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerGenerators([
            'Action',
            'Route',
            'Task',
            'Exception',
            // ...
        ]);
    }

    /**
     * Register the generators.
     */
    private function registerGenerators(array $classes)
    {
        foreach ($classes as $class) {
            $lowerClass = strtolower($class);

            $this->app->singleton("command.porto.$lowerClass", function ($app) use ($class) {
                return $app['App\Ship\Generator\Commands\\' . $class . 'Generator'];
            });

            $this->commands("command.porto.$lowerClass");
        }

    }

}

<?php

namespace App\Ship\Generator;

use Illuminate\Support\ServiceProvider;

class GeneratorsServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerGenerators([
            'Action',
            'Exception',
            'Route',
            'Task',
            'Model',
        ]);
    }

    /**
     * Register the generators.
     */
    private function registerGenerators(array $classes)
    {
        foreach ($classes as $class) {
            $lowerClass = strtolower($class);

            $this->app->singleton("command.porto.$lowerClass", function ($app) use ($class) {
                return $app['App\Ship\Generator\Commands\\' . $class . 'Generator'];
            });

            $this->commands("command.porto.$lowerClass");
        }
    }
}

Add Model generator to Generators Service Provider


<?php

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

use App\Models\Event;
use League\Fractal;
use App\Models\Chat\Channel;

class ChannelTransformer extends Fractal\TransformerAbstract
{
    public function transform(Channel $channel)
    {
        return [
            'channel_id' => $channel->channel_id,
            'name' => $channel->name,
            'type' => $channel->type,
        ];
    }
}

<?php

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

use App\Models\Event;
use League\Fractal;
use App\Models\Chat\Channel;

class ChannelTransformer extends Fractal\TransformerAbstract
{
    public function transform(Channel $channel)
    {
        return [
            'channel_id' => $channel->channel_id,
            'name' => $channel->name,
            'description' => $channel->description,
            'type' => $channel->type,
        ];
    }
}

Add description to channel response

Add description to channel response


<?php

namespace FroshProfiler\Components\VarDumper;

use Enlight_Controller_Front;
use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;

/**
 * Class RequestContextProvider
 * @author Soner Sayakci <shyim@posteo.de>
 */
class RequestContextProvider implements ContextProviderInterface
{
    /**
     * @var Enlight_Controller_Front
     */
    private $front;

    /**
     * RequestContextProvider constructor.
     * @param Enlight_Controller_Front $front
     * @author Soner Sayakci <shyim@posteo.de>
     */
    public function __construct(Enlight_Controller_Front $front)
    {
        $this->front = $front;
    }

    /**
     * @return array|null Context data or null if unable to provide any context
     */
    public function getContext()
    {
        $request = $this->front->Request();

        return array(
            'uri' => $request->getScheme() . '//' . $request->getHttpHost() . $request->getRequestUri(),
            'method' => $request->getMethod(),
            'controller' => $request->getControllerName(),
            'identifier' => spl_object_hash($request),
        );
    }
}

<?php

namespace FroshProfiler\Components\VarDumper;

use Enlight_Controller_Front;
use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;

/**
 * Class RequestContextProvider
 * @author Soner Sayakci <shyim@posteo.de>
 */
class RequestContextProvider implements ContextProviderInterface
{
    /**
     * @var Enlight_Controller_Front
     */
    private $front;

    /**
     * RequestContextProvider constructor.
     * @param Enlight_Controller_Front $front
     * @author Soner Sayakci <shyim@posteo.de>
     */
    public function __construct(Enlight_Controller_Front $front)
    {
        $this->front = $front;
    }

    /**
     * @return array|null Context data or null if unable to provide any context
     */
    public function getContext()
    {
        $request = $this->front->Request();

        if ($request === null) {
            return null;
        }

        return array(
            'uri' => $request->getScheme() . '//' . $request->getHttpHost() . $request->getRequestUri(),
            'method' => $request->getMethod(),
            'controller' => $request->getControllerName(),
            'identifier' => spl_object_hash($request),
        );
    }
}

Fix VarDumper Server for Dumps where no request exist


<?php
declare(strict_types=1);

namespace HansOtt\PSR7Cookies;

use Exception;

/**
 * @deprecated Exception is not used and will be removed in future versions
 */
final class InvalidArgumentException extends Exception
{
}

<?php
declare(strict_types=1);

namespace HansOtt\PSR7Cookies;

use Exception;

final class InvalidArgumentException extends Exception
{
}

Revert "🗑 Add deprecation warning"

Revert "🗑 Add deprecation warning"

This reverts commit 10151d7522980429e960b883e09b95a1c393172e.


<?php
/**
 * list_patch_0300
 * @package modules.list
 */
class list_patch_0300 extends patch_BasePatch
{
	/**
	 * Entry point of the patch execution.
	 */
	public function execute()
	{
		/*$newPath = f_util_FileUtils::buildWebeditPath('modules/list/persistentdocument/editablelist.xml');
		$newModel = generator_PersistentModel::loadModelFromString(f_util_FileUtils::read($newPath), 'list', 'editablelist');
		$newProp = $newModel->getPropertyByName('useVoIfNotTranslated');
		f_persistentdocument_PersistentProvider::getInstance()->addProperty('list', 'editablelist', $newProp);*/

		foreach (list_EditablelistService::getInstance()->createQuery()->find() as $list)
		{
			$list->setUseVoIfNotTranslated(true);
			$list->save();
		}
	}

	/**
	 * @return String
	 */
	protected final function getModuleName()
	{
		return 'list';
	}

	/**
	 * @return String
	 */
	protected final function getNumber()
	{
		return '0300';
	}
}

<?php
/**
 * list_patch_0300
 * @package modules.list
 */
class list_patch_0300 extends patch_BasePatch
{
	/**
	 * Entry point of the patch execution.
	 */
	public function execute()
	{
		try
		{
			$newPath = f_util_FileUtils::buildWebeditPath('modules/list/persistentdocument/editablelist.xml');
			$newModel = generator_PersistentModel::loadModelFromString(f_util_FileUtils::read($newPath), 'list', 'editablelist');
			$newProp = $newModel->getPropertyByName('useVoIfNotTranslated');
			f_persistentdocument_PersistentProvider::getInstance()->addProperty('list', 'editablelist', $newProp);
		}
		catch (BaseException $e)
		{
			if ($e->getAttribute('sqlstate') != '42S21' || $e->getAttribute('errorcode') != '1060')
			{
				throw $e;
			}
		}

		foreach (list_EditablelistService::getInstance()->createQuery()->find() as $list)
		{
			$list->setUseVoIfNotTranslated(true);
			$list->save();
		}
	}

	/**
	 * @return String
	 */
	protected final function getModuleName()
	{
		return 'list';
	}

	/**
	 * @return String
	 */
	protected final function getNumber()
	{
		return '0300';
	}
}

[FIX] Patch 300 et colonne potientiellement existante


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface MethodNameMatch extends ParametersMatch
{
    /**
     * Adds a new method name match and returns the parameter match object for
     * further matching possibilities.
     *
     * @param \PHPUnit\Framework\Constraint\Constraint $name Constraint for matching method, if a string is passed it will use the PHPUnit_Framework_Constraint_IsEqual
     *
     * @return ParametersMatch
     */
    public function method($name);
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface MethodNameMatch extends ParametersMatch
{
    /**
     * Adds a new method name match and returns the parameter match object for
     * further matching possibilities.
     *
     * @param \PHPUnit\Framework\Constraint\Constraint $constraint Constraint for matching method, if a string is passed it will use the PHPUnit_Framework_Constraint_IsEqual
     *
     * @return ParametersMatch
     */
    public function method($constraint);
}

Fix issue identified by Psalm

Fix issue identified by Psalm


<?php

namespace Milax\Mconsole\Processors;

use Milax\Mconsole\Contracts\ContentLocalizator as Repository;

class ContentLocalizator implements Repository
{
    public function localize($object, $lang = null)
    {
        $lang = is_null($lang) ? config('app.locale') : $lang;
        $attributes = $object->getAttributes();

        foreach ($attributes as $key => $value) {
            $value = $object->$key;
            if (is_array($value) && isset($value[$lang])) {
                $attributes[$key] = $value[$lang];
            }
        }

        $object->fill($attributes);

        return $object;
    }
}

<?php

namespace Milax\Mconsole\Processors;

use Milax\Mconsole\Contracts\ContentLocalizator as Repository;

class ContentLocalizator implements Repository
{
    public function localize($object, $lang = null)
    {
        $lang = is_null($lang) ? config('app.locale') : $lang;
        $attributes = $object->getAttributes();

        foreach ($attributes as $key => $value) {
            $hasLanguages = false;
            $value = $object->$key;
            if (is_array($value)) {
                if (isset($value[$lang])) {
                    $hasLanguages = true;
                }
            } else {
                $value = json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    if (isset($value[$lang])) {
                        $hasLanguages = true;
                    }
                }
            }

            if ($hasLanguages) {
                $attributes[$key] = $value[$lang];
            }
        }

        $object->fill($attributes);

        return $object;
    }
}

Support for screened json strings

Support for screened json strings


<?php // @codeCoverageIgnoreStart

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress;

/**
 * Class Patterns
 *
 * @package WyriHaximus\HtmlCompress
 */
class Patterns
{
    const MATCH_PRE        = '!(<pre[^>]*>?)(.*?)(</pre>)!is';
    const MATCH_TEXTAREA   = '!(<textarea[^>]*>?)(.*?)(</textarea>)!is';
    const MATCH_STYLE      = '!(<style>|<style[^>]*>?)(.*?)(</style>)!is';
    // @codingStandardsIgnoreStart
    const MATCH_JSCRIPT    = '!(<script>|<script[^>]*type="text/javascript"[^>]*>|<script[^>]*type=\'text/javascript\'[^>]*>)(.*?)(</script>)!is';
    // @codingStandardsIgnoreEnd
    const MATCH_SCRIPT     = '!(<script[^>]*>?)(.*?)(</script>)!is';
    const MATCH_NOCOMPRESS = '!(<nocompress>)(.*?)(</nocompress>)!is';
}

<?php // @codeCoverageIgnoreStart

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress;

/**
 * Class Patterns
 *
 * @package WyriHaximus\HtmlCompress
 */
class Patterns
{
    const MATCH_PRE        = '!(<pre>|<pre[^>]*>?)(.*?)(</pre>)!is';
    const MATCH_TEXTAREA   = '!(<textarea>|<textarea[^>]*>?)(.*?)(</textarea>)!is';
    const MATCH_STYLE      = '!(<style>|<style[^>]*>?)(.*?)(</style>)!is';
    // @codingStandardsIgnoreStart
    const MATCH_JSCRIPT    = '!(<script>|<script[^>]*type="text/javascript"[^>]*>|<script[^>]*type=\'text/javascript\'[^>]*>)(.*?)(</script>)!is';
    // @codingStandardsIgnoreEnd
    const MATCH_SCRIPT     = '!(<script[^>]*>?)(.*?)(</script>)!is';
    const MATCH_NOCOMPRESS = '!(<nocompress>)(.*?)(</nocompress>)!is';
}

Make sure to match pre and textarea without any attributes


<?php

namespace Illuminate\Foundation\Console;

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

class ServeCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Serve the application on the PHP development server';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        chdir($this->laravel->publicPath());

        $host = $this->input->getOption('host');

        $port = $this->input->getOption('port');

        $base = $this->laravel->basePath();

        $this->info("Laravel development server started on http://{$host}:{$port}/");

        passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} \"{$base}\"/server.php");
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'],

            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
        ];
    }
}

<?php

namespace Illuminate\Foundation\Console;

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

class ServeCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Serve the application on the PHP development server';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        chdir($this->laravel->publicPath());

        $host = $this->input->getOption('host');

        $port = $this->input->getOption('port');

        $base = $this->laravel->basePath();

        $this->info("Laravel development server started on http://{$host}:{$port}/");

        if (defined('HHVM_VERSION') && HHVM_VERSION >= '3.8.0') {
            passthru('"'.PHP_BINARY.'"'." -m server -v Server.Type=proxygen -v Server.SourceRoot=\"{$base}\"/ -v Server.IP={$host} -v Server.Port={$port} -v Server.DefaultDocument=server.php -v Server.ErrorDocument404=server.php");
        } else {
            passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} \"{$base}\"/server.php");
        }
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'],

            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
        ];
    }
}

Add HHVM >= 3.8.0 support in the artisan serve command via Proxygen Web Server

Now we can run Laravel development server with HHVM, like this:
hhvm artisan serve


<?php

namespace Rayku\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

use Rayku\UserBundle\Entity\User;
use Rayku\UserBundle\Form\UserType;

/**
 * User controller.
 */
class UserController extends Controller
{
    /**
     * @ApiDoc(
     *   resource=true,
     *   description="Update a user profile settings",
     *   input="Rayku\UserBundle\Form\UserType"
     * )
     */
    public function postUserAction(User $user)
    {
    	if($user->getId() !== $this->getUser()->getId()){
    		die('access denied');
    		throw new AccessDeniedException();
    	}
    	$request = $this->getRequest();
        $editForm = $this->createForm(new UserType(), $user);
        $editForm->bind($request);

        if ($editForm->isValid()) {
        	$em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            return $user;
        }
        return array(
            'entity'      => $user,
            'edit_form'   => $editForm->createView(),
        );
    }
}

<?php

namespace Rayku\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use Rayku\UserBundle\Entity\User;
use Rayku\UserBundle\Form\UserType;

/**
 * User controller.
 */
class UserController extends Controller
{
    /**
     * @ApiDoc(
     *   resource=true,
     *   description="Update a user profile settings",
     *   input="Rayku\UserBundle\Form\UserType"
     * )
     */
    public function postUserAction(User $user)
    {
    	if($user->getId() !== $this->getUser()->getId()){
    		throw new AccessDeniedException();
    	}
    	$request = $this->getRequest();
        $editForm = $this->createForm(new UserType(), $user);
        $editForm->bind($request);

        if ($editForm->isValid()) {
        	$em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            return $user;
        }
        return array(
            'entity'      => $user,
            'edit_form'   => $editForm->createView(),
        );
    }
}

Throw access denied exception when user doesn't match


<?php
if (!defined('MEDIAWIKI')) die();
/**
 * Class file for the GoogleAdSense extension
 *
 * @addtogroup Extensions
 * @author Siebrand Mazeland
 * @license MIT
 */
class GoogleAdSense {

	static function GoogleAdSenseInSidebar( $skin, &$bar ) {
		global $wgGoogleAdSenseWidth, $wgGoogleAdSenseID,
			$wgGoogleAdSenseHeight, $wgGoogleAdSenseClient,
			$wgGoogleAdSenseSlot, $wgGoogleAdSenseSrc;

		// Return $bar unchanged if not all values have been set.
		// FIXME: signal incorrect configuration nicely?
		if( $wgGoogleAdSenseClient == 'none' || $wgGoogleAdSenseSlot == 'none' || $wgGoogleAdSenseID == 'none' )
			return $bar;

		wfLoadExtensionMessages( 'GoogleAdSense' );

		$bar['googleadsense'] = "<script type=\"text/javascript\"><!--
google_ad_client = \"$wgGoogleAdSenseClient\";
/* $wgGoogleAdSenseID */
google_ad_slot = \"$wgGoogleAdSenseSlot\";
google_ad_width = $wgGoogleAdSenseWidth;
google_ad_height = $wgGoogleAdSenseHeight;
//-->
</script>
<script type=\"text/javascript\"
src=\"$wgGoogleAdSenseSrc\">
</script>";

		return $bar;
	}
}

<?php
if (!defined('MEDIAWIKI')) die();
/**
 * Class file for the GoogleAdSense extension
 *
 * @addtogroup Extensions
 * @author Siebrand Mazeland
 * @license MIT
 */
class GoogleAdSense {

	static function GoogleAdSenseInSidebar( $skin, &$bar ) {
		global $wgGoogleAdSenseWidth, $wgGoogleAdSenseID,
			$wgGoogleAdSenseHeight, $wgGoogleAdSenseClient,
			$wgGoogleAdSenseSlot, $wgGoogleAdSenseSrc;

		// Return $bar unchanged if not all values have been set.
		// FIXME: signal incorrect configuration nicely?
		if( $wgGoogleAdSenseClient == 'none' || $wgGoogleAdSenseSlot == 'none' || $wgGoogleAdSenseID == 'none' )
			return $bar;

		wfLoadExtensionMessages( 'GoogleAdSense' );

		$bar['googleadsense'] = "<script type=\"text/javascript\"><!--
google_ad_client = \"$wgGoogleAdSenseClient\";
/* $wgGoogleAdSenseID */
google_ad_slot = \"$wgGoogleAdSenseSlot\";
google_ad_width = $wgGoogleAdSenseWidth;
google_ad_height = $wgGoogleAdSenseHeight;
//-->
</script>
<script type=\"text/javascript\"
src=\"$wgGoogleAdSenseSrc\">
</script>";

		return true;
	}
}

Return true instead of $bar.

Return true instead of $bar.


<?php
namespace PVL\NowPlayingAdapter;

use \Entity\Station;

class FillydelphiaRadio extends AdapterAbstract
{
    /* Process a nowplaying record. */
    protected function _process($np)
    {
        $return_raw = $this->getUrl();

        if (!$return_raw)
            return false;

        $return = @json_decode($return_raw, true);

        if ($return['result'])
        {
            $np['listeners'] = (int)$return['result']['server_listener_total'];

            $np_stream = $return['result']['server_streams'][0];
            $np['artist'] = $np_stream['artist'];
            $np['title'] = $np_stream['song'];
            $np['text'] = $np_stream['artist'].' - '.$np_stream['song'];
            return $np;
        }

        return false;
    }
}

<?php
namespace PVL\NowPlayingAdapter;

use \Entity\Station;

class FillydelphiaRadio extends AdapterAbstract
{
    /* Process a nowplaying record. */
    protected function _process($np)
    {
        $return_raw = $this->getUrl();

        if (!$return_raw)
            return false;

        $return = @json_decode($return_raw, true);

        if ($return['result'])
        {
            $np['listeners'] = (int)$return['result']['server_listener_total'];

            $np_stream = $return['result']['server_streams'][0]['stream_nowplaying'];
            $np['artist'] = $np_stream['artist'];
            $np['title'] = $np_stream['song'];
            $np['text'] = $np_stream['text'];
            return $np;
        }

        return false;
    }
}

Fix format inconsistency with FR/THR.

Fix format inconsistency with FR/THR.


<?php

namespace Liip\ImagineBundle\Imagine\Filter\Loader;

use Imagine\Exception\InvalidArgumentException;
use Imagine\Image\ImageInterface;
use Liip\ImagineBundle\Imagine\Filter\RelativeResize;

/**
 * Loader for this bundle's relative resize filter.
 *
 * @author Jeremy Mikola <jmikola@gmail.com>
 */
class RelativeResizeFilterLoader implements LoaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ImageInterface $image, array $options = array())
    {
        if (list($method, $parameter) = each($options)) {
            $filter = new RelativeResize($method, $parameter);

            return $filter->apply($image);
        }

        throw new InvalidArgumentException('Expected method/parameter pair, none given');
    }
}

<?php

namespace Liip\ImagineBundle\Imagine\Filter\Loader;

use Imagine\Exception\InvalidArgumentException;
use Imagine\Image\ImageInterface;
use Liip\ImagineBundle\Imagine\Filter\RelativeResize;

/**
 * Loader for this bundle's relative resize filter.
 *
 * @author Jeremy Mikola <jmikola@gmail.com>
 */
class RelativeResizeFilterLoader implements LoaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ImageInterface $image, array $options = array())
    {
        foreach ($options as $method => $parameter) {
            $filter = new RelativeResize($method, $parameter);

            return $filter->apply($image);
        }

        throw new InvalidArgumentException('Expected method/parameter pair, none given');
    }
}

Revert "Refactor RelativeResize param extraction in filter loader"

This reverts commit 6226d0f5dffda0f8db8cfa212ced16b73c44b1b0.


<?php

namespace Silber\Bouncer\Database\Titles;

use Illuminate\Support\Str;

abstract class Title
{
    /**
     * The human-readable title.
     *
     * @var string
     */
    protected $title = '';

    /**
     * Convert the given string into a human-readable format.
     *
     * @param  string  $value
     * @return string
     */
    protected function humanize($value)
    {
        // First we'll convert the string to snake case. Then we'll
        // convert all dashes and underscores to spaces. Finally,
        // we'll add a space before a pound (Laravel doesn't).
        $value = Str::snake($value);

        $value = preg_replace('~(?:-|_)+~', ' ', $value);

        $value = preg_replace('~([^ ])(?:#)+~', '$1 #', $value);

        return ucfirst($value);
    }

    /**
     * Get the title as a string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->title;
    }
}

<?php

namespace Silber\Bouncer\Database\Titles;

use Illuminate\Support\Str;

abstract class Title
{
    /**
     * The human-readable title.
     *
     * @var string
     */
    protected $title = '';

    /**
     * Convert the given string into a human-readable format.
     *
     * @param  string  $value
     * @return string
     */
    protected function humanize($value)
    {
        // Older versions of Laravel's inflector strip out spaces
        // in the original string, so we'll first swap out all
        // spaces with underscores, then convert them back.
        $value = str_replace(' ', '_', $value);

        // First we'll convert the string to snake case. Then we'll
        // convert all dashes and underscores to spaces. Finally,
        // we'll add a space before a pound (Laravel doesn't).
        $value = Str::snake($value);

        $value = preg_replace('~(?:-|_)+~', ' ', $value);

        $value = preg_replace('~([^ ])(?:#)+~', '$1 #', $value);

        return ucfirst($value);
    }

    /**
     * Get the title as a string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->title;
    }
}

Handle spaces in older versions of Illuminate


<?php

class Tests_Selenium2TestCase_SessionCommand_FileTest extends Tests_Selenium2TestCase_BaseTestCase
{
    public function testUploadFile()
    {
        $this->url('php/file_upload.php');

        $remote_file = $this->file('selenium-1-tests/html/banner.gif');

        $this->byName('upload_here')
            ->value($remote_file);

        $this->byId('submit')
            ->click();

        $msg_displayed    = $this->byId('uploaded')
            ->displayed();

        $this->assertNotEmpty($msg_displayed);
    }
}

<?php

class Tests_Selenium2TestCase_SessionCommand_FileTest extends Tests_Selenium2TestCase_BaseTestCase
{
    public function testUploadFile()
    {
        $this->markTestIncomplete("Cannot get this to run reliablyat all on Travis CI.");
        $this->url('php/file_upload.php');

        $remote_file = $this->file('selenium-1-tests/html/banner.gif');

        $this->byName('upload_here')
            ->value($remote_file);

        $this->byId('submit')
            ->click();

        $msg_displayed    = $this->byId('uploaded')
            ->displayed();

        $this->assertNotEmpty($msg_displayed);
    }
}

Test for file upload cannot run in CI

Test for file upload cannot run in CI


<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait informatio
 */
class Traits extends \WebService {

    /**
     * @param $querydata[]
     * @returns array of traits
     */
    public function execute($querydata) {
    }
}

?>

<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait informatio
 */
class Traits extends \WebService {

    /**
     * @param $querydata[]
     * @returns array of traits
     */
    public function execute($querydata) {
        global $db;
        $data = array();
        $search = "%%";
        if(in_array('search', array_keys($querydata))){
            $search = "%".$querydata['search']."%";
        }
        $query_get_traits = <<<EOF
SELECT *
    FROM trait_entry LIMIT 10;
EOF;
        $stm_get_traits = $db->prepare($query_get_traits);
        $stm_get_traits->execute();

        while ($row = $stm_get_traits->fetch(PDO::FETCH_ASSOC)) {
            var_dump($row);
        }

        return data;
    }
}

?>

Add simple sql query which returns all columns of trait_entry


<?php
/**
 * @package    hubzero-cms
 * @copyright  Copyright 2005-2019 HUBzero Foundation, LLC.
 * @license    http://opensource.org/licenses/MIT MIT
 */

// No direct access
defined('_HZEXEC_') or die();

?>
<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
<input type="hidden" name="alias" value="<?php echo $this->model->get('alias'); ?>" />
<input type="hidden" name="pid" id="pid" value="<?php echo $this->model->get('id'); ?>" />
<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
<input type="hidden" name="task" value="save" />
<input type="hidden" name="setup" id="insetup" value="<?php echo $this->model->inSetup() ? 1 : 0; ?>" />
<input type="hidden" name="active" value="<?php echo $this->section; ?>" />
<input type="hidden" name="step" id="step" value="<?php echo $this->step; ?>" />
<input type="hidden" name="gid" value="<?php echo $this->model->get('owned_by_group') ? $this->model->get('owned_by_group') : 0; ?>" />

<?php echo Html::input('token'); ?>
<?php echo Html::input('honeypot');

<?php
/**
 * @package    hubzero-cms
 * @copyright  Copyright 2005-2019 HUBzero Foundation, LLC.
 * @license    http://opensource.org/licenses/MIT MIT
 */

// No direct access
defined('_HZEXEC_') or die();

?>
<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
<input type="hidden" name="alias" value="<?php echo $this->model->get('alias'); ?>" />
<input type="hidden" name="pid" id="pid" value="<?php echo $this->model->get('id'); ?>" />
<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
<input type="hidden" name="task" value="save" />
<input type="hidden" name="setup" id="insetup" value="<?php echo $this->model->inSetup() ? 1 : 0; ?>" />
<input type="hidden" name="active" value="<?php echo $this->section; ?>" />
<input type="hidden" name="access" value="<?php echo $this->model->get('access'); ?>" />
<input type="hidden" name="step" id="step" value="<?php echo $this->step; ?>" />
<input type="hidden" name="gid" value="<?php echo $this->model->get('owned_by_group') ? $this->model->get('owned_by_group') : 0; ?>" />

<?php echo Html::input('token'); ?>
<?php echo Html::input('honeypot');

Use the default access value when creating a project


<?php

class HomepageTest extends TestCase {

    /**
     * A basic functional test of the homepage.
     *
     * @return void
     */
    public function testHomepageGetResponse()
    {
        $crawler = $this->client->request('GET', '/');

        $this->assertTrue($this->client->getResponse()->isOk());
    }

}

<?php

class HomepageTest extends TestCase {

    /**
     * A basic functional test of the homepage.
     *
     * @return void
     */
    public function testHomepageGetResponse()
    {
        $this->client->request('GET', '/');

        $this->assertTrue($this->client->getResponse()->isOk());
    }

}

Remove unused variable from Homepage test


<?php

namespace kamranahmedse;

/**
 * Geocode
 *
 * A wrapper around Google's Geocode API that parses the address,
 * to get different details regarding the address
 *
 * @author Kamran Ahmed <kamranahmed.se@gmail.com>
 * @version 0.1
 * @license http://www.opensource.org/licenses/MIT
 */
class Geocode
{
    protected $address;
    protected $latitude;
    protected $longitude;
    protected $country;
    protected $town;

    /**
     * Constructor
     *
     * @param string $address The address that is to be parsed
     */
    public function __construct( $address = '' )
    {
        $this->fetchAddressDetail( $address );
    }

    public function fetchAddressDetail( $address )
    {
        if ( !empty($address) ) {
            // Send a request to google API
        } else {
            return false;
        }
    }

    /**
     * @return string the full file name
     */
    public function __toString()
    {

    }
}

<?php

namespace kamranahmedse;

/**
 * Geocode
 *
 * A wrapper around Google's Geocode API that parses the address,
 * to get different details regarding the address
 *
 * @author Kamran Ahmed <kamranahmed.se@gmail.com>
 * @version 0.1
 * @license http://www.opensource.org/licenses/MIT
 */
class Geocode
{
    /**
     * API URL through which the address will be obtained.
     */
    private $service_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=";

    /**
     * Array containing the query results
     */
    private $service_results = array();

    protected $address = '';
    protected $latitude = '';
    protected $longitude = '';
    protected $country = '';
    protected $town = '';

    /**
     * Constructor
     *
     * @param string $address The address that is to be parsed
     */
    public function __construct( $address = '' )
    {
        $this->fetchAddressDetail( $address );
    }

    public function fetchAddressDetail( $address )
    {
        $this->address = $address;

        if ( !empty($address) ) {

            $this->service_url .= urlencode( $address );

            $ch = curl_init();

            curl_setopt( $ch, CURLOPT_URL, $this->service_url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

            $this->service_results = json_decode(curl_exec($ch), true);

        } else {
            return false;
        }
    }

    /**
     * @return string the full file name
     */
    public function __toString()
    {

    }
}

Address detail being fetched from the Google's API


<?php namespace JwtAuth;

use Illuminate\Support\ServiceProvider;

class JwtAuthServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {

    }

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

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

}

<?php namespace JwtAuth;

use Illuminate\Support\ServiceProvider;

class JwtAuthServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Find path to the package
        $componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName();
        $componenentsPath = dirname($componenentsFileName);

        $this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth');

        // include $componenentsPath . '/../routes.php';

    }

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

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

}

Update service provider Applications , JwtAuth


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\Commands\ResetPassword;
use App\Http\Controllers\AbstractController;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Str;

/**
 * @Middleware("guest")
 */
class ResetPasswordController extends AbstractController
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $command = new ResetPassword(
            $user->setFromArray([
                'password'       => bcrypt($password),
                'remember_token' => Str::random(60),
            ])
        );

        $result = $this->sendCommandToBusHelper($command);
        $this->isCommandError($result);
    }

    /**
     * @inheritdoc
     *
     * @return array
     */
    protected function getValidationRules(): array
    {
        return [];
    }

    /**
     * @inheritdoc
     *
     * @return array
     */
    protected function getValidationMessages(): array
    {
        return [];
    }
}

Add guest middleware as an annotation and remove the constructor method. Extend from the AbstractController and override the resetPassword method to use the command bus for resetting a password.


#!/usr/bin/env php
<?php

use DDelrio1986\Superheroes\Superheroes;

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

$options = getopt('a', ['all']);

$superheroes = new Superheroes;

if (count($options)) {
    array_walk($superheroes->all, function ($superhero) {
        echo $superhero . "\n";
    });
} else {
    echo $superheroes->random() . "\n";
}

#!/usr/bin/env php
<?php

use DDelrio1986\Superheroes\Superheroes;

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

$options = getopt('a', ['all']);

$superheroes = new Superheroes;

// Print all superheroes.
if (count($options)) {
    array_walk($superheroes->all, function ($superhero) {
        echo $superhero . "\n";
    });

// Print one random superhero.
} else {
    echo $superheroes->random() . "\n";
}

Add a bit of comments

Add a bit of comments


<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r($data);

}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r(json_decode($data, 'utf-8'));
	exit;
}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

Improve DiscoJuice Feed debug view

Improve DiscoJuice Feed debug view

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@2900 44740490-163a-0410-bde0-09ae8108e29a


<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
define('REQUEST_MICROTIME', microtime(true));
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
define('REQUEST_MICROTIME', microtime(true));
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}

define('DS', DIRECTORY_SEPARATOR);
// Define root path
$parts = explode(DS, realpath(dirname(__FILE__) . '/..'));
define("CON_ROOT_PATH", implode(DS, $parts));
$parts = explode(DS, realpath(dirname(__FILE__)));
define("DOCUMENT_ROOT", implode(DS, $parts));

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

Add global constants document root and root directory path

Change-Id: I12458ba161c2c04569e0002cdede6a59dc5c5e23


<?php

error_reporting(E_ALL | E_STRICT);

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

// Load our dependencies
$container = require_once __DIR__.'/../bootstrap/dependencies.php';

// Run the imageRack server
$server = new Diarmuidie\ImageRack\Server($container);

// Array of available templates with claaback to return a processor
// that implements Diarmuidie\ImageRack\Image\TemplateInterface
$templates = array(
    'small' => function () {
        return new Templates\Small();
    }
);

// Set the valid templates
$server->setTemplates($templates);

// Optionally set the not found response content
$server->notFound(function ($response) {
    $response->setBody('Image not found.');
});

$server->run();

<?php

error_reporting(E_ALL | E_STRICT);

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

// Load our dependencies
$container = require_once __DIR__.'/../bootstrap/dependencies.php';

// Run the imageRack server
$server = new Diarmuidie\ImageRack\Server(
    $container['source'],
    $container['cache'],
    $container['imageManager']
);

// Array of available templates with claaback to return a processor
// that implements Diarmuidie\ImageRack\Image\TemplateInterface
$templates = array(
    'small' => function () {
        return new Templates\Small();
    }
);

// Set the valid templates
$server->setTemplates($templates);

// Optionally set the not found response content
$server->notFound(function ($response) {
    $response->setBody('Image not found.');
});

$server->run();

Change how dependencies are injected

Change how dependencies are injected


<?php

namespace hiapi\Core\Console\Formatter;

use Lcobucci\ContentNegotiation\Formatter\ContentOnly;

class Php extends ContentOnly
{
    public function formatContent($content, $attributes = []): string
    {
        return var_export($content, true);
    }
}

<?php

namespace hiapi\Core\Console\Formatter;

use Exception;
use Lcobucci\ContentNegotiation\Formatter\ContentOnly;

class Php extends ContentOnly
{
    public function formatContent($content, $attributes = []): string
    {
        if ($content instanceof Exception) {
            throw $content;
        }

        return var_export($content, true);
    }
}

Fix request to `index.php` in URL

Fix request to `index.php` in URL


<?php

namespace JoeStewart\RoboDrupalVM\Task;

use Robo\Result;
use Robo\Task\BaseTask;
use Robo\Common\ExecOneCommand;
use Robo\Contract\CommandInterface;
use Robo\Contract\TaskInterface;
use Robo\Contract\PrintedInterface;
use Robo\Exception\TaskException;
use Robo\Common\Timer;

class Vm extends \JoeStewart\RoboDrupalVM\Task\Base
{
    use Timer;

    /**
     * @return Result
     */
    public function run()
    {
        return new Result(
            $this,
            0,
            'Vm'
        );
    }
}

<?php

namespace JoeStewart\RoboDrupalVM\Task;

use Robo\Result;
use Robo\Task\BaseTask;
use Robo\Common\ExecOneCommand;
use Robo\Contract\CommandInterface;
use Robo\Contract\TaskInterface;
use Robo\Contract\PrintedInterface;
use Robo\Exception\TaskException;

class Vm extends \JoeStewart\RoboDrupalVM\Task\Base
{

    /**
     * @return Result
     */
    public function run()
    {
        return new Result(
            $this,
            0,
            'Vm'
        );
    }
}

Remove Timer as we are extending Base Task now


<?php

namespace Phrest\API;

trait HateoasResponseGeneratorAwareTrait
{
    /**
     * @var HateoasResponseGenerator
     */
    protected $hateoasResponseGenerator;

    public function setHateoasResponseGenerator(HateoasResponseGenerator $hateoasResponseGenerator)
    {
        $this->hateoasResponseGenerator = $hateoasResponseGenerator;
    }

    /**
     * Generates a JSON HATEOAS response based on the given data and annotations.
     * @param $data
     * @return \Psr\Http\Message\ResponseInterface
     */
    protected function generateHateoasResponse($data): \Psr\Http\Message\ResponseInterface
    {
        return $this->hateoasResponseGenerator->generate($data);
    }
}

<?php

namespace Phrest\API;

trait HateoasResponseGeneratorAwareTrait
{
    /**
     * @var HateoasResponseGenerator
     */
    protected $hateoasResponseGenerator;

    public function setHateoasResponseGenerator(HateoasResponseGenerator $hateoasResponseGenerator)
    {
        $this->hateoasResponseGenerator = $hateoasResponseGenerator;
    }

    /**
     * @param $data
     * @param int $httpStatusCode
     * @param array $headers
     * @return \Psr\Http\Message\ResponseInterface
     */
    protected function generateHateoasResponse($data, int $httpStatusCode = 200, array $headers = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->hateoasResponseGenerator->generate($data, $httpStatusCode, $headers);
    }
}

Allow to pass a http status code and header to generateHateoasResponse


<?php

namespace RCatlin\Blog\Behavior;

use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Http\Response;

trait RenderError
{
    public function renderNotFound(Response $response, $message)
    {
        Assertion::string($message);

        $response->setStatusCode(404);
        $response->setResult(ResourceFactory::result(['message' => $message]));

        return $response;
    }

    public function renderBadRequest(Response $response, $message)
    {
        Assertion::string($message);

        $response->setStatusCode(400);
        $response->setResult(ResourceFactory::result(['message' => $message]));

        return $response;
    }

    public function renderValidationError(Response $response, array $errors)
    {
        $response->setStatusCode(400);
        $response->setResult(ResourceFactory::result(['errors' => $errors]));

        return $response;
    }
}

<?php

namespace RCatlin\Blog\Behavior;

use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Response;

trait RenderError
{
    public function renderNotFound(Response $response, $message)
    {
        Assertion::string($message);

        $response->setStatusCode(404);
        $response->setResult(ResourceFactory::result(['message' => $message]));

        return $response;
    }

    public function renderBadRequest(Response $response, $message)
    {
        Assertion::string($message);

        $response->setStatusCode(400);
        $response->setResult(ResourceFactory::result(['message' => $message]));

        return $response;
    }

    public function renderValidationError(Response $response, array $errors)
    {
        $response->setStatusCode(400);
        $response->setResult(ResourceFactory::result(['errors' => $errors]));

        return $response;
    }
}

Use correct Response namespace in RendorError trait


<?php

use Flarum\Event\ConfigureLocales;
use Illuminate\Contracts\Events\Dispatcher;

return function (Dispatcher $events) {
    $events->listen(ConfigureLocales::class, function (ConfigureLocales $event) {
        $event->loadLanguagePackFrom(__DIR__);
    });
};

<?php

use Flarum\Event\ConfigureLocales;
use Illuminate\Contracts\Events\Dispatcher;

return function (Dispatcher $events) {
    $events->listen(ConfigureLocales::class, function(ConfigureLocales $event) {
        $name = $title = basename(__DIR__);

        if (file_exists($manifest = __DIR__.'/composer.json')) {
            $json = json_decode(file_get_contents($manifest), true);

            if (empty($json)) {
                throw new RuntimeException("Error parsing composer.json in $name: ".json_last_error_msg());
            }

            $locale = array_get($json, 'extra.flarum-locale.code');
            $title = array_get($json, 'extra.flarum-locale.title', $title);
        }

        if (! isset($locale)) {
            throw new RuntimeException("Language pack $name must define \"extra.flarum-locale.code\" in composer.json.");
        }

        $event->locales->addLocale($locale, $title);

        if (! is_dir($localeDir = __DIR__.'/locale')) {
            throw new RuntimeException("Language pack $name must have a \"locale\" subdirectory.");
        }

        if (file_exists($file = $localeDir.'/config.js')) {
            $event->locales->addJsFile($locale, $file);
        }

        foreach (new DirectoryIterator($localeDir) as $file) {
            if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
                $event->locales->addTranslations($locale, $file->getPathname());
            }
        }
    });
};

Fix fatal error in beta4

Fix fatal error in beta4


<?php

namespace Dash;

function groupBy($input, $groupBy)
{
	assertType($input, ['iterable']);

	return reduce($input, function($grouped, $value) use ($groupBy) {
		$key = get($value, $groupBy);
		$grouped[$key][] = $value;
		return $grouped;
	});
}

<?php

namespace Dash;

function groupBy($input, $groupBy, $defaultGroup = null)
{
	assertType($input, ['iterable']);

	return reduce($input, function($grouped, $value) use ($groupBy, $defaultGroup) {
		$key = get($value, $groupBy);
		$key = is_null($key) ? $defaultGroup : $key;
		$grouped[$key][] = $value;
		return $grouped;
	});
}

Add default value to groupby()

Add default value to groupby()

for null \$groupBy values


<?php

/**
 * Get the Space Open/Close state from external sources
 *
 * For now, only get state from the Wordpress Opening Hours plugin
 *
 * @since 0.3
 */
class Space_State
{

    public function is_open()
    {
        //TODO add cases based on external sources
        //TODO add enabled/available Opening Hours plugin check
        return $this->get_opening_hours_state();
    }

    /**
     * Get the open/close status from the Opening Hours plugin
     *
     * @return bool $is_open
     */
    private function get_opening_hours_state()
    {
        if (function_exists('is_open')){
            return is_open();
        }
        else {
            return null;
        }
    }
}

<?php

// allow to use `is_plugin_active` function
include_once(ABSPATH.'wp-admin/includes/plugin.php');

/**
 * Get the Space Open/Close state from external sources
 *
 * For now, only get state from the Wordpress Opening Hours plugin
 *
 * @since 0.3
 */
class Space_State
{
    /**
     *  Retrive the opening state of the hackerspace
     *
     * @retun boll The open/close state
     */
    public function is_open()
    {
        //TODO add more external sources and allow user to choice the source from settings
        if (is_plugin_active('wp-opening-hours/wp-opening-hours.php')) {
            return $this->get_opening_hours_state();
        }
    }

    /**
     * Get the open/close status from the Opening Hours plugin
     *
     * @return bool $is_open
     */
    private function get_opening_hours_state()
    {
        if (function_exists('is_open')){ // plugin version 1.2
            return is_open();
        }
        else {
            return null;
        }
    }
}

Add a check for activated plugins

Add a check for activated plugins


<?php

namespace Rehyved\utilities;

class StringHelper
{
    public static function endsWith(string $haystack, string $needle, bool $caseSensitive = true){
        $haystackLength = strlen($haystack);
        $needleLength = strlen($needle);
        if ($needleLength > $haystackLength) return false;
        return substr_compare($haystack, $needle, $haystackLength - $needleLength, $needleLength, $caseSensitive) === 0;
    }

    public static function equals($first, $second, bool $caseSensitive = true){
        if($caseSensitive){
            return $first === $second;
        }else{
            return mb_strtolower($first) === mb_strtolower($second);
        }
    }

    public static function startsWith($haystack, $needle, bool $caseSensitive = true)
    {
        $haystackLength = strlen($haystack);
        $needleLength = strlen($needle);
        if ($needleLength > $haystackLength) return false;
        return substr_compare($haystack, $needle, 0, $needleLength, $caseSensitive) === 0;
    }

    public static function contains($haystack, $needle, bool $caseSensitive = true){
        if(!$caseSensitive){
            return stripos($haystack, $needle);
        }
        return strpos($haystack, $needle);
}
}

<?php

namespace Rehyved\utilities;

class StringHelper
{
    public static function endsWith(string $haystack, string $needle, bool $caseSensitive = true){
        $haystackLength = strlen($haystack);
        $needleLength = strlen($needle);
        if ($needleLength > $haystackLength) return false;
        return substr_compare($haystack, $needle, $haystackLength - $needleLength, $needleLength, $caseSensitive) === 0;
    }

    public static function equals($first, $second, bool $caseSensitive = true){
        if($caseSensitive){
            return $first === $second;
        }else{
            return mb_strtolower($first) === mb_strtolower($second);
        }
    }

    public static function startsWith($haystack, $needle, bool $caseSensitive = true)
    {
        $haystackLength = strlen($haystack);
        $needleLength = strlen($needle);
        if ($needleLength > $haystackLength) return false;
        return substr_compare($haystack, $needle, 0, $needleLength, $caseSensitive) === 0;
    }

    public static function contains($haystack, $needle, bool $caseSensitive = true){
        if(!$caseSensitive){
            return stripos($haystack, $needle) !== false;
        }
        return strpos($haystack, $needle) !== false;
}
}

Fix for function not returning boolean value


<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Output JSON format
echo $api->get_json($worker->getWorkers($user_id));

// Supress master template
$supress_master = 1;
?>

<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Fetch data interval from admin settings
if ( ! $interval = $setting->getValue('statistics_ajax_data_interval')) $interval = 300;

// Output JSON format
echo $api->get_json($worker->getWorkers($user_id, $interval));

// Supress master template
$supress_master = 1;
?>

Use data interval on getuserworkers

[IMPROVED] Use data interval on getuserworkers


{{--
    $breadcrumbs => array // [['display_name', 'relative_url']]
--}}

        @foreach($breadcrumbs as $key=>$crumb)
            @if($key == 0)

                    @svg('home', 'w-4 h-4'){{ strip_tags($crumb['display_name']) }}

            @elseif($key == (count($breadcrumbs) - 1))

                    {{ $crumb['display_name'] }}
            @else

                {{ $crumb['display_name'] }}

            @endif

        @endforeach

{{--
    $breadcrumbs => array // [['display_name', 'relative_url']]
--}}

        @foreach($breadcrumbs as $key=>$crumb)
            @if($key == 0)

                    @svg('home', 'w-4 h-4')

            @elseif($key == (count($breadcrumbs) - 1))

                    {{ $crumb['display_name'] }}
            @else

                {{ $crumb['display_name'] }}

            @endif

        @endforeach

Remove the visually hidden so it doesn't read Home twice


; <?php /*

[admin]

default                 = On

[editor]

default                 = Off
admin                   = On
admin/edit              = On
admin/delete            = On
content/member          = On
content/private         = On
blog                    = On
blocks                  = On
filemanager             = On

[member]

default                 = Off
member                  = On

; */ ?>

; <?php /*

[admin]

default                 = On

[editor]

default                 = Off
admin                   = On
admin/edit              = On
admin/delete            = On
content/member          = On
content/private         = On
blog                    = On
blocks                  = On
filemanager             = On

[member]

default                 = Off
content/member          = On

; */ ?>

Allow members to have an access to members' content by default.


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Generally will be localhost if you're querying from the machine that Mongo is installed on
$config['mongo_host'] = "localhost";

// Generally will be 27017 unless you've configured Mongo otherwise
$config['mongo_port'] = 27017;

// The database you want to work from (required)
$config['mongo_db'] = "10layer";

// Leave blank if Mongo is not running in auth mode
$config['mongo_username'] = "";
$config['mongo_password'] = "";

// Persistant connections
$config['mongo_persist'] = TRUE;

$config['mongo_persist_key'] = 'ci_mongo_persist';

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Generally will be localhost if you're querying from the machine that Mongo is installed on
$config['mongo_host'] = "localhost";

// Generally will be 27017 unless you've configured Mongo otherwise
$config['mongo_port'] = 27017;

// The database you want to work from (required)
$config['mongo_db'] = "tenlayer";

// Leave blank if Mongo is not running in auth mode
$config['mongo_username'] = "";
$config['mongo_password'] = "";

// Persistant connections
$config['mongo_persist'] = TRUE;

$config['mongo_persist_key'] = 'ci_mongo_persist';

Change default db from 10layer to tenlayer


<?php namespace ProcessWire\GraphQL\Type;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Type\Traits\CacheTrait;

class AuthResponseType
{
  use CacheTrait;
  public static function type()
  {
    return self::cache('default', function () {
      return new ObjectType([
        'name' => 'AuthResponse',
        'description' => 'Object type that represents the authentication response.',
        'fields' => [
          'statusCode' => [
            'type' => Type::nonNull(Type::int()),
            'description' => 'The authentication status code. E.g. 200 if successful.',
          ],
          'message' => [
            'type' => Type::nonNull(Type::string()),
            'description' => 'Homan readable message of the authentication reponse. E.g. "successful login!"',
          ],
        ]
      ]);
    });
  }
}

<?php namespace ProcessWire\GraphQL\Type;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Cache;

class AuthResponseType
{
  public static $name = 'AuthResponse';

  public static function type()
  {
    return Cache::type(self::$name, function () {
      return new ObjectType([
        'name' => self::$name,
        'description' => 'Object type that represents the authentication response.',
        'fields' => [
          'statusCode' => [
            'type' => Type::nonNull(Type::int()),
            'description' => 'The authentication status code. E.g. 200 if successful.',
          ],
          'message' => [
            'type' => Type::nonNull(Type::string()),
            'description' => 'Homan readable message of the authentication reponse. E.g. "successful login!"',
          ],
        ]
      ]);
    });
  }
}

Update caching for AuthResponse type.

Update caching for AuthResponse type.


<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

class CallbackCollection extends Collection
{
    /** @var callable */
    private $callback;

    public function __construct(iterable $items, callable $callback)
    {
        if (is_array($items)) {
            $items = new \ArrayIterator($items);
        }

        parent::__construct($items);
        $this->callback = $callback;
    }

    public function current()
    {
        return call_user_func($this->callback, $this, $this->key());
    }
}

<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

class CallbackCollection extends Collection
{
    /** @var callable */
    private $callback;

    public function __construct(iterable $items, callable $callback)
    {
        if (is_array($items)) {
            $items = new \ArrayIterator($items);
        }

        parent::__construct($items);
        $this->callback = $callback;
    }

    public function current()
    {
        return call_user_func($this->callback, parent::current(), $this->key());
    }
}

Revert "Return self instead of parent to allow nested resolutions"

This reverts commit ae2a25ad2373588c52b3a3df025f1f99e533f769.


<?php

return [
    /**
     * The driver to use to store the session (defaults to `file`)
     */
    'driver' => getenv('SESSION_DRIVER') ?? 'file',

    /**
     * The name of the cookie that is set in a visitors browser
     */
    'cookie' => getenv('SESSION_COOKIE') ?? 'lumberjack_session',

    /**
     * How long the session will persist for
     */
    'lifetime' => getenv('SESSION_LIFETIME') ?? 120,

    /**
     * The URL path that will be considered valid for the cookie. Normally this is the
     * root of the domain but might need to be changed if serving WordPress from a sub-directory.
     */
    'path' => '/',

    /**
     * The domain that the cookie is valid for
     */
    'domain' => getenv('SESSION_DOMAIN') ?? null,

    /**
     * If true, the cookie will only be sent if the connection is done over HTTPS
     */
    'secure' => getenv('SESSION_SECURE_COOKIE') ?? false,

    /**
     * If true, JavaScript will not be able to access the cookie data
     */
    'http_only' => true,

    /**
     * Should the session data be encrypted when stored?
     */
    'encrypt' => false,

    /**
     * When using the `file` driver this is the path to which session data is stored.
     * If none is specified the default PHP location will be used.
     */
    'files' => false,
];

<?php

return [
    /**
     * The driver to use to store the session (defaults to `file`)
     */
    'driver' => getenv('SESSION_DRIVER') ?: 'file',

    /**
     * The name of the cookie that is set in a visitors browser
     */
    'cookie' => getenv('SESSION_COOKIE') ?: 'lumberjack_session',

    /**
     * How long the session will persist for
     */
    'lifetime' => getenv('SESSION_LIFETIME') ?: 120,

    /**
     * The URL path that will be considered valid for the cookie. Normally this is the
     * root of the domain but might need to be changed if serving WordPress from a sub-directory.
     */
    'path' => '/',

    /**
     * The domain that the cookie is valid for
     */
    'domain' => getenv('SESSION_DOMAIN') ?: null,

    /**
     * If true, the cookie will only be sent if the connection is done over HTTPS
     */
    'secure' => getenv('SESSION_SECURE_COOKIE') ?: false,

    /**
     * If true, JavaScript will not be able to access the cookie data
     */
    'http_only' => true,

    /**
     * Should the session data be encrypted when stored?
     */
    'encrypt' => false,

    /**
     * When using the `file` driver this is the path to which session data is stored.
     * If none is specified the default PHP location will be used.
     */
    'files' => false,
];

Fix defaults for Session config

Fix defaults for Session config


<?php

namespace PatternSeek\ECommerce\ViewState;

use PatternSeek\ComponentView\ViewState\ViewState;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class AddressState
 * @package PatternSeek\ECommerce
 */
class AddressState extends ViewState
{

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\NotBlank()
     */
    public $addressLine1;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $addressLine2;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\NotBlank()
     */
    public $townOrCity;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $stateOrRegion;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $postCode;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $countryString;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\NotBlank()
     * @Assert\Length(min="2", max="2")
     */
    public $countryCode;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\Choice(choices = {"edit", "view"})
     */
    public $mode = 'view';

}

<?php

namespace PatternSeek\ECommerce\ViewState;

use PatternSeek\ComponentView\ViewState\ViewState;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class AddressState
 * @package PatternSeek\ECommerce
 */
class AddressState extends ViewState
{

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $addressLine1;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $addressLine2;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $townOrCity;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $stateOrRegion;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $postCode;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     */
    public $countryString;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\Length(min="2", max="2")
     */
    public $countryCode;

    /**
     * @var string
     *
     * @Assert\Type(type="string")
     * @Assert\Choice(choices = {"edit", "view"})
     */
    public $mode = 'view';

}

Remove required fields from address state


#!/usr/bin/env php
<?php
// vim: set ai ts=4 sw=4 ft=php:
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2013 Schmooze Com Inc.
//
// Dashboard Scheduler.
// Runs every minute.
//

$lockfile = "/tmp/scheduler-lock";

// Sleep to fix crazy issues with large VM hosting providers
sleep(mt_rand(1,30));

// Create a lock to make sure no more than one instance of this
// program can be running on a machine at a time
$fh = fopen($lockfile, "a");
if (!$fh || !flock($fh, LOCK_EX|LOCK_NB)) {
	// Unable to lock, we're already running.
	exit;
}

// Start quickly.
$bootstrap_settings['freepbx_auth'] = false;  // Just in case.
$restrict_mods = true; // Takes startup from 0.2 seconds to 0.07 seconds.
include '/etc/freepbx.conf';
// Run the trigger
\FreePBX::Dashboard()->runTrigger();

// remove lockfile, and then close handle to release kernel lock
unlink($lockfile);
fclose($fh);
?>

#!/usr/bin/env php
<?php
// vim: set ai ts=4 sw=4 ft=php:
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2013 Schmooze Com Inc.
//
// Dashboard Scheduler.
// Runs every minute.
//

// Start quickly.
$bootstrap_settings['freepbx_auth'] = false;  // Just in case.
$restrict_mods = true; // Takes startup from 0.2 seconds to 0.07 seconds.
include '/etc/freepbx.conf';

$lockfile = \FreePBX::Config()->get('ASTRUNDIR')."/scheduler.lock";

// Sleep to fix crazy issues with large VM hosting providers
sleep(mt_rand(1,30));

// Create a lock to make sure no more than one instance of this
// program can be running on a machine at a time
$fh = fopen($lockfile, "a");
if (!$fh || !flock($fh, LOCK_EX|LOCK_NB)) {
	// Unable to lock, we're already running.
	exit;
}

// Run the trigger
\FreePBX::Dashboard()->runTrigger();

// remove lockfile, and then close handle to release kernel lock
unlink($lockfile);
fclose($fh);
?>

Use ASTRUNDIR, not /tmp, for the lockfile

Use "scheduler.lock" as the lockfile name.
Need to read in the configuration files first,
so we know which directory will hold the lock.


<?php

namespace Hodor\MessageQueue;

use PHPUnit_Framework_TestCase;
use RuntimeException;

/**
 * @coversDefaultClass Hodor\MessageQueue\OutgoingMessage
 */
class OutgoingMessageTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::getEncodedContent
     */
    public function testEncodedContentCanBeRetrieved()
    {
        $content = ['name' => 'Hey', 'id' => 123, 'active' => true];

        $message = new OutgoingMessage($content);
        $this->assertSame(
            json_encode($content),
            $message->getEncodedContent()
        );
    }

    /**
     * @covers ::__construct
     * @covers ::getEncodedContent
     * @expectedException RuntimeException
     */
    public function testOver100LevelsOfNestingThrowsAnException()
    {
        $message = 123;
        for ($i = 1; $i <= 101; ++$i) {
            $message = ['message' => $message];
        }

        $message = new OutgoingMessage($message);
        $message->getEncodedContent();
    }
}

<?php

namespace Hodor\MessageQueue;

use PHPUnit_Framework_TestCase;
use RuntimeException;

/**
 * @coversDefaultClass Hodor\MessageQueue\OutgoingMessage
 */
class OutgoingMessageTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::getEncodedContent
     */
    public function testEncodedContentCanBeRetrieved()
    {
        $content = ['name' => 'Hey', 'id' => 123, 'active' => true];

        $message = new OutgoingMessage($content);
        $this->assertSame(
            json_encode($content),
            $message->getEncodedContent()
        );
    }

    /**
     * @covers ::__construct
     * @covers ::getEncodedContent
     */
    public function testEncodedContentCanBeRetrievedMultipleTimes()
    {
        $content = ['name' => 'Hey', 'id' => 123, 'active' => true];

        $message = new OutgoingMessage($content);
        $this->assertSame(
            $message->getEncodedContent(),
            $message->getEncodedContent()
        );
    }

    /**
     * @covers ::__construct
     * @covers ::getEncodedContent
     * @expectedException RuntimeException
     */
    public function testOver100LevelsOfNestingThrowsAnException()
    {
        $message = 123;
        for ($i = 1; $i <= 101; ++$i) {
            $message = ['message' => $message];
        }

        $message = new OutgoingMessage($message);
        $message->getEncodedContent();
    }
}

Test outgoing message can be retrieved repeatedly


<?php namespace Philipbrown\WorldPay;

use Illuminate\Support\ServiceProvider;

class WorldPayServiceProvider extends ServiceProvider {

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

  /**
   * Bootstrap the application events.
   *
   * @return void
   */
  public function boot()
  {
    $this->package('philipbrown/worldpay');
  }

  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register()
  {
    $this->app['worldpay'] = $this->app->share(function($app)
    {
      return new WorldPay;
    });
    $this->app->booting(function()
    {
      $loader = \Illuminate\Foundation\AliasLoader::getInstance();
      $loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay');
    });
  }

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

}

<?php namespace Philipbrown\WorldPay;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;

class WorldPayServiceProvider extends ServiceProvider {

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

  /**
   * Bootstrap the application events.
   *
   * @return void
   */
  public function boot()
  {
    $this->package('philipbrown/worldpay');
  }

  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register()
  {
    $this->app['worldpay'] = $this->app->share(function($app)
    {
      $wp = new PhilipBrown\WorldPay\WorldPay;

      $wp->setConfig(Config::get('worldpay'));
    });
    $this->app->booting(function()
    {
      $loader = \Illuminate\Foundation\AliasLoader::getInstance();
      $loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay');
    });
  }

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

}

Add Laravel config into Service Provider


<?php

namespace App\Http\Controllers\User;

use Session;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function showLoginPage(Request $request){
        return view('user.login');
    }

    public static function isLoggedIn(){
        return (Session::get('user_logged_in') === true);
    }
    }
}

<?php

namespace App\Http\Controllers\User;

use Session;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function showLoginPage(Request $request){
        return view('user.login');
    }

    public static function isLoggedIn(){
        return (Session::get('user_logged_in') === true);
    }

    public function showLogoutPage(){
        return view('user.logout');
    }

    public function handleLogout(){
        Session::flush();
        Session::regenerate();

        return redirect('/');
    }
}

Create method to render logout page Create method to log the user out