<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>about cheeseb.us radio</title>
    <link rel="stylesheet" href="/stylesheet.css">

about cheeseb.us radio

cheeseb.us radio cycles through a handpicked rotation of songs. the song database updates at least once a month.

albums prohibiting unauthorized copying and/or broadcasting are excluded from the rotation to the best extent possible.

on top of that, cheeseb.us radio operates on a NonCommercial basis.

(source code and other juicy backend stuff will be out in the near future. ^^,)

other questions? email

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>about cheeseb.us radio</title>
    <link rel="stylesheet" href="/stylesheet.css">

about cheeseb.us radio

cheeseb.us radio cycles through a handpicked rotation of songs. the song database updates at least once a month.

albums prohibiting unauthorized copying and/or broadcasting are excluded from the rotation to the best extent possible.

on top of that, cheeseb.us radio operates on a NonCommercial basis.

the source code is available on GitHub.

other questions? email

Add reference to source code

Add reference to source code


<?php
/**
 * @package BC Security
 */

namespace BlueChip\Security\Tests\Cases;

use BlueChip\Security\Plugin;

class PluginTest extends \BlueChip\Security\Tests\TestCase
{
    /**
     * @var \BlueChip\Security\Plugin
     */
    protected $bc_security;

    /**
     * Setup test.
     */
    public function setUp() {
        global $wpdb;

        parent::setUp();

        $this->bc_security = new Plugin('', $wpdb);
    }

    /**
     * Test class instances.
     */
    function test_instances() {
        $this->assertInstanceOf(Plugin::class, $this->bc_security);
        $this->assertInstanceOf(\wpdb::class, $this->readAttribute($this->bc_security, 'wpdb'));
    }
}

<?php
/**
 * @package BC Security
 */

namespace BlueChip\Security\Tests\Cases;

use BlueChip\Security\Plugin;

class PluginTest extends \BlueChip\Security\Tests\TestCase
{
    /**
     * @var \BlueChip\Security\Plugin
     */
    protected $bc_security;

    /**
     * Setup test.
     */
    public function setUp()
    {
        global $wpdb;

        parent::setUp();

        $this->bc_security = new Plugin('', $wpdb);
    }

    /**
     * Test class instances.
     */
    public function test_instances()
    {
        $this->assertInstanceOf(Plugin::class, $this->bc_security);
        $this->assertInstanceOf(\wpdb::class, $this->readAttribute($this->bc_security, 'wpdb'));
    }
}

Fix PSR compliance in test files.

Fix PSR compliance in test files.


<?php

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

class CreateDuesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dues', function (Blueprint $table) {
            $table->increments('id');
            $table->boolean('eligible_for_shirt')->default(false);
            $table->boolean('eligible_for_polo')->default(false);
            $table->boolean('received_shirt')->default(false);
            $table->boolean('received_polo')->default(false);
            $table->timestamp('effective_start');
            $table->timestamp('effective_end');
            $table->unsignedInteger('payment_id');

            $table->foreign('payment_id')->references('id')->on('payments');
        });
    }

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

<?php

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

class CreateDuesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dues', function (Blueprint $table) {
            $table->increments('id');
            $table->boolean('eligible_for_shirt')->default(false);
            $table->boolean('eligible_for_polo')->default(false);
            $table->boolean('received_shirt')->default(false);
            $table->boolean('received_polo')->default(false);
            $table->timestamp('effective_start');
            $table->timestamp('effective_end');
            $table->unsignedInteger('payment_id')->nullable();
            $table->timestamps();

            $table->foreign('payment_id')->references('id')->on('payments');
        });
    }

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

Allow nullable payment_id for pending payment purposes; Add standard eloquent timestamps


<?php
class Kwf_Assets_Util_Trl
{
    //returns replacement used for js trl strings
    //used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
    public static function getJsReplacement($trlElement)
    {
        $b = $trlElement['before'];
        $fn = substr($b, 0, strpos($b, '('));
        $key = $trlElement['type'].'.'.$trlElement['source'];
        if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
        $key .= '.'.str_replace("'", "\\'", $trlElement['text']);
        if (preg_match('#^([a-z]+\.)trl#i', $b, $m)) {
            $replace = substr($b, 0, strlen($m[1]));
        }
        if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
            $replace .= "_kwfTrlp";
        } else {
            $replace .= "_kwfTrl";
        }
        $replace .= "('$key', ".substr($b, strpos($b, '(')+1);

        unset($trlElement['before']);
        unset($trlElement['linenr']);
        unset($trlElement['error_short']);

        return array(
            'before' => $b,
            'replace' => $replace,
            'trlElement' => (object)$trlElement
        );
    }
}

<?php
class Kwf_Assets_Util_Trl
{
    //returns replacement used for js trl strings
    //used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
    public static function getJsReplacement($trlElement)
    {
        $b = $trlElement['before'];
        $fn = substr($b, 0, strpos($b, '('));
        $key = $trlElement['type'].'.'.$trlElement['source'];
        if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
        $key .= '.'.str_replace("'", "\\'", $trlElement['text']);
        $replace = '';
        if (preg_match('#^([a-z]+\.)trl#i', $b, $m)) {
            $replace = substr($b, 0, strlen($m[1]));
        }
        if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
            $replace .= "_kwfTrlp";
        } else {
            $replace .= "_kwfTrl";
        }
        $replace .= "('$key', ".substr($b, strpos($b, '(')+1);

        unset($trlElement['before']);
        unset($trlElement['linenr']);
        unset($trlElement['error_short']);

        return array(
            'before' => $b,
            'replace' => $replace,
            'trlElement' => (object)$trlElement
        );
    }
}

Fix error if regexp doesn't match beause trl() is used directly


<?php
/**
 * DateEnablement.php
 *
 * @copyright 2016 George D. Cooksey, III
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

namespace texdc\range;

use DateTime;

/**
 * A date-based enablement.
 *
 * @author George D. Cooksey, III
 */
final class DateEnablement implements EnablementInterface
{
    /**
     * @var DateRangeInterface
     */
    private $dateRange;

    /**
     * @param DateRangeInterface $aDateRange
     */
    public function __construct(DateRangeInterface $aDateRange)
    {
        $this->dateRange = $aDateRange;
    }

    /**
     * @param  DateTime|null $onDate optional, will default to 'now'
     * @return bool
     */
    public function isEnabled(DateTime $onDate = null) : bool
    {
        $onDate = $onDate ?: new DateTime;
        return $this->dateRange->includes($onDate);
    }
}

<?php
/**
 * DateEnablement.php
 *
 * @copyright 2016 George D. Cooksey, III
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

namespace texdc\range;

use DateTimeInterface;

/**
 * A date-based enablement.
 *
 * @author George D. Cooksey, III
 */
final class DateEnablement implements EnablementInterface
{
    /**
     * @var DateRangeInterface
     */
    private $dateRange;

    /**
     * @param DateRangeInterface $aDateRange
     */
    public function __construct(DateRangeInterface $aDateRange)
    {
        $this->dateRange = $aDateRange;
    }

    /**
     * @param  DateTimeInterface|null $onDate optional, will default to 'now'
     * @return bool
     */
    public function isEnabled(DateTimeInterface $onDate = null) : bool
    {
        return $this->dateRange->includes($onDate ?? new DateTime);
    }
}

Use DateTimeInterface and null coalescing


<?php
/**
 * StaticFile.php
 *
 * Created By: jonathan
 * Date: 26/09/2017
 * Time: 15:04
 */

namespace Stati\Entity;

use Symfony\Component\Finder\SplFileInfo;

class StaticFile extends SplFileInfo
{
    public function get($item)
    {
        if ($item === 'path') {
            return $this->getRelativePathname();
        }
        if ($item === 'modified_time') {
            return $this->getMTime();
        }
        if ($item === 'name') {
            return $this->getBasename();
        }
        if ($item === 'basename') {
            return pathinfo($this->getRelativePathname(), PATHINFO_BASENAME);
        }
        if ($item === 'extname') {
            return '.'.pathinfo($this->getRelativePathname(), PATHINFO_EXTENSION);
        }
        return null;
    }

    public function __get($item)
    {
        return $this->get($item);
    }
}

<?php
/**
 * StaticFile.php
 *
 * Created By: jonathan
 * Date: 26/09/2017
 * Time: 15:04
 */

namespace Stati\Entity;

use Symfony\Component\Finder\SplFileInfo;

class StaticFile extends SplFileInfo
{
    public function get($item)
    {
        if ($item === 'path') {
            return $this->getRelativePathname();
        }
        if ($item === 'modified_time') {
            return $this->getMTime();
        }
        if ($item === 'name') {
            return $this->getFilename();
        }
        if ($item === 'basename') {
            return pathinfo($this->getRelativePathname(), PATHINFO_BASENAME);
        }
        if ($item === 'extname') {
            return '.'.pathinfo($this->getRelativePathname(), PATHINFO_EXTENSION);
        }
        return null;
    }

    public function field_exists($item)
    {
        return in_array($item, ['path', 'modified_time', 'name', 'basename', 'extname']);
    }

    public function __get($item)
    {
        return $this->get($item);
    }
}

Return proper filename for static file

Return proper filename for static file


<?php

namespace Mtahv3\LaravelQueueSnsSqs\Queue;

use Aws\Sqs\SqsClient;
use Illuminate\Queue\SqsQueue;
use Mtahv3\LaravelQueueSnsSqs\Jobs\SnsSqsJob;

class SnsSqsQueue extends SqsQueue {

    protected $routes=[];

    /**
     * Create a new Amazon SQS queue instance.
     *
     * @param  \Aws\Sqs\SqsClient  $sqs
     * @param  string  $default
     * @param  string  $prefix
     * @return void
     */
    public function __construct(SqsClient $sqs, $default, $prefix = '', $routes)
    {
        parent::__construct($sqs, $default, $prefix);

        $this->routes=$routes;
    }

    /**
     * Pop the next job off of the queue.
     *
     * @param  string  $queue
     * @return \Illuminate\Contracts\Queue\Job|null
     */
    public function pop($queue = null)
    {
        $response = $this->sqs->receiveMessage([
            'QueueUrl' => $queue = $this->getQueue($queue),
            'AttributeNames' => ['ApproximateReceiveCount'],
        ]);

        if (count($response['Messages']) > 0) {
            return new SnsSqsJob(
                $this->container,
                $this->sqs,
                $response['Messages'][0],
                $this->connectionName,
                $queue,
                $this->routes
            );
        }
    }
}

<?php

namespace Mtahv3\LaravelQueueSnsSqs\Queue;

use Aws\Sqs\SqsClient;
use Illuminate\Queue\SqsQueue;
use Mtahv3\LaravelQueueSnsSqs\Jobs\SnsSqsJob;

class SnsSqsQueue extends SqsQueue {

    protected $routes=[];

    /**
     * Create a new Amazon SQS queue instance.
     *
     * @param  \Aws\Sqs\SqsClient  $sqs
     * @param  string  $default
     * @param  string  $prefix
     * @return void
     */
    public function __construct(SqsClient $sqs, $default, $prefix = '', $routes)
    {
        parent::__construct($sqs, $default, $prefix);

        $this->routes=$routes;
    }

    /**
     * Pop the next job off of the queue.
     *
     * @param  string  $queue
     * @return \Illuminate\Contracts\Queue\Job|null
     */
    public function pop($queue = null)
    {
        $response = $this->sqs->receiveMessage([
            'QueueUrl' => $queue = $this->getQueue($queue),
            'AttributeNames' => ['ApproximateReceiveCount'],
        ]);

        if (! is_null($response['Messages']) && count($response['Messages']) > 0) {
            return new SnsSqsJob(
                $this->container,
                $this->sqs,
                $response['Messages'][0],
                $this->connectionName,
                $queue,
                $this->routes
            );
        }
    }
}

Use null check similar to other messages validation


<?php

/*
 * This file is part of the broadway/broadway package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Broadway\Saga\Testing;

use Broadway\CommandHandling\Testing\TraceableCommandBus;
use Broadway\EventDispatcher\EventDispatcher;
use Broadway\Saga\Metadata\StaticallyConfiguredSagaMetadataFactory;
use Broadway\Saga\MultipleSagaManager;
use Broadway\Saga\State\InMemoryRepository;
use Broadway\Saga\State\StateManager;
use Broadway\UuidGenerator\UuidGeneratorInterface;
use PHPUnit_Framework_TestCase as TestCase;

class SagaScenarioTestCase extends TestCase
{
    protected function createScenario($sagaClass, UuidGeneratorInterface $uuidGenerator)
    {
        $traceableCommandBus = new TraceableCommandBus();
        $saga                = new $sagaClass($traceableCommandBus, $uuidGenerator);
        $sagaStateRepository = new InMemoryRepository();
        $sagaManager         = new MultipleSagaManager(
            $sagaStateRepository,
            array($saga),
            new StateManager($sagaStateRepository, $uuidGenerator),
            new StaticallyConfiguredSagaMetadataFactory(),
            new EventDispatcher()
        );

        return new Scenario($this, $sagaManager, $traceableCommandBus);
    }
}

<?php

/*
 * This file is part of the broadway/broadway package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Broadway\Saga\Testing;

use Broadway\CommandHandling\CommandBusInterface;
use Broadway\CommandHandling\Testing\TraceableCommandBus;
use Broadway\EventDispatcher\EventDispatcher;
use Broadway\Saga\Metadata\StaticallyConfiguredSagaMetadataFactory;
use Broadway\Saga\MultipleSagaManager;
use Broadway\Saga\SagaInterface;
use Broadway\Saga\State\InMemoryRepository;
use Broadway\Saga\State\StateManager;
use Broadway\UuidGenerator\Rfc4122\Version4Generator;
use PHPUnit_Framework_TestCase as TestCase;

abstract class SagaScenarioTestCase extends TestCase
{
    /**
     * @var Scenario
     */
    protected $scenario;

    /**
     * Create the saga you want to test in this test case
     *
     * @param CommandBusInterface $commandBus
     * @return SagaInterface
     */
    abstract protected function createSaga(CommandBusInterface $commandBus);

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

        $this->scenario = $this->createScenario();
    }

    protected function createScenario()
    {
        $traceableCommandBus = new TraceableCommandBus();
        $saga                = $this->createSaga($traceableCommandBus);
        $sagaStateRepository = new InMemoryRepository();
        $sagaManager         = new MultipleSagaManager(
            $sagaStateRepository,
            array($saga),
            new StateManager($sagaStateRepository, new Version4Generator()),
            new StaticallyConfiguredSagaMetadataFactory(),
            new EventDispatcher()
        );

        return new Scenario($this, $sagaManager, $traceableCommandBus);
    }
}

Enhance usability of scenario-based saga test case


<?php
namespace Concrete\Core\Site\Type\Controller;

use Concrete\Core\Application\Application;
use Concrete\Core\Support\Manager as CoreManager;

class Manager extends CoreManager
{

    protected $standardController = StandardController::class;

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

    protected function getStandardController()
    {
        return $this->app->make($this->standardController);
    }

    public function driver($driver = null)
    {
        if (!isset($this->customCreators[$driver]) && !isset($this->drivers[$driver])) {
            return $this->getStandardController();
        }

        return parent::driver($driver);
    }

    public function __construct(Application $application)
    {
        parent::__construct($application);
    }

}

<?php

namespace Concrete\Core\Site\Type\Controller;

use Concrete\Core\Application\Application;
use Concrete\Core\Support\Manager as CoreManager;

class Manager extends CoreManager
{
    /**
     * @var string
     */
    protected $standardController = StandardController::class;

    public function __construct(Application $application)
    {
        parent::__construct($application);
    }

    /**
     * @return $this
     */
    public function setStandardController(string $vaiue): self
    {
        $this->standardController = $vaiue;

        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @see \Illuminate\Support\Manager::driver()
     *
     * @throws \InvalidArgumentException
     *
     * @return \Concrete\Core\Site\Type\Controller\ControllerInterface
     */
    public function driver($driver = null)
    {
        if (!isset($this->customCreators[$driver]) && !isset($this->drivers[$driver])) {
            return $this->getStandardController();
        }

        return parent::driver($driver);
    }

    protected function getStandardController(): ControllerInterface
    {
        return $this->app->make($this->standardController);
    }
}

Add type hinting to Site Type controller manager


<?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
    private $model;
    private $status;
    public $successful = false;
    public $submitted = false;
    public $newId;

    public function __construct(User $model, SigninStatus $status) {
        $this->model = $model;
        $this->status = $status;
        $this->code = $code;
    }

    public function main($data) {
        $this->submitted = false;
        return true;
    }

    public function submit($data) {
        $this->submitted = true;
        if ($data['password'] !== $data['password_confirm']) return false;
        $this->newId = $this->model->save($data)->id;
        return $this->newId !== false;
    }

    public function success() {
        $this->status->setSigninID($this->newId);
        $this->successful = true;
    }
}

<?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
    private $model;
    private $status;
    public $successful = false;
    public $submitted = false;
    public $newUser;

    public function __construct(User $model, SigninStatus $status) {
        $this->model = $model;
        $this->status = $status;
    }

    public function main($data) {
        $this->submitted = false;
        return true;
    }

    public function submit($data) {
        $this->submitted = true;
        if ($data['password'] !== $data['password_confirm']) return false;
        $this->newUser = $this->model->save($data);
        return $this->newUser !== false;
    }

    public function success() {
        $this->status->setSigninID($this->newUser->id);
        $this->successful = true;
    }
}

Store new user instead of just id

Store new user instead of just id


<?php
require_once '../repository/ImageRepository.php';
/**
 * Siehe Dokumentation im DefaultController.
 */
class ImageController
{
    public function index()
    {
        $imageRepository = new ImageRepository();
        $view = new View('image_index');
        $view->title = 'Upload';
        $view->heading = 'Upload ';
        $view->image = $imageRepository->readAll();
        $view->display();
    }
    public function upload()
    {
        $imageRepository = new ImageRepository();
        $view = new View('image_upload');
        $view->title = 'Upload';
        $view->heading = 'Upload';
        $view->image = $imageRepository->readAll();
        $view->display();
    }
    public function doUpload()
    {
        if ($_POST['post']) {
            $title = $_POST['title'];
            $image = $_FILES['image']['name'];
            $image_path = $_FILES['image']['tmp_name'];
            $userid = 1;
            $imageRepository = new ImageRepository();
            if (!$imageRepository->upload($title, $image, $image_path, $userid)){
                header("Location: /image/upload");
            }else {
                header("Location: /");
            }

        }

    }
}

<?php
require_once '../repository/ImageRepository.php';
/**
 * Siehe Dokumentation im DefaultController.
 */
class ImageController
{
    public function index()
    {
        $imageRepository = new ImageRepository();
        $view = new View('image_index');
        $view->title = 'Upload';
        $view->heading = 'Upload ';
        $view->image = $imageRepository->readAll();
        $view->display();
    }
    public function upload()
    {
        $imageRepository = new ImageRepository();
        $view = new View('image_upload');
        $view->title = 'Upload';
        $view->heading = 'Upload';
        $view->image = $imageRepository->readAll();
        $view->display();
    }
    public function doUpload()
    {
        if ($_POST['post']) {
            $title = $_POST['title'];
            $image = $_FILES['image']['name'];
            $image_path = $_FILES['image']['tmp_name'];
            $userid = 1;
            $imageRepository = new ImageRepository();
            if (!$imageRepository->upload($title, $image, $image_path, $userid)){
                header("Location: /image/upload");
            }else {
                $value = "uploaded";
                setcookie("imageUploaded", $value, time()+ 5);
                header("Location: /");
            }

        }

    }
}

Set cookie if image uploaded

Set cookie if image uploaded


<?php namespace GeneaLabs\LaravelCasts\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use GeneaLabs\LaravelCasts\Providers\LaravelCastsService;
use File;

class Publish extends Command
{
    protected $signature = 'casts:publish {--assets} {--config}';
    protected $description = 'Publish various assets of the Laravel Casts package.';

    public function handle()
    {
        if ($this->option('assets')) {
            $this->delTree(public_path('genealabs-laravel-casts'));
            $this->call('vendor:publish', [
                '--provider' => LaravelCastsService::class,
                '--tag' => ['assets'],
                '--force' => true,
            ]);
        }

        if ($this->option('config')) {
            $this->call('vendor:publish', [
                '--provider' => LaravelCastsService::class,
                '--tag' => ['config'],
                '--force' => true,
            ]);
        }
    }

    private function delTree($folder)
    {
        if (! is_dir($folder)) {
            return false;
        }

        $files = array_diff(scandir($folder), ['.','..']);

        foreach ($files as $file) {
            is_dir("$folder/$file") ? $this->delTree("$folder/$file") : unlink("$folder/$file");
        }

        return rmdir($folder);
    }
}

<?php namespace GeneaLabs\LaravelCasts\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use GeneaLabs\LaravelCasts\Providers\Service;
use File;

class Publish extends Command
{
    protected $signature = 'casts:publish {--assets} {--config}';
    protected $description = 'Publish various assets of the Laravel Casts package.';

    public function handle()
    {
        if ($this->option('assets')) {
            $this->delTree(public_path('genealabs-laravel-casts'));
            $this->call('vendor:publish', [
                '--provider' => Service::class,
                '--tag' => ['assets'],
                '--force' => true,
            ]);
        }

        if ($this->option('config')) {
            $this->call('vendor:publish', [
                '--provider' => Service::class,
                '--tag' => ['config'],
                '--force' => true,
            ]);
        }
    }

    private function delTree($folder)
    {
        if (! is_dir($folder)) {
            return false;
        }

        $files = array_diff(scandir($folder), ['.','..']);

        foreach ($files as $file) {
            is_dir("$folder/$file") ? $this->delTree("$folder/$file") : unlink("$folder/$file");
        }

        return rmdir($folder);
    }
}

Fix service provider class reference

Fix service provider class reference


<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Chat\Repository;

use Chat\Entity\Message;
use Doctrine\ORM\EntityRepository;

class MessageRepository extends EntityRepository
{
    const lastMessageCache = 'last_message';

    /**
     * @param $room
     * @return Message[]
     */
    public function getLastMessages($room)
    {
        $dql = "
        SELECT m, u, a
        FROM Chat\Entity\Message m
        JOIN m.user u
        JOIN u.avatar a
        WHERE m.room = :room
        ORDER BY m.id DESC
        ";
        $query = $this->_em->createQuery($dql);
        $query->setMaxResults(10);
        $query->setParameter('room', $room);
        $query->useResultCache(true, 3600, self::lastMessageCache);
        return $query->getResult();
    }
}

<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Chat\Repository;

use Chat\Entity\Message;
use Doctrine\ORM\EntityRepository;

class MessageRepository extends EntityRepository
{
    const lastMessageCache = 'last_message';

    /**
     * @param $room
     * @return Message[]
     */
    public function getLastMessages($room)
    {
        $dql = "
        SELECT m, u, a
        FROM Chat\Entity\Message m
        JOIN m.user u
        LEFT JOIN u.avatar a
        WHERE m.room = :room
        ORDER BY m.id DESC
        ";
        $query = $this->_em->createQuery($dql);
        $query->setMaxResults(10);
        $query->setParameter('room', $room);
        $query->useResultCache(true, 3600, self::lastMessageCache);
        return $query->getResult();
    }
}

Load messages with users and avatars.

Load messages with users and avatars.


<?php

namespace MassAPIBundle\Repository;

use Doctrine\ORM\EntityRepository;

class PlaceRepository extends EntityRepository
{
    public function getNearPlace(array $criteria = array())
    {
        return $this->createQueryBuilder('p')
            ->leftJoin('p.geo', 'g')
            ->andWhere('CONTAINS(GeomFromJson(:inside_json), p.geoPoint) > 0')
            ->setParameter('inside_json', $criteria['inside_json'])
            ;
    }
}

<?php

namespace MassAPIBundle\Repository;

use Doctrine\ORM\EntityRepository;

class PlaceRepository extends EntityRepository
{
    public function getNearPlace(array $criteria = array())
    {
        return $this->createQueryBuilder('p')
            ->addSelect('p', 'g')
            ->leftJoin('p.geo', 'g')
            ->andWhere('CONTAINS(GeomFromJson(:inside_json), g.geoPoint) > 0')
            ->setParameter('inside_json', $criteria['inside_json'])
            ->getQuery()
            ->getResult()
            ;
    }
}

Fix Doctrine request for place

Fix Doctrine request for place


<?php

namespace RabbitMQ\Management;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;

class HttpClient extends Client
{
    private $hydrator;

    public function getHydrator()
    {
        if (!$this->hydrator) {
            $this->hydrator = new Hydrator();
        }

        return $this->hydrator;
    }

    /**
     * Factory method to create the HttpClient
     *
     * The following array keys and values are available options:
     * - url     : Base URL of web service
     * - port    : Port of web service
     * - scheme  : URI scheme: http or https
     * - username: API username
     * - password: API password
     *
     * @param array|Collection $config Configuration data
     *
     * @return self
     */
    public static function factory($config = array())
    {
        $default = array(
            'base_url' => '{scheme}://{username}:{password}@{url}:{port}',
            'scheme'   => 'http',
            'username' => 'guest',
            'password' => 'guest',
            'port'     => '55672',
        );

        $required = array('port', 'url', 'username', 'password');
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self($config->get('base_url'), $config);

        return $client;
    }
}

<?php

namespace RabbitMQ\Management;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use RabbitMQ\Management\Exception\RuntimeException;

class HttpClient extends Client
{
    private $hydrator;

    public function getHydrator()
    {
        if (!$this->hydrator) {
            $this->hydrator = new Hydrator();
        }

        return $this->hydrator;
    }

    /**
     * Factory method to create the HttpClient
     *
     * The following array keys and values are available options:
     * - url     : Base URL of web service
     * - port    : Port of web service
     * - scheme  : URI scheme: http or https
     * - username: API username
     * - password: API password
     *
     * @param array|Collection $options Configuration data
     *
     * @return self
     */
    public static function factory($options = array())
    {
        $default = array(
            'base_url' => '{scheme}://{username}:{password}@{url}:{port}',
            'scheme'   => 'http',
            'username' => 'guest',
            'password' => 'guest',
            'port'     => '55672',
        );

        $options = array_merge($default, $options);
        $required = array('port', 'url', 'username', 'password');

        foreach ($required as $key) {
            if (!array_key_exists($key, $options)) {
                throw new RuntimeException(sprintf('Missing option `%s`', $key));
            }
        }

        $config = new Collection($options);
        $client = new self($config->get('base_url'), $config);

        return $client;
    }
}

Downgrade to guzzle 2.8 for react compatibility


<?php
	// Get sub-categories
	$cats2 = (new \FelixOnline\Core\CategoryManager())
		->filter('hidden = 0')
		->filter('active = 1');

	if(!$currentuser->isLoggedIn()) {
		$cats2->filter('secret = 0');
	}

	$cats2 = $cats2->filter('id > 0')
		->filter('parent = %i', array($item->getId()))
		->order('order', 'ASC')
		->values();

	$active = false;

	if(isset($check) && $check == $item->getCat()) {
		$active = true;
	}

	foreach($parents as $parent) {
		if($parent->getCat() == $item->getCat()) {
			$active = true;
		}
	}
?>
	<li class="<?php if($active) echo 'active '; if(!is_null($cats2)) echo 'has-dropdown'; ?>">
		<a href="<?php echo STANDARD_URL.$item->getCat(); ?>/">
			<?php echo $item->getLabel(); ?>

<?php
	if(!is_null($cats2)) {
		echo '
';
		foreach($cats2 as $sub_category) {
			$theme->render('components/navigation/nav_item', array('item' => $sub_category));
		}
		echo '
';
	}
?>

<?php
	// Get sub-categories
	$cats2 = (new \FelixOnline\Core\CategoryManager())
		->filter('hidden = 0')
		->filter('active = 1');

	if(!$currentuser->isLoggedIn()) {
		$cats2->filter('secret = 0');
	}

	$cats2 = $cats2->filter('id > 0')
		->filter('parent = %i', array($item->getId()))
		->order('order', 'ASC')
		->values();

	$active = false;

	if(isset($check) && $check == $item->getCat()) {
		$active = true;
	}

	foreach($parents as $parent) {
		if($parent->getCat() == $item->getCat()) {
			$active = true;
		}
	}
?>
	<li class="<?php if($active) echo 'active '; if(!is_null($cats2)) echo 'has-dropdown'; ?>">
		<a href="<?php echo $item->getURL(); ?>">
			<?php echo $item->getLabel(); ?>

<?php
	if(!is_null($cats2)) {
		echo '
';
		foreach($cats2 as $sub_category) {
			$theme->render('components/navigation/nav_item', array('item' => $sub_category));
		}
		echo '
';
	}
?>

Fix URLS in nav bar

Fix URLS in nav bar


<?php
OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
OCP\JSON::checkAppEnabled('files_versions');

$source = (string)$_GET['source'];
$start = (string)$_GET['start'];
list ($uid, $filename) = OCA\Files_Versions\Storage::getUidAndFilename($source);
$count = 5; //show the newest revisions
$versions = OCA\Files_Versions\Storage::getVersions($uid, $filename, $source);
if( $versions ) {

	$endReached = false;
	if (count($versions) <= $start+$count) {
		$endReached = true;
	}

	$versions = array_slice($versions, $start, $count);

	\OCP\JSON::success(array('data' => array('versions' => $versions, 'endReached' => $endReached)));

} else {

	\OCP\JSON::success(array('data' => array('versions' => false, 'endReached' => true)));

}

<?php
OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
OCP\JSON::checkAppEnabled('files_versions');

$source = (string)$_GET['source'];
$start = (int)$_GET['start'];
list ($uid, $filename) = OCA\Files_Versions\Storage::getUidAndFilename($source);
$count = 5; //show the newest revisions
$versions = OCA\Files_Versions\Storage::getVersions($uid, $filename, $source);
if( $versions ) {

	$endReached = false;
	if (count($versions) <= $start+$count) {
		$endReached = true;
	}

	$versions = array_slice($versions, $start, $count);

	\OCP\JSON::success(array('data' => array('versions' => $versions, 'endReached' => $endReached)));

} else {

	\OCP\JSON::success(array('data' => array('versions' => false, 'endReached' => true)));

}

Use `int` instead of `string`

Use `int` instead of `string`


<?php

namespace Spark\Controller;

class ControllerCollection extends \Silex\ControllerCollection
{
    function draw(callable $callback)
    {
        $callback($this);
        return $this;
    }
}

<?php

namespace Spark\Controller;

class ControllerCollection extends \Silex\ControllerCollection
{
    function draw(callable $callback)
    {
        $callback($this);
        return $this;
    }

    function resources($resourceName)
    {
        $this->get("/$resourceName", "$resourceName#index")
             ->bind("{$resourceName}_index");

        $this->get("/$resourceName/new", "$resourceName#new")
             ->bind("{$resourceName}_new");

        $this->get("/$resourceName/{id}", "$resourceName#show")
             ->bind("{$resourceName}_show");

        $this->get("/$resourceName/{id}/edit", "$resourceName#edit")
             ->bind("{$resourceName}_edit");

        $this->post("/$resourceName", "$resourceName#create")
             ->bind("{$resourceName}_create");

        $this->put("/$resourceName/{id}", "$resourceName#update")
             ->bind("{$resourceName}_update");

        $this->delete("/$resourceName/{id}", "$resourceName#delete")
             ->bind("{$resourceName}_delete");
    }

    function resource($resourceName)
    {
    }
}

Add 'resources' method for easy definition of restful routes


<?php

require_once('_include.php');

$config = SimpleSAML_Configuration::getInstance();

if (array_key_exists('link_href', $_REQUEST)) {
    $link = (string) $_REQUEST['link_href'];
    $link = \SimpleSAML\Utils\HTTP::normalizeURL($link);
} else {
    $link = 'index.php';
}

if (array_key_exists('link_text', $_REQUEST)) {
    $text = $_REQUEST['link_text'];
} else {
    $text = '{logout:default_link_text}';
}

$t = new SimpleSAML_XHTML_Template($config, 'logout.php');
$t->data['link'] = $link;
$t->data['text'] = $text;
$t->show();
exit();

<?php

require_once('_include.php');

$config = SimpleSAML_Configuration::getInstance();

if (array_key_exists('link_href', $_REQUEST)) {
    $link = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['link_href']);
} else {
    $link = 'index.php';
}

if (array_key_exists('link_text', $_REQUEST)) {
    $text = $_REQUEST['link_text'];
} else {
    $text = '{logout:default_link_text}';
}

$t = new SimpleSAML_XHTML_Template($config, 'logout.php');
$t->data['link'] = $link;
$t->data['text'] = $text;
$t->show();
exit();

Fix another issue with URLs not being validated before displaying them into a page. Reported by John Page (hyp3rlinx).


<?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;

class ExceptionTest extends TestCase
{
    public function testExceptionSleep(): void
    {
        $exception = new Exception();

        $expectedArray = [
            'serializableTrace',
            'message',
            'code',
            'file',
            'line',
        ];

        $this->assertSame($expectedArray, $exception->__sleep());
    }
}

<?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;

class ExceptionTest extends TestCase
{
    public function testExceptionSleep(): void
    {
        $actual = (new Exception)->__sleep();

        $this->assertCount(5, $actual);
        $this->assertContains('serializableTrace', $actual);
        $this->assertContains('message', $actual);
        $this->assertContains('code', $actual);
        $this->assertContains('file', $actual);
        $this->assertContains('line', $actual);
    }
}

Make this test more robust

Make this test more robust

The order of properties in changed in various places (including serialization and var_dump()) in PHP 8.1


<?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\Config\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\ConfigCacheFactory;

class ConfigCacheFactoryTest extends TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Invalid type for callback argument. Expected callable, but got "object".
     */
    public function testCachWithInvalidCallback()
    {
        $cacheFactory = new ConfigCacheFactory(true);

        $cacheFactory->cache('file', new \stdClass());
    }
}

<?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\Config\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\ConfigCacheFactory;

class ConfigCacheFactoryTest extends TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Invalid type for callback argument. Expected callable, but got "object".
     */
    public function testCacheWithInvalidCallback()
    {
        $cacheFactory = new ConfigCacheFactory(true);

        $cacheFactory->cache('file', new \stdClass());
    }
}

Fix typo in test method name

Fix typo in test method name


<?php
namespace wcf\data;

/**
 * Every object with permissions has to implement this interface.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data
 * @category	Community Framework
 */
interface IPermissionObject {
	/**
	 * Checks if the active user has the given permissions for this object and
	 * throws a PermissionDeniedException if they don't have one of the permissions.
	 *
	 * @param	string[]		$permissions
	 */
	public function checkPermissions(array $permissions);

	/**
	 * Returns the permission value of the given permission for this object
	 * and the active user.
	 *
	 * @param	string			$permission
	 * @return	mixed
	 */
	public function getPermission($permission);
}

<?php
namespace wcf\data;
use wcf\system\exception\PermissionDeniedException;

/**
 * Every object with permissions has to implement this interface.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data
 * @category	Community Framework
 */
interface IPermissionObject {
	/**
	 * Checks if the active user has the given permissions for this object.
	 *
	 * @param	string[]	$permissions
	 * @throws	PermissionDeniedException	if the active user does not have at least one of the given permissions.
	 */
	public function checkPermissions(array $permissions);

	/**
	 * Returns the permission value of the given permission for this object
	 * and the active user.
	 *
	 * @param	string		$permission
	 * @return	mixed
	 */
	public function getPermission($permission);
}

Add @throws tag for IPermissionObject::checkPermissions()


        <?php
        if (($dt = strtotime($context->search_query)) && ($context->search_query != 'art')) {
            echo 'Search results for events dated '.date('F jS',$dt).'';
        } else {
            echo 'Search results for "'.htmlentities($context->search_query).'"';
        }
        ?>

    <?php

    echo ''.$context->count().' results.  getURL().'">(link)';
    echo $savvy->render($context, 'EventListing.tpl.php');
    ?>

        <a id="icsformat" title="ics format for search results" href="<?php echo $context->getURL()?>?format=ics">ics format for search results
        <a id="rssformat" title="rss format for search results" href="<?php echo $context->getURL()?>?format=rss">rss format for search results

            <?php
            if (($dt = strtotime($context->search_query)) && ($context->search_query != 'art')) {
                echo 'Search results for events dated '.date('F jS',$dt).'';
            } else {
                echo 'Search results for "'.htmlentities($context->search_query).'"';
            }
            ?>

        <?php echo ''.$context->count().' results.  getURL().'">(link)'; ?>

            <a id="icsformat" title="ics format for search results" href="<?php echo $context->getURL()?>?format=ics">ics format for search results
            <a id="rssformat" title="rss format for search results" href="<?php echo $context->getURL()?>?format=rss">rss format for search results

        <?php echo $savvy->render($context, 'EventListing.tpl.php'); ?>

Move title and extra information into sidebar


<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Binaries\PackageManagers;

/**
 * Represents the "npm" binary.
 */
class Npm extends AbstractPackageManager
{
    /**
     * The name of the manifest file to look for.
     *
     * @var string
     */
    protected $manifest = 'package.json';

    /**
     * Get an array of default paths to look for.
     *
     * @return string[]
     */
    protected function getKnownPaths()
    {
        return [
            'npm',
        ];
    }

    /**
     * Get where dependencies are installed.
     *
     * @return string|null
     */
    public function getDependenciesFolder()
    {
        return 'node_modules';
    }
}

<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Binaries\PackageManagers;

/**
 * Represents the "npm" binary.
 */
class Npm extends AbstractPackageManager
{
    /**
     * The name of the manifest file to look for.
     *
     * @var string
     */
    protected $manifest = 'package.json';

    /**
     * Get an array of default paths to look for.
     *
     * @return string[]
     */
    protected function getKnownPaths()
    {
        return [
            'yarn',
            'npm',
        ];
    }

    /**
     * Get where dependencies are installed.
     *
     * @return string|null
     */
    public function getDependenciesFolder()
    {
        return 'node_modules';
    }
}

Use Yarn over NPM if available

Use Yarn over NPM if available


<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Mapping;

/**
 * @Annotation
 */
class Source
{
    private $columns;
    private $filterable;

    public function __construct($metadata = array())
    {
        $this->columns = isset($metadata['columns']) ? array_map(array($this, 'format'), explode(',', $metadata['columns'])) : array();
        $this->filterable = !(isset($metadata['filterable']) && $metadata['filterable']);
    }

    private function format($columName) {
        $columName =  str_replace('.','__', $columName);
        return trim($columName);
    }

    public function getColumns()
    {
        return $this->columns;
    }

    public function hasColumns()
    {
        return !empty($this->columns);
    }

    public function isFilterable()
    {
        return $this->filterable;
    }
}

<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Mapping;

/**
 * @Annotation
 */
class Source
{
    private $columns;
    private $filterable;

    public function __construct($metadata = array())
    {
        $this->columns = isset($metadata['columns']) ? array_map(array($this, 'formatColumnName'), explode(',', $metadata['columns'])) : array();
        $this->filterable = !(isset($metadata['filterable']) && $metadata['filterable']);
    }

    private function formatColumnName($columnName) {
        $columnName =  str_replace('.','__', $columnName);
        return trim($columnName);
    }

    public function getColumns()
    {
        return $this->columns;
    }

    public function hasColumns()
    {
        return !empty($this->columns);
    }

    public function isFilterable()
    {
        return $this->filterable;
    }
}

Change the name of the format function in the source class


<?php

namespace BitWasp\Bitcoin\Test\Network\Messages;

use BitWasp\Buffertools\Buffer;
use BitWasp\Bitcoin\Network\Messages\GetAddr;
use BitWasp\Bitcoin\Tests\AbstractTestCase;

class GetAddrTest extends AbstractTestCase
{
    public function testGetAddr()
    {
        $getaddr = new GetAddr();
        $this->assertSame('getaddr', $getaddr->getNetworkCommand());
        $this->assertEquals(new Buffer(), $getaddr->getBuffer());
    }
}

<?php

namespace BitWasp\Bitcoin\Test\Network\Messages;

use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Serializer\Network\NetworkMessageSerializer;
use BitWasp\Buffertools\Buffer;
use BitWasp\Bitcoin\Network\Messages\GetAddr;
use BitWasp\Bitcoin\Tests\AbstractTestCase;

class GetAddrTest extends AbstractTestCase
{
    public function testGetAddr()
    {
        $getaddr = new GetAddr();
        $this->assertSame('getaddr', $getaddr->getNetworkCommand());
        $this->assertEquals(new Buffer(), $getaddr->getBuffer());
    }

    public function testNetworkSerializer()
    {
        $parser = new NetworkMessageSerializer(Bitcoin::getDefaultNetwork());
        $getaddr = new GetAddr();
        $serialized = $getaddr->getNetworkMessage()->getBuffer();
        $parsed = $parser->parse($serialized)->getPayload();

        $this->assertEquals($getaddr, $parsed);
    }
}

Add GetAddr Network Serializer test

Add GetAddr Network Serializer test


<?php

/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserActivityInjector.php');
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserCountActivityInjector.php');
class SV_UserActivity_XenForo_ControllerPublic_Watched extends XFCP_SV_UserActivity_XenForo_ControllerPublic_Watched
{
    protected function forumFetcher(
        /** @noinspection PhpUnusedParameterInspection */
        XenForo_ControllerResponse_View $response,
        $action,
        array $config)
    {
        if (empty($response->params['forumsWatched']))
        {
            return null;
        }

        return array_keys($response->params['forumsWatched']);
    }

    protected function threadFetcher(
        /** @noinspection PhpUnusedParameterInspection */
        XenForo_ControllerResponse_View $response,
        $action,
        array $config)

    {
        if (empty($response->params['threads']))
        {
            return null;
        }

        return array_keys($response->params['threads']);
    }

    protected $countActivityInjector = [
        [
            'activeKey' => 'watched-forums',
            'type'      => 'node',
            'actions'   => ['forums'],
            'fetcher'   => 'forumFetcher',
        ],
        [
            'activeKey' => 'watched-threads',
            'type'      => 'thread',
            'actions'   => ['threads', 'threadsall'],
            'fetcher'   => 'threadFetcher'
        ],
    ];
    use UserCountActivityInjector;
}

<?php

/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserActivityInjector.php');
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserCountActivityInjector.php');
class SV_UserActivity_XenForo_ControllerPublic_Watched extends XFCP_SV_UserActivity_XenForo_ControllerPublic_Watched
{
    protected function forumFetcher(
        /** @noinspection PhpUnusedParameterInspection */
        XenForo_ControllerResponse_View $response,
        $action,
        array $config)
    {
        if (empty($response->params['forumsWatched']))
        {
            return null;
        }

        return array_keys($response->params['forumsWatched']);
    }

    protected function threadFetcher(
        /** @noinspection PhpUnusedParameterInspection */
        XenForo_ControllerResponse_View $response,
        $action,
        array $config)

    {
        $key = ($action == 'threads') ? 'newThreads' : 'threads';
        if (empty($response->params[$key]))
        {
            return null;
        }

        return array_keys($response->params[$key]);
    }

    protected $countActivityInjector = [
        [
            'activeKey' => 'watched-forums',
            'type'      => 'node',
            'actions'   => ['forums'],
            'fetcher'   => 'forumFetcher',
        ],
        [
            'activeKey' => 'watched-threads',
            'type'      => 'thread',
            'actions'   => ['threads', 'threadsall'],
            'fetcher'   => 'threadFetcher'
        ],
    ];
    use UserCountActivityInjector;
}

Fix watched threads (new not all)

Fix watched threads (new not all)


<?php

namespace Joindin\Api\Model;

use Joindin\Api\Request;

/**
 * Container for multiple EventCommentReportModel objects
 */
class PendingTalkClaimModelCollection extends BaseModelCollection
{
    /** @var array|PendingTalkClaimModel[] */
    protected $list;

    protected $total;

    /**
     * Take arrays of data and create a collection of models; store metadata
     *
     * @param array $data
     * @param       $total
     */
    public function __construct(array $data, $total)
    {
        $this->list  = [];
        $this->total = $total;

        // hydrate the model objects if necessary and store to list
        foreach ($data as $item) {
            if (!$item instanceof PendingTalkClaimModel) {
                $item = new PendingTalkClaimModel($item);
            }
            $this->list[] = $item;
        }
    }

    /**
     * Present this collection ready for the output handlers
     *
     * This creates the expected output structure, converting each resource
     * to it's presentable representation and adding the meta fields for totals
     * and pagination
     *
     * @param Request $request
     * @param bool    $verbose
     *
     * @return array
     */
    public function getOutputView(Request $request, $verbose = false)
    {
        $retval = [];
        // handle the collection first
        $retval = ['claims' => []];
        foreach ($this->list as $item) {
            $retval['claims'][] = $item->getOutputView($request, $verbose);
        }

        // add other fields
        $retval['meta'] = $this->addPaginationLinks($request);

        return $retval;
    }
}

<?php

namespace Joindin\Api\Model;

use Joindin\Api\Request;

/**
 * Container for multiple EventCommentReportModel objects
 */
class PendingTalkClaimModelCollection extends BaseModelCollection
{
    /** @var array|PendingTalkClaimModel[] */
    protected $list;

    protected $total;

    /**
     * Take arrays of data and create a collection of models; store metadata
     *
     * @param array $data
     * @param int   $total
     */
    public function __construct(array $data, $total)
    {
        $this->list  = [];
        $this->total = $total;

        // hydrate the model objects if necessary and store to list
        foreach ($data as $item) {
            if (!$item instanceof PendingTalkClaimModel) {
                $item = new PendingTalkClaimModel($item);
            }
            $this->list[] = $item;
        }
    }

    /**
     * Present this collection ready for the output handlers
     *
     * This creates the expected output structure, converting each resource
     * to it's presentable representation and adding the meta fields for totals
     * and pagination
     *
     * @param Request $request
     * @param bool    $verbose
     *
     * @return array
     */
    public function getOutputView(Request $request, $verbose = false)
    {
        $retval = [];
        // handle the collection first
        $retval = ['claims' => []];
        foreach ($this->list as $item) {
            $retval['claims'][] = $item->getOutputView($request, $verbose);
        }

        // add other fields
        $retval['meta'] = $this->addPaginationLinks($request);

        return $retval;
    }
}

Add type to param annotation

Fix: Add type to param annotation


<?php
/**
 * @group Kwc_FormDynamic
 */
class Kwc_FormDynamic_Basic_Test extends Kwc_TestAbstract
{
    public function setUp()
    {
        parent::setUp('Kwc_FormDynamic_Basic_Root');
    }

    public function testIt()
    {
        $c = $this->_root->getComponentById('root_form-form')->getComponent();
        $postData = array(
            'form_root_form-paragraphs-1' => '',
            'form_root_form-paragraphs-2' => 'asdfasdf',
            'form_root_form-paragraphs-3' => '',
            'form_root_form-paragraphs-4' => 'Def',
            'form_root_form-paragraphs-5-post' => '1',
            'form_root_form-paragraphs-6' => 'on',
            'form_root_form-paragraphs-6-post' => '1',
            'root_form-form' => 'submit',
            'root_form-form-post' => 'post',
        );
        $c->processInput($postData);
        $this->assertEquals($c->getErrors(), array());
        $row = $c->getFormRow();

        $text = $row->sent_mail_content_text;
        $this->assertContains('Required: asdfasdf', $text);
        $this->assertContains('Check: off', $text);
        $this->assertContains('CheckDefault: on', $text);
    }
}

<?php
/**
 * @group Kwc_FormDynamic
 */
class Kwc_FormDynamic_Basic_Test extends Kwc_TestAbstract
{
    public function setUp()
    {
        parent::setUp('Kwc_FormDynamic_Basic_Root');
    }

    public function testIt()
    {
        $c = $this->_root->getComponentById('root_form-form')->getComponent();
        $postData = array(
            'form_root_form-paragraphs-1' => '',
            'form_root_form-paragraphs-2' => 'asdfasdf',
            'form_root_form-paragraphs-3' => '',
            'form_root_form-paragraphs-4' => 'Def',
            'form_root_form-paragraphs-5-post' => '1',
            'form_root_form-paragraphs-6' => 'on',
            'form_root_form-paragraphs-6-post' => '1',
            'root_form-form' => 'submit',
            'root_form-form-post' => 'post',
        );
        $c->processInput($postData);
        $this->assertEquals($c->getErrors(), array());
        $row = $c->getFormRow();

        $text = $row->sent_mail_content_text;
        $this->assertContains('Required: asdfasdf', $text);
        $this->assertContains('Check: No', $text);
        $this->assertContains('CheckDefault: Yes', $text);
    }
}

Change test because yes/no fits better for checkbox

FormDynamic-code changed because checkbox in german added "Am" instead of "Yes". This updates the test to fit the new text.


<?php
/**
 * Base class for controllers
 *
 * @file      BaseController.php
 *
 * PHP version 5.4+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2016 Alexander Yancharuk
 * @date      2016-10-21 16:43
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Controllers;

use Application\ApplicationTrait;

/**
 * Class   BaseController
 *
 * @author Yancharuk Alexander <alex at itvault dot info>
 */
class BaseController
{
	use ApplicationTrait;

	/**
	 * Getting route params
	 *
	 * @param string $name
	 *
	 * return string
	 */
	protected function getParam($name)
	{
		$params = $this->getApplication()->getRoute()->getParams();

		return $params[$name];
	}
}

<?php
/**
 * Base class for controllers
 *
 * @file      BaseController.php
 *
 * PHP version 5.4+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2016 Alexander Yancharuk
 * @date      2016-10-21 16:43
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Veles\Controllers;

use Application\ApplicationTrait;
use Veles\Application\Application;

/**
 * Class   BaseController
 *
 * @codeCoverageIgnore
 *
 * @author Yancharuk Alexander <alex at itvault dot info>
 */
class BaseController
{
	use ApplicationTrait;

	/**
	 * Set application as internal property
	 *
	 * @param Application $application
	 */
	public function __construct(Application $application)
	{
		$this->setApplication($application);
	}

	/**
	 * Getting route params
	 *
	 * @param string $name
	 *
	 * return string
	 */
	protected function getParam($name)
	{
		$params = $this->getApplication()->getRoute()->getParams();

		return $params[$name];
	}
}

Add application object as controller constructor param


<?php namespace App\Data;

use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Discussion extends Eloquent
{
	use SoftDeletes, PresentableTrait;

	protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = DiscussionPresenter::class;

	protected static function boot()
	{
		parent::boot();

		static::addGlobalScope('replyCount', function ($builder) {
			$builder->withCount('replies');
		});
	}

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function answer()
	{
		return $this->hasOne(Reply::class, 'id', 'answer_id');
	}

	public function author()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function replies()
	{
		return $this->hasMany(Reply::class)->withCount('favorites');
	}

	public function topic()
	{
		return $this->belongsTo(Topic::class);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function addReply(array $data)
	{
		$this->replies()->create($data);
	}

	public function scopeFilter($query, $filters)
	{
		return $filters->apply($query);
	}
}

<?php namespace App\Data;

use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Discussion extends Eloquent
{
	use SoftDeletes, PresentableTrait;

	protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = DiscussionPresenter::class;

	protected static function boot()
	{
		parent::boot();

		static::addGlobalScope('replyCount', function ($builder) {
			$builder->withCount('replies');
		});
	}

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function answer()
	{
		return $this->hasOne(Reply::class, 'id', 'answer_id')->withCount('favorites');
	}

	public function author()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function replies()
	{
		return $this->hasMany(Reply::class)->withCount('favorites');
	}

	public function topic()
	{
		return $this->belongsTo(Topic::class);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function addReply(array $data)
	{
		$this->replies()->create($data);
	}

	public function scopeFilter($query, $filters)
	{
		return $filters->apply($query);
	}
}

Make sure to return the favorites count

Make sure to return the favorites count


<?php

namespace Smartbox\Integration\FrameworkBundle\Tests\Unit\Exceptions\Handler;

use PHPUnit\Framework\TestCase;
use Smartbox\Integration\FrameworkBundle\Core\Endpoints\Endpoint;
use Smartbox\Integration\FrameworkBundle\Exceptions\Handler\ReThrowExceptionHandler;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableException;

class ReThrowExceptionHandlerTest extends TestCase
{
    public function testReThrow()
    {
        $this->expectException(RecoverableException::class);

        $endpoint = $this->createMock(Endpoint::class);

        $handler = new ReThrowExceptionHandler();
        $handler(new RecoverableException(), $endpoint, null);
    }
}

<?php

namespace Smartbox\Integration\FrameworkBundle\Tests\Unit\Exceptions\Handler;

use PHPUnit\Framework\TestCase;
use Smartbox\Integration\FrameworkBundle\Exceptions\Handler\ReThrowExceptionHandler;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableException;

class ReThrowExceptionHandlerTest extends TestCase
{
    public function testReThrow()
    {
        $this->expectException(RecoverableException::class);

        $handler = new ReThrowExceptionHandler();
        $handler->handle(new RecoverableException(), null);
    }
}

Update test after interface method change


@extends('layout.base')
@section('body')

    @include('layout.header')

Project

{{ $project->title }}

{{ $project->title }}

Project:	{{ $project->title }}

Release:	{{ $project->released }}

Technologies:	{{ $project->tech }}

View:	url }}">{{ substr($project->url,0,35).'...' }}

            {{ Parsedown::instance()->text($project->text) }}

        @foreach($project->images as $image)
        filename }}" width="100%" height="100%" class="project-image">
        @endforeach

@stop

@extends('layout.base')
@section('body')

    @include('layout.header')

Project

{{ $project->title }}

{{ $project->title }}

Project:	{{ $project->title }}

Release:	{{ $project->released }}

Technologies:	{{ $project->tech }}

View:	url }}">{{ substr($project->url,0,35).'...' }}

            {{ Parsedown::instance()->text($project->text) }}

        @foreach($project->images as $image)
        filename }}">
        filename }}" width="100%" height="100%" class="project-image">

        @endforeach

@stop

Allow users to enlarge project images

Allow users to enlarge project images


<?php

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

class ConstrainComments extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        //
        Schema::table('comments',function($table)
        {

            $table->foreign('userID')->references('userID')->on('users');
            $table->foreign('workID')->references('workID')->on('works');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::table('users', function ($table) {

        $table->dropForeign('comments_userID_foreign');
        $table->dropForeign('comments_workID_foreign');
      });
    }
}

<?php

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

class ConstrainComments extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        //
        Schema::table('comments',function($table)
        {

            $table->foreign('userID')->references('userID')->on('users');
            $table->foreign('workID')->references('workID')->on('works');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::table('comments', function ($table) {

        $table->dropForeign('comments_userID_foreign');
        $table->dropForeign('comments_workID_foreign');
      });
    }
}

Correct drop table referencing wrong table


<?php _e('Content State'); ?>

					 	<?php echo Utils::html_select( 'status', array_flip($statuses), $post->status == Post::status( 'scheduled' ) ? Post::status( 'published' ) : $post->status, array( 'class'=>'longselect') ); ?>

<?php _e('Comments Allowed'); ?>

<input type="checkbox" name="comments_enabled" class="styledformelement" value="1" <?php echo ( $post->info->comments_disabled == 1 ) ? '' : 'checked'; ?>>

<?php _e('Publication Time'); ?>

<input type="text" name="pubdate" id="pubdate" class="styledformelement" value="<?php echo $post->pubdate; ?>">

<?php _e('Content Address'); ?>

<input type="text" name="newslug" id="newslug" class="styledformelement" value="<?php echo $post->slug; ?>">

<?php _e('Content State'); ?>

					 	<?php echo Utils::html_select( 'status', array_flip($statuses), $post->status == Post::status( 'scheduled' ) ? Post::status( 'published' ) : $post->status, array( 'class'=>'longselect') ); ?>

<?php _e('Comments Allowed'); ?>

<input type="checkbox" name="comments_enabled" class="styledformelement" value="1" <?php echo ( $post->info->comments_disabled == 1 ) ? '' : 'checked'; ?>>

<?php _e('Publication Time'); ?>

<input type="text" name="pubdate" id="pubdate" class="styledformelement" value="<?php echo $post->pubdate; ?>"> To schedule a post, enter a future date

<?php _e('Content Address'); ?>

<input type="text" name="newslug" id="newslug" class="styledformelement" value="<?php echo $post->slug; ?>">

Add a note about scheduled posts to the UI. If there's a better way to insert this into the CSS, please go right ahead.

git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@1579 653ae4dd-d31e-0410-96ef-6bf7bf53c507


<?php

namespace N98\Magento\Command;

use N98\Magento\Command\PHPUnit\TestCase;
use Symfony\Component\Console\Tester\CommandTester;

class ListCommandTest extends TestCase
{
    public function testExecute()
    {
        $command = $this->getApplication()->find('list');

        $commandTester = new CommandTester($command);
        $commandTester->execute(
            array(
                'command' => 'list',
            )
        );

        $this->assertContains(
            sprintf('n98-magerun version %s by netz98 new media GmbH', $this->getApplication()->getVersion()),
            $commandTester->getDisplay()
        );
    }
}

<?php

namespace N98\Magento\Command;

use N98\Magento\Command\PHPUnit\TestCase;
use Symfony\Component\Console\Tester\CommandTester;

class ListCommandTest extends TestCase
{
    public function testExecute()
    {
        $command = $this->getApplication()->find('list');

        $commandTester = new CommandTester($command);
        $commandTester->execute(
            [
                'command' => 'list',
            ]
        );

        $this->assertContains(
            sprintf('n98-magerun version %s by netz98 GmbH', $this->getApplication()->getVersion()),
            $commandTester->getDisplay()
        );
    }
}

[FIX] Fix test after renaming the company name


<?php

namespace eien\Helpers;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Session
{

    /**
     * @return mixed
     */
    public function getCurrentUserSessions()
    {
        return DB::table('sessions')
                 ->where('user_id', Auth::user()->id)
                 ->get();
    }

    public function lastSeen($sessionId)
    {
        $last_activity = DB::table('sessions')
                           ->where('id', $sessionId)
                           ->value('last_activity');

        return $diff = Carbon::createFromTimestamp($last_activity)
                             ->diffForHumans();
    }

    public function removeSession($sessionId)
    {
        DB::table('sessions')
          ->where('id', $sessionId)
          ->delete();
    }
}

<?php

namespace eien\Helpers;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Session
{

    /**
     * @return mixed
     */
    public function getCurrentUserSessions()
    {
        return DB::table('sessions')
                 ->where('user_id', Auth::user()->id)
                 ->get();
    }

    public function lastSeen($sessionId)
    {
        $last_activity = DB::table('sessions')
                           ->where('id', $sessionId)
                           ->value('last_activity');

        return $diff = Carbon::createFromTimestamp($last_activity)
                             ->diffForHumans();
    }

    public function removeSession($sessionId)
    {
        DB::table('sessions')
          ->where('id', $sessionId)
          ->delete();
    }

    public function removeAllSessions($userId)
    {
        DB::table('sessions')
            ->where('user_id', $userId)
            ->delete();
    }
}

Add helper to remove all sessions

Add helper to remove all sessions


<?php
require_once 'views/_shared/status.html.php';
?>

Code Editor

						<form action="<?= $ControllerURL ?>/code" method="post">
<?php if ($ReadOnly) { ?>

Viewing: <?= $FilePath ?>

This file is not writable by the current user.

<?php } else { ?>

Editing: <?= $FilePath ?>

<?php } ?>
							<input type="hidden" name="file-path" value="<?= $FilePath ?>" />
							<textarea id="file-contents" name="file-contents" wrap="off" <?= $ReadOnly ? 'readonly="true"' : '' ?> placeholder="This file is empty." autofocus required><?= $FileContents ?></textarea>
<?php
if (!$ReadOnly) {
	$directory = dirname($FilePath);
?>

								<button id="submit" type="submit">Save</button>
								<button type="button" data-cwa-click="cancelEdit" data-destination="<?= "$ControllerURL/code" . ($directory === '.' ? '' : "/$directory") ?>">Cancel</button>

<?php
}
?>
						</form>

<?php
require_once 'views/_shared/status.html.php';
?>

Code Editor

<?php if ($ReadOnly) { ?>

Viewing: <?= $FilePath ?>

This file is not writable by the current user.

<?php } else { ?>

Editing: <?= $FilePath ?>

<?php } ?>
						<form action="<?= $ControllerURL ?>/code" method="post">
							<input type="hidden" name="file-path" value="<?= $FilePath ?>" />
							<textarea id="file-contents" name="file-contents" wrap="off" <?= $ReadOnly ? 'readonly="true"' : '' ?> placeholder="This file is empty." autofocus required><?= $FileContents ?></textarea>
<?php
if (!$ReadOnly) {
	$directory = dirname($FilePath);
?>

								<button id="submit" type="submit">Save</button>
								<button type="button" data-cwa-click="cancelEdit" data-destination="<?= "$ControllerURL/code" . ($directory === '.' ? '' : "/$directory") ?>">Cancel</button>

<?php
}
?>
						</form>

Move error message outside form.

Move error message outside form.


<?php

namespace Knplabs\TimeBundle\DependencyInjection;

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

class TimeExtension extends Extension
{

    public function configLoad(array $configs, ContainerBuilder $container)
    {
        foreach ($configs as $config) {
            $this->doConfigLoad($config, $container);
        }
    }

    public function doConfigLoad(array $config, ContainerBuilder $container)
    {
        if(!$container->hasDefinition('time.templating.helper.time')) {
            $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
            $loader->load('templating.xml');
            $loader->load('twig.xml');
        }
    }

    /**
     * Returns the base path for the XSD files.
     *
     * @return string The XSD base path
     */
    public function getXsdValidationBasePath()
    {
        return null;
    }

    public function getNamespace()
    {
        return 'http://www.symfony-project.org/schema/dic/symfony';
    }

    public function getAlias()
    {
        return 'time';
    }

}

<?php

namespace Knplabs\TimeBundle\DependencyInjection;

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

class TimeExtension extends Extension
{

    public function configLoad(array $configs, ContainerBuilder $container)
    {
        foreach ($configs as $config) {
            $this->doConfigLoad($config, $container);
        }
    }

    public function doConfigLoad(array $config, ContainerBuilder $container)
    {
        if(!$container->hasDefinition('time.templating.helper.time')) {
            $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
            $loader->load('templating.xml');
            $loader->load('twig.xml');
        }
    }

    /**
     * Returns the base path for the XSD files.
     *
     * @return string The XSD base path
     */
    public function getXsdValidationBasePath()
    {
        return null;
    }

    public function getNamespace()
    {
        return 'http://www.symfony-project.org/schema/dic/symfony';
    }

    public function getAlias()
    {
        return 'time';
    }

}

Update namespace in DIC extension

Update namespace in DIC extension


<?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\Bridge\Doctrine\HttpFoundation;

use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;

/**
 * Test class for DbalSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 */
class DbalSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            $this->markTestSkipped('The "HttpFoundation" component is not available');
        }
    }

    public function testConstruct()
    {
        $this->connection = $this->getMock('Doctrine\DBAL\Driver\Connection');
        $mock = $this->getMockBuilder('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler');
        $mock->setConstructorArgs(array($this->connection));
        $this->driver = $mock->getMock();
    }
}

<?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\Bridge\Doctrine\Tests\HttpFoundation;

use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;

/**
 * Test class for DbalSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 */
class DbalSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            $this->markTestSkipped('The "HttpFoundation" component is not available');
        }
    }

    public function testConstruct()
    {
        $this->connection = $this->getMock('Doctrine\DBAL\Driver\Connection');
        $mock = $this->getMockBuilder('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler');
        $mock->setConstructorArgs(array($this->connection));
        $this->driver = $mock->getMock();
    }
}

Fix a few namespaces to match file system.


<?php

class Denkmal_FormAction_Login_Process extends CM_FormAction_Abstract {

    protected function _getRequiredFields() {
        return array('email', 'password');
    }

    protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
    }

    protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        /** @var Denkmal_Site $site */
        $site = $response->getSite();

        try {
            $user = Denkmal_Model_User::authenticate($params->getString('email'), $params->getString('password'));
        } catch (CM_Exception_AuthFailed $e) {
            $response->addError($e->getMessagePublic($response->getRender()), 'password');
            return;
        }

        $response->getRequest()->getSession()->setUser($user);
        $response->addMessage($response->getRender()->getTranslation('Erfolgreich angemeldet. Bitte warten...'));
        $response->redirect($site->getLoginPage(), null, true);
    }
}

<?php

class Denkmal_FormAction_Login_Process extends CM_FormAction_Abstract {

    protected function _getRequiredFields() {
        return array('email', 'password');
    }

    protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
    }

    protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        /** @var Denkmal_Site $site */
        $site = $response->getSite();

        try {
            $user = Denkmal_Model_User::authenticate($params->getString('email'), $params->getString('password'));
        } catch (CM_Exception_AuthFailed $e) {
            $response->addError($e->getMessagePublic($response->getRender()), 'password');
            return;
        }

        $response->getRequest()->getSession()->setUser($user);
        $response->getRequest()->getSession()->setLifetime(86400 * 14);

        $response->addMessage($response->getRender()->getTranslation('Erfolgreich angemeldet. Bitte warten...'));
        $response->redirect($site->getLoginPage(), null, true);
    }
}

Set specific session expiration of 14d

Set specific session expiration of 14d


<?php
declare(strict_types = 1);
/**
 * /src/Entity/Interfaces/UserGroupAwareInterface.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Entity\Interfaces;

use App\Entity\UserGroup;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * Interface UserGroupAwareInterface
 *
 * @package App\Entity
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
interface UserGroupAwareInterface extends EntityInterface
{
    /**
     * @return Collection<int, UserGroup>|ArrayCollection<int, UserGroup>
     */
    public function getUserGroups(): Collection;

    /**
     * Method to attach new userGroup to current user OR api key.
     */
    public function addUserGroup(UserGroup $userGroup): self;

    /**
     * Method to remove specified userGroup from current user OR api key.
     */
    public function removeUserGroup(UserGroup $userGroup): self;

    /**
     * Method to remove all many-to-many userGroup relations from current user
     * OR api key.
     */
    public function clearUserGroups(): self;
}

<?php
declare(strict_types = 1);
/**
 * /src/Entity/Interfaces/UserGroupAwareInterface.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Entity\Interfaces;

use App\Entity\UserGroup;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * Interface UserGroupAwareInterface
 *
 * @package App\Entity
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
interface UserGroupAwareInterface extends EntityInterface
{
    /**
     * @return Collection<int, UserGroup>|ArrayCollection<int, UserGroup>
     */
    public function getUserGroups(): Collection|ArrayCollection;

    /**
     * Method to attach new userGroup to current user OR api key.
     */
    public function addUserGroup(UserGroup $userGroup): self;

    /**
     * Method to remove specified userGroup from current user OR api key.
     */
    public function removeUserGroup(UserGroup $userGroup): self;

    /**
     * Method to remove all many-to-many userGroup relations from current user
     * OR api key.
     */
    public function clearUserGroups(): self;
}

Use PHP 8 union types

Use PHP 8 union types


 {{ config('pagekit.conpany_name', 'PageKit') }}. {{ config( 'pagekit.address', 'Company Address' ) }}
            © All right reserved

Move footer credit to one line

Move footer credit to one line


@extends('root.app')

@section('content')

Registered Users

    {!! Table::withContents($users->toArray())->striped()->condensed()->hover() !!}

@endsection

@extends('layouts.user')

@section('content')

Registered Users

    {!! Table::withContents($users->toArray())->striped()->condensed()->hover() !!}

@endsection

Change used layout to new theme

Change used layout to new theme


<?php
/**
 * YAWIK
 *
 * @filesource
 * @license MIT
 * @copyright  2013 - 2016 Cross Solution <http://cross-solution.de>
 */

/** */
namespace Core\Listener;

use Core\Controller\AdminControllerEvent;
use Core\ModuleManager\Feature\VersionProviderInterface;
use Laminas\ModuleManager\ModuleManager;

/**
 * ${CARET}
 *
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 * @todo write test
 */
class ModuleVersionAdminWidgetProvider
{
    /**
     *
     *
     * @var ModuleManager
     */
    private $moduleManager;

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

    public function __invoke(AdminControllerEvent $event)
    {
        /* @var \Core\Controller\AdminController $controller */
        $modules = $this->moduleManager->getLoadedModules();
        $modules = array_filter(
            $modules,
            function($i) {
                return 0 !== strpos($i, 'Zend\\') && 0 !== strpos($i, 'Doctrine');
            },
            ARRAY_FILTER_USE_KEY
        );
        ksort($modules);

        $event->addViewTemplate('modules', 'core/admin/module-version-widget.phtml', ['modules' => $modules], 100);
    }
}

<?php
/**
 * YAWIK
 *
 * @filesource
 * @license MIT
 * @copyright  2013 - 2016 Cross Solution <http://cross-solution.de>
 */

/** */
namespace Core\Listener;

use Core\Controller\AdminControllerEvent;
use Core\ModuleManager\Feature\VersionProviderInterface;
use Laminas\ModuleManager\ModuleManager;

/**
 * ${CARET}
 *
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 * @todo write test
 */
class ModuleVersionAdminWidgetProvider
{
    /**
     *
     *
     * @var ModuleManager
     */
    private $moduleManager;

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

    public function __invoke(AdminControllerEvent $event)
    {
        /* @var \Core\Controller\AdminController $controller */
        $modules = $this->moduleManager->getLoadedModules();
        $modules = array_filter(
            $modules,
            function($i) {
                return 0 !== strpos($i, 'Laminas\\') && 0 !== strpos($i, 'Doctrine');
            },
            ARRAY_FILTER_USE_KEY
        );
        ksort($modules);

        $event->addViewTemplate('modules', 'core/admin/module-version-widget.phtml', ['modules' => $modules], 100);
    }
}

fix(Core): Exclude Laminas modules from module version widget.


<?php

namespace AbleCore\Modules;

class ImageStyleManager {

	private $generated = array();

	public static function init()
	{
		return new self();
	}

	public function define($name, $label, $effects = array())
	{
		$this->generated[$name] = array(
			'label' => $label,
			'effects' => $effects,
		);
		return $this;
	}

	public function defineScale($name, $label, $width = null, $height = null, $upscale = false)
	{
		$effects = array();
		$scale_effect = array(
			'name' => 'image_scale',
			'data' => array(),
		);
		if ($width !== null)
			$scale_effect['data']['width'] = $width;
		if ($height !== null)
			$scale_effect['data']['height'] = $height;
		$scale_effect['data']['upscale'] = $upscale;
		$effects[] = $scale_effect;
		return $this->define($name, $label, $effects);
	}

}

<?php

namespace AbleCore\Modules;

class ImageStyleManager {

	private $generated = array();

	public static function init()
	{
		return new self();
	}

	public function define($name, $label, $effects = array())
	{
		$this->generated[$name] = array(
			'label' => $label,
			'effects' => $effects,
		);
		return $this;
	}

	public function defineScale($name, $label, $width = null, $height = null, $upscale = false)
	{
		$effects = array();
		$scale_effect = array(
			'name' => 'image_scale',
			'data' => array(),
		);
		if ($width !== null)
			$scale_effect['data']['width'] = $width;
		if ($height !== null)
			$scale_effect['data']['height'] = $height;
		$scale_effect['data']['upscale'] = $upscale;
		$effects[] = $scale_effect;
		return $this->define($name, $label, $effects);
	}

	public function fin()
	{
		return $this->generated;
	}

}

Fix the fin() function not being present.


<?php
declare(strict_types = 1);
/**
 * /tests/E2E/Rest/src/Controller/ControllerForLifeCycleTests.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Tests\E2E\Rest\src\Controller;

use App\Rest\Controller;
use App\Rest\Traits\Methods;
use App\Tests\E2E\Rest\src\Resource\ResourceForLifeCycleTests;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Throwable;

/**
 * Class ControllerForLifeCycleTests
 *
 * @Route(
 *     path="/test_lifecycle_behaviour",
 *  )
 *
 * @package App\Tests\E2E\Rest\src\Controller
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class ControllerForLifeCycleTests extends Controller
{
    // Traits
    use Methods\FindOneMethod;

    public function __construct(
        protected ResourceForLifeCycleTests $resource,
    ) {
    }

    /**
     * @Route(
     *      "/{role}",
     *      requirements={
     *          "role" = "^ROLE_\w+$"
     *      },
     *      methods={"GET"}
     *  )
     *
     * @throws Throwable
     */
    public function findOneAction(Request $request, string $role): Response
    {
        return $this->findOneMethod($request, $role);
    }
}

<?php
declare(strict_types = 1);
/**
 * /tests/E2E/Rest/src/Controller/ControllerForLifeCycleTests.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Tests\E2E\Rest\src\Controller;

use App\Rest\Controller;
use App\Rest\Traits\Methods;
use App\Tests\E2E\Rest\src\Resource\ResourceForLifeCycleTests;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Throwable;

/**
 * Class ControllerForLifeCycleTests
 *
 * @package App\Tests\E2E\Rest\src\Controller
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
#[Route(
    path: '/test_lifecycle_behaviour',
)]
class ControllerForLifeCycleTests extends Controller
{
    // Traits
    use Methods\FindOneMethod;

    public function __construct(
        protected ResourceForLifeCycleTests $resource,
    ) {
    }

    /**
     * @throws Throwable
     */
    #[Route(
        path: '/{role}',
        requirements: [
            'role' => '^ROLE_\w+$',
        ],
        methods: [Request::METHOD_GET],
    )]
    public function findOneAction(Request $request, string $role): Response
    {
        return $this->findOneMethod($request, $role);
    }
}

Use PHP8 attributes instead annotations

Use PHP8 attributes instead annotations


<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.

$loader = new ApcClassLoader('symfony2Benchmark', $loader);
$loader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

require_once __DIR__.'/../app/AppKernel.php';

// FrameworkBenchmark rules prohibit using AppCache,
// specifically every request for the JSON test type
// must be handled separately
//
// require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Remove APC cache (php 5.5 included Zend cache already)


<?php
class Kwc_FulltextSearch_Search_ViewAjax_SearchForm_FrontendForm extends Kwf_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->_model = new Kwf_Model_FnF();
        $this->fields->add(new Kwf_Form_Field_TextField('query', 'Query'))
            ->setAutoComplete(false)
            ->setHideLabel(true)
            ->setClearOnFocus(true)
            ->setDefaultValue(trlKwfStatic('Search'));
    }
}

<?php
class Kwc_FulltextSearch_Search_ViewAjax_SearchForm_FrontendForm extends Kwf_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->_model = new Kwf_Model_FnF();
        $this->fields->add(new Kwf_Form_Field_TextField('query', 'Query'))
            ->setAutoComplete(false)
            ->setHideLabel(true)
            ->setEmptyText(trlStatic('Suchbegriff'));
    }
}

Use setEmptyText instead of default-value and clearOnFocus


<?php

namespace Opifer\EavBundle\Form\Transformer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataTransformerInterface;

class CollectionToObjectTransformer implements DataTransformerInterface
{
    /**
     * Transforms an ArrayCollection Object to a single Object.
     *
     * @param \Doctrine\ORM\PersistentCollection $values
     *
     * @return Object
     */
    public function transform($values)
    {
        if (null === $values || !($values instanceof Collection)) {
            return null;
        }

        return $values->first();
    }

    /**
     * Transforms a single Object to an ArrayCollection
     *
     * @param Object $value
     *
     * @return ArrayCollection
     */
    public function reverseTransform($value)
    {
        if ($value instanceof Collection) {
            return $value;
        }

        $collection = new ArrayCollection();
        $collection->add($value);

        return $collection;
    }
}

<?php

namespace Opifer\EavBundle\Form\Transformer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataTransformerInterface;

class CollectionToObjectTransformer implements DataTransformerInterface
{
    /**
     * Transforms an ArrayCollection Object to a single Object.
     *
     * @param \Doctrine\ORM\PersistentCollection $values
     *
     * @return Object
     */
    public function transform($values)
    {
        if (null === $values || !($values instanceof Collection)) {
            return null;
        }

        return $values->first();
    }

    /**
     * Transforms a single Object to an ArrayCollection
     *
     * @param Object $value
     *
     * @return ArrayCollection
     */
    public function reverseTransform($value)
    {
        if ($value instanceof Collection) {
            return $value;
        }

        $collection = new ArrayCollection();
        if(null !== $value) {
            $collection->add($value);
        }

        return $collection;
    }
}

Set empty array on object transformer

Set empty array on object transformer


<?php

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

class CreatePluginsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('plugins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('dir_name');
            $table->int('area');
            $table->int('permission');
            $table->string('tables');
            $table->int('active');
        });
    }

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

<?php

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

class CreatePluginsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('plugins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('dir_name');
            $table->integer('area');
            $table->integer('permission');
            $table->string('tables');
            $table->integer('active');
        });
    }

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

Fix plugin migration file 2

Fix plugin migration file 2