<?php
namespace Faker\Test\Provider;

use Faker\Provider\en_US\Text;
use Faker\Generator;

class TextTest extends \PHPUnit_Framework_TestCase
{
    public function testTextMaxLength()
    {
        $generator = new Generator();
        $generator->addProvider(new Text($generator));
        $generator->seed(0);

        $lengths = array(10, 20, 50, 70, 90, 120, 150, 200, 500);

        foreach ($lengths as $length) {
            $this->assertLessThan($length, $generator->realText($length));
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMaxIndex()
    {
        Text::realText(200, 11);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMinIndex()
    {
        Text::realText(200, 0);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMinLength()
    {
        Text::realText(9);
    }
}

<?php
namespace Faker\Test\Provider;

use Faker\Provider\en_US\Text;
use Faker\Generator;

class TextTest extends \PHPUnit_Framework_TestCase
{
    public function testTextMaxLength()
    {
        $generator = new Generator();
        $generator->addProvider(new Text($generator));
        $generator->seed(0);

        $lengths = array(10, 20, 50, 70, 90, 120, 150, 200, 500);

        foreach ($lengths as $length) {
            $this->assertLessThan($length, $generator->realText($length));
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMaxIndex()
    {
	$generator = new Generator();
        $generator->addProvider(new Text($generator));
        $generator->seed(0);
	$generator->realText(200, 11);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMinIndex()
    {
	$generator = new Generator();
        $generator->addProvider(new Text($generator));
        $generator->seed(0);
        $generator->realText(200, 0);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTextMinLength()
    {
	$generator = new Generator();
        $generator->addProvider(new Text($generator));
        $generator->seed(0);
        $generator->realText(9);
    }
}

Fix tests for Text provider

Fix tests for Text provider


<?php

require_once('tests/php/base.php');

class CashSeedTests extends UnitTestCase {
	function testS3Seed(){
		$settings = new S3Seed(1,1);
		$this->assertIsa($settings, 'S3Seed');
	}
	function testTwitterSeed(){
		$user_id      = 1;
		$settings_id  = 1;
		$twitter      = new TwitterSeed($user_id,$settings_id);
		$this->assertIsa($twitter, 'TwitterSeed');
	}
	function testMailchimpSeed(){
		if(array_key_exists('MAILCHIMP_API_KEY', $_ENV)) {
			$key = $_ENV['MAILCHIMP_API_KEY'];
			$settings = new MailchimpSeed($key);
			$this->assertIsa($settings, 'MailchimpSeed');
			$this->assertTrue($settings->url);
			$this->assertTrue($settings->lists());
			$this->assertTrue($settings->listWebhooks(42));
		} else {
			fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n");
			return;
		}
	}
}
?>

<?php

require_once('tests/php/base.php');

class CashSeedTests extends UnitTestCase {
	function testS3Seed(){
		$settings = new S3Seed(1,1);
		$this->assertIsa($settings, 'S3Seed');
	}
	function testTwitterSeed(){
		$user_id      = 1;
		$settings_id  = 1;
		$twitter      = new TwitterSeed($user_id,$settings_id);
		$this->assertIsa($twitter, 'TwitterSeed');
	}
	function testMailchimpSeed(){
		if(array_key_exists('MAILCHIMP_API_KEY', $_ENV)) {
			$key = $_ENV['MAILCHIMP_API_KEY'];
			$mc = new MailchimpSeed($key);
			$this->assertIsa($mc, 'MailchimpSeed');
			$this->assertTrue($mc->url);
			$this->assertTrue($mc->lists());
			$this->assertTrue($mc->listWebhooks(42));
			$this->assertTrue($mc->listWebhooks(42));
			$this->assertTrue($mc->listMembers(1));
		} else {
			fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n");
			return;
		}
	}
}
?>

Add a test for listMembers

Add a test for listMembers


<?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\Notifier\Messenger;

use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Transport\TransportInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @experimental in 5.1
 */
final class MessageHandler
{
    private $transport;

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

    public function __invoke(MessageInterface $message)
    {
        $this->transport->send($message);
    }
}

<?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\Notifier\Messenger;

use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SentMessage;
use Symfony\Component\Notifier\Transport\TransportInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @experimental in 5.1
 */
final class MessageHandler
{
    private $transport;

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

    public function __invoke(MessageInterface $message): ?SentMessage
    {
        return $this->transport->send($message);
    }
}

[Notifier] Return SentMessage from the Notifier message handler


<?php

namespace Api;

/**
 * File API controller
 *
 * @package  api
 * @author   Frederic Guillot
 */
class File extends Base
{
    public function getFile($file_id)
    {
        return $this->file->getById($file_id);
    }

    public function getAllFiles($task_id)
    {
        return $this->file->getAll($task_id);
    }

    public function downloadFile($file_id)
    {
        $file = $this->file->getById($file_id);

        if (! empty($file)) {

            $filename = FILES_DIR.$file['path'];

            if (file_exists($filename)) {
                return base64_encode(file_get_contents($filename));
            }
        }

        return '';
    }

    public function createFile($project_id, $task_id, $filename, $is_image, &$blob)
    {
        return $this->file->uploadContent($project_id, $task_id, $filename, $is_image, $blob);
    }

    public function removeFile($file_id)
    {
        return $this->file->remove($file_id);
    }
}

<?php

namespace Api;

/**
 * File API controller
 *
 * @package  api
 * @author   Frederic Guillot
 */
class File extends Base
{
    public function getFile($file_id)
    {
        return $this->file->getById($file_id);
    }

    public function getAllFiles($task_id)
    {
        return $this->file->getAll($task_id);
    }

    public function downloadFile($file_id)
    {
        $file = $this->file->getById($file_id);

        if (! empty($file)) {

            $filename = FILES_DIR.$file['path'];

            if (file_exists($filename)) {
                return base64_encode(file_get_contents($filename));
            }
        }

        return '';
    }

    public function createFile($project_id, $task_id, $filename, $is_image, $blob)
    {
        return $this->file->uploadContent($project_id, $task_id, $filename, $is_image, $blob);
    }

    public function removeFile($file_id)
    {
        return $this->file->remove($file_id);
    }
}

Fix bug: api exceptions can occurs with some versions of PHP


@extends ('layouts.master')

    @section('meta_title') Documentation @stop

    @section('content')

General Information

Before you start, please be aware of the following rules

You must have an API Key to create Screenshots

Your screenshots will be removed after 12 hours of their creation.

Do API Request

For a simple request, just send a POST-Request to http://screenly.com/api/v1/fullscreen. The API will then take a screenshot of the given URL width a with of 1024 pixels. The height of the screenshot is 100%.

{
    "key": "YOUR_API_KEY",
    "url": "http://en.wikipedia.org/"
}

Return Value

{
    "filename": "http://screeenly.com/images/generated/FILENAME.jpg",
    "base64":   "ENCODED_FILE"
}

    @stop

@extends ('layouts.master')

    @section('meta_title') Documentation @stop

    @section('content')

General Information

Before you start, please be aware of the following rules

You must have an API Key to create Screenshots

Your screenshots will be removed after 12 hours of their creation.

Do API Request

For a simple request, just send a POST-Request to http://screeenly.com/api/v1/fullsize. The API will then take a screenshot of the given URL width a with of 1024 pixels. The height of the screenshot is 100%.

Simple PHP CURL Example.

{
    "key": "YOUR_API_KEY",
    "url": "http://en.wikipedia.org/"
}

Return Value

{
    "filename": "http://screeenly.com/images/generated/FILENAME.jpg",
    "base64":   "ENCODED_FILE"
}

    @stop

Fix documentation error. Added link to Example


<?php

namespace Mini\Model;

use PDOStatement;

class PaginatingStore extends Store {
    /**
     * The default page size
     * @var int
     */
    private $pageSize;

    function __construct(PingablePDO $db, string $table, int $pageSize = 50) {
        $this->pageSize = $pageSize;
        parent::__construct($db, $table);
    }

    public function getPageCount($limit = null, $count = null): int
    {
        $limit = $limit ?? $this->pageSize;
        $count = $count ?? $this->getCount();
        if($limit > 0) {
            return ceil($count / (float)$limit);
        }
        else {
            return 0;
        }
    }

    public function getOffset(int $page): int
    {
        return ($page - 1) * $this->pageSize;
    }

    protected function doPagination(PDOStatement $query, int $offset = 0, int $limit = null, $start = ":start", $stop = ":stop")
    {
        $limit = $limit ?? $this->pageSize;
        $query->bindValue($start, $offset, PDO::PARAM_INT);
        $query->bindValue($stop, $limit, PDO::PARAM_INT);
    }
}

<?php

namespace Mini\Model;

use PDOStatement;

class PaginatingStore extends Store {
    /**
     * The default page size
     * @var int
     */
    protected $pageSize;

    function __construct(PingablePDO $db, string $table, int $pageSize = 50) {
        $this->pageSize = $pageSize;
        parent::__construct($db, $table);
    }

    public function getPageCount($limit = null, $count = null): int
    {
        $limit = $limit ?? $this->pageSize;
        $count = $count ?? $this->getCount();
        if($limit > 0) {
            return ceil($count / (float)$limit);
        }
        else {
            return 0;
        }
    }

    public function getOffset(int $page): int
    {
        return ($page - 1) * $this->pageSize;
    }

    protected function doPagination(PDOStatement $query, int $offset = 0, int $limit = null, $start = ":start", $stop = ":stop")
    {
        $limit = $limit ?? $this->pageSize;
        $query->bindValue($start, $offset, PDO::PARAM_INT);
        $query->bindValue($stop, $limit, PDO::PARAM_INT);
    }
}

Fix access to page size

Fix access to page size


<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Auth extends Controller_Template {
    public $template = 'templates/public';
    public function action_index()
    {
        if( $this->request->post('username') ) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            // Hack: repair later //todo
            Auth::instance()->force_login('demo');
            $is_logged_in = Auth::instance()->logged_in();
            if ($is_logged_in) {
                Notify::success('Success!');
                $this->redirect('welcome');
            } else {
                Notify::error('Kasutajanimi või parool vale!');
            }
        }
    }
    public function action_logout()
    {
        Auth::instance()->logout();
        $this->redirect('auth');
    }

} // End Welcome

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Auth extends Controller_Template
{
    public $template = 'templates/public';

    public function action_index()
    {
        if ($this->request->post('username')) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            $is_logged_in = Auth::instance()->login($username, $password);

            if ($is_logged_in) {
                Notify::success('Success!');
                $this->redirect('welcome');
            } else {
                Notify::error('Kasutajanimi või parool vale!');
            }
        }
    }

    public function action_logout()
    {
        Auth::instance()->logout();
        $this->redirect('auth');
    }

} // End Welcome

Reformat code, remove auth hack

Reformat code, remove auth hack


<?php

namespace Tests\Feature;

use Tests\IntegrationTestCase;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ReadArticlesByTagTest extends IntegrationTestCase
{

    use DatabaseMigrations;

    protected $article;
    protected $tag;

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

        $this->article = factory('App\Article')->create();
        $this->tag = factory('App\Tag')->create();

        $this->article->tags()->attach($this->tag);
    }

    /** @test */
    public function a_user_can_view_all_articles_with_tag()
    {
        $response = $this->get('/tags/' . $this->tag->name);

        $response->assertSee($this->article->title);
    }
}

<?php

namespace Tests\Feature;

use Tests\IntegrationTestCase;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ReadArticlesByTagTest extends IntegrationTestCase
{

    use DatabaseMigrations;

    protected $article;
    protected $tag;

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

        $this->article = factory('App\Article')->create();
        $this->tag = factory('App\Tag')->create();

        $this->article->tags()->attach($this->tag);
    }

    /** @test */
    public function a_user_can_view_all_articles_with_tag()
    {
        $response = $this->get('/tag/' . $this->tag->name);

        $response->assertSee($this->article->title);
    }
}

Fix read articles by tag test

Fix read articles by tag test


<?php
namespace OpenCFP\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

class SecurityController
{
    public function indexAction(Request $req, Application $app)
    {
        $template = $app['twig']->loadTemplate('login.twig');

        return $template->render(array());
    }

    public function processAction(Request $req, Application $app)
    {
        $template = $app['twig']->loadTemplate('login.twig');
        $template_data = array();

        try {
            $page = new \OpenCFP\Login($app['sentry']);

            if ($page->authenticate($req->get('email'), $req->get('passwd'))) {
                return $app->redirect($app['url'] . '/dashboard');
            }

            $template_data = array(
                'user' => $app['sentry']->getUser(),
                'email' => $req->get('email'),
                'errorMessage' => $page->getAuthenticationMessage()
            );
        } catch (Exception $e) {
            $template_data = array(
                'user' => $app['sentry']->getUser(),
                'email' => $req->get('email'),
                'errorMessage' => $e->getMessage()
            );
        }

        return $template->render($template_data);
    }

    public function outAction(Request $req, Application $app)
    {
        $app['sentry']->logout();

        return $app->redirect($app['url'] . '/');
    }
}

<?php
namespace OpenCFP\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityController
{
    public function indexAction(Request $req, Application $app)
    {
        $template = $app['twig']->loadTemplate('login.twig');

        return $template->render(array());
    }

    public function processAction(Request $req, Application $app)
    {
        $template = $app['twig']->loadTemplate('login.twig');
        $template_data = array();
        $code = 200;

        try {
            $page = new \OpenCFP\Login($app['sentry']);

            if ($page->authenticate($req->get('email'), $req->get('passwd'))) {
                return $app->redirect($app['url'] . '/dashboard');
            }

            $template_data = array(
                'user' => $app['sentry']->getUser(),
                'email' => $req->get('email'),
                'errorMessage' => $page->getAuthenticationMessage()
            );
            $code = 400;
        } catch (Exception $e) {
            $template_data = array(
                'user' => $app['sentry']->getUser(),
                'email' => $req->get('email'),
                'errorMessage' => $e->getMessage()
            );
            $code = 400;
        }

        return new Response($template->render($template_data), $code);
    }

    public function outAction(Request $req, Application $app)
    {
        $app['sentry']->logout();

        return $app->redirect($app['url'] . '/');
    }
}

Return 400 response on login fail

Return 400 response on login fail


<?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()
        );
    }
}

<?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 GmbH', $this->getApplication()->getVersion()),
            $commandTester->getDisplay()
        );
    }
}

Fix array syntax for old PHP versions

[FIX] Fix array syntax for old PHP versions


Default values

{{ $default }}

Customized example

{{ $customized }}

Fix incorrect border color in custom config component


<?php

use Symfony\Component\HttpFoundation\Request;

$loader = require dirname(__DIR__).'/app/config/bootstrap.php';
include_once __DIR__.'/../var/bootstrap.php.cache';

// Enable APC for autoloading to improve performance.
// You should change the ApcClassLoader first argument to a unique prefix
// in order to prevent cache key conflicts with other applications
// also using APC.
/*
$apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);
*/

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;

$loader = require dirname(__DIR__).'/app/config/bootstrap.php';

// Enable APC for autoloading to improve performance.
// You should change the ApcClassLoader first argument to a unique prefix
// in order to prevent cache key conflicts with other applications
// also using APC.
/*
$apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);
*/

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Remove reference to bootstrap.php.cache file


<?php namespace Bosnadev\Database;

use Bosnadev\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;

/**
 * Class DatabaseServiceProvider
 * @package Bosnadev\Database
 */
class DatabaseServiceProvider extends \Illuminate\Database\DatabaseServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // The connection factory is used to create the actual connection instances on
        // the database. We will inject the factory into the manager so that it may
        // make the connections while they are actually needed and not of before.
        $this->app->bindShared('db.factory', function ($app) {
            return new ConnectionFactory($app);
        });

        // The database manager is used to resolve various connections, since multiple
        // connections might be managed. It also implements the connection resolver
        // interface which may be used by other components requiring connections.
        $this->app->bindShared('db', function ($app) {
            return new DatabaseManager($app, $app['db.factory']);
        });
    }
}

<?php namespace Bosnadev\Database;

use Bosnadev\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;

/**
 * Class DatabaseServiceProvider
 * @package Bosnadev\Database
 */
class DatabaseServiceProvider extends \Illuminate\Database\DatabaseServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // The connection factory is used to create the actual connection instances on
        // the database. We will inject the factory into the manager so that it may
        // make the connections while they are actually needed and not of before.
        $this->app->singleton('db.factory', function ($app) {
            return new ConnectionFactory($app);
        });

        // The database manager is used to resolve various connections, since multiple
        // connections might be managed. It also implements the connection resolver
        // interface which may be used by other components requiring connections.
        $this->app->singleton('db', function ($app) {
            return new DatabaseManager($app, $app['db.factory']);
        });
    }
}

Replace usages of 'bindShared' with 'singleton'


<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/autoloader.php';

/*
 * If there's a 7-character ID, use that
 */
if ( isset($_GET['id']) && strlen($_GET['id']) == 7)
{
    $id = $_GET['id'];
}

$database = new Database;
$db = $database->connect();

if (!$db)
{
    echo json_encode('Error');
    exit;
}

/*
 * Get the business record
 */
$business = new Business;
$business->db = $db;
$business->id = $id;
$biz = $business->fetch();

if (!is_array($biz))
{
    echo json_encode('Error');
    exit;
}

echo json_encode($biz);

<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/autoloader.php';

/*
 * Use the identifier passed in the URL
 */
if ( isset($_GET['id']) && strlen($_GET['id']) == 7)
{
    $id = $_GET['id'];
}

$database = new Database;
$db = $database->connect();

if (!$db)
{
    header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500);
    echo json_encode('Error');
    exit;
}

/*
 * Get the business record
 */
$business = new Business;
$business->db = $db;
$business->id = $id;
$biz = $business->fetch();

if (!is_array($biz))
{
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    echo json_encode('Error');
    exit;
}

echo json_encode($biz);

Add HTTP headers to API errors

Add HTTP headers to API errors


<?php
/**
 * @package       johnpancoast/php-common
 * @copyright (c) 2015-2018 John Pancoast
 * @license       MIT
 */

namespace Pancoast\Common\Entity;

/**
 * Contract for entities that have a time range
 *
 * @author John Pancoast <johnpancoaster@gmail.com>
 */
interface TimeRangeInterface
{
    /**
     * Get start time
     *
     * Format will be 'hh:mm'
     *
     * @return string
     */
    public function getStartTime();

    /**
     * Set start time
     *
     * Accepts format 'hh:mm'
     *
     * @return string
     */
    public function setStartTime();

    /**
     * Get end time
     *
     * Format will be 'hh:mm'
     *
     * @return string
     */
    public function getEndTime();

    /**
     * Set start time
     *
     * Accepts format 'hh:mm'
     *
     * @return string
     */
    public function setEndTime();
}

<?php
/**
 * @package       johnpancoast/php-common
 * @copyright (c) 2015-2018 John Pancoast
 * @license       MIT
 */

namespace Pancoast\Common\Entity;

/**
 * Contract for entities that have a time range
 *
 * Only hour and minute properties are relevant for \DateTime objects.
 *
 * @author John Pancoast <johnpancoaster@gmail.com>
 */
interface TimeRangeInterface
{
    /**
     * Get start time
     *
     * @return \DateTime
     */
    public function getStartTime();

    /**
     * Set start time
     *
     * @param \DateTime $startTime
     */
    public function setStartTime(\DateTime $startTime);

    /**
     * Get end time
     *
     * @return \DateTime
     */
    public function getEndTime();

    /**
     * Set start time
     *
     * @param \DateTime $endTime
     */
    public function setEndTime(\DateTime $endTime);
}

Change TimeRange interface to use \DateTime objects


<?php namespace GeneaLabs\LaravelGovernor\Listeners;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class CreatedListener
{
    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function handle(string $event, array $models)
    {
        if (str_contains($event, "Hyn\Tenancy\Models\Website")
            || str_contains($event, "Hyn\Tenancy\Models\Hostname")
            || ! Schema::hasTable('roles')
        ) {
            return;
        }

        collect($models)
            ->filter(function ($model) {
                return $model instanceof Model
                    && get_class($model) === config('genealabs-laravel-governor.models.auth');
            })
            ->each(function ($model) {
                $model->roles()->attach('Member');
            });
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Listeners;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class CreatedListener
{
    /**
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.StaticAccess)
     */
    public function handle(string $event, array $models)
    {
        if (str_contains($event, "Hyn\Tenancy\Models\Website")
            || str_contains($event, "Hyn\Tenancy\Models\Hostname")
            || ! Schema::hasTable('governor_roles')
        ) {
            return;
        }

        collect($models)
            ->filter(function ($model) {
                return $model instanceof Model
                    && get_class($model) === config('genealabs-laravel-governor.models.auth');
            })
            ->each(function ($model) {
                $model->roles()->attach('Member');
            });
    }
}

Fix attaching new user to Membersrole

Fix attaching new user to Membersrole


<?php
namespace Nats;

/**
 * Class EncodedConnection
 * @package Nats
 */
class EncodedConnection extends Connection {

    /**
     * @var Encoder|null
     */
    private $encoder = null;

    /**
     * EncodedConnection constructor.
     * @param ConnectionOptions|null $options
     * @param Encoder|null $encoder
     */
    public function __construct(ConnectionOptions $options = null, Encoder $encoder = null) {
        $this->encoder = $encoder;
        parent::__construct($options);
    }

    /**
     * @param string $subject
     * @param string $payload
     * @param mixed $callback
     * @param int $wait
     */
    public function request($subject, $payload, $callback, $wait = 1) {
        $payload = $this->encoder->encode($payload);
        $decode_callback = function ($payload) use ($callback) {
            $callback(json_decode($payload));
        };
        parent::request($subject, $payload, $decode_callback, $wait);
    }

    /**
     * @param string $subject
     * @param null $payload
     */
    public function publish($subject, $payload = null) {
        $payload = $this->encoder->encode($payload);
        parent::publish($subject, $payload);
    }

    /**
     * @param string $subject
     * @param \Closure $callback
     */
    public function subscribe($subject, \Closure $callback) {
        $decode_callback = function ($payload) use ($callback) {
            $callback(json_decode($payload));
        };
        parent::subscribe($subject, $decode_callback);
    }

}

<?php
namespace Nats;

/**
 * Class EncodedConnection
 * @package Nats
 */
class EncodedConnection extends Connection {

    /**
     * @var Encoder|null
     */
    private $encoder = null;

    /**
     * EncodedConnection constructor.
     * @param ConnectionOptions|null $options
     * @param Encoder|null $encoder
     */
    public function __construct(ConnectionOptions $options = null, Encoder $encoder = null) {
        $this->encoder = $encoder;
        parent::__construct($options);
    }

    /**
     * @param string $subject
     * @param string $payload
     * @param mixed $callback
     * @param int $wait
     */
    public function request($subject, $payload, $callback, $wait = 1) {
        $payload = $this->encoder->encode($payload);
        $decode_callback = function ($payload) use ($callback) {
            $callback($this->encoder->decode($payload));
        };
        parent::request($subject, $payload, $decode_callback, $wait);
    }

    /**
     * @param string $subject
     * @param null $payload
     */
    public function publish($subject, $payload = null) {
        $payload = $this->encoder->encode($payload);
        parent::publish($subject, $payload);
    }

    /**
     * @param string $subject
     * @param \Closure $callback
     */
    public function subscribe($subject, \Closure $callback) {
        $decode_callback = function ($payload) use ($callback) {
            $callback($this->encoder->decode($payload));
        };
        parent::subscribe($subject, $decode_callback);
    }

}

Use decode from the encoder

Use decode from the encoder


<?php
/* @var $installer Ikonoshirt_Pbkdf2_Model_Mysql4_Setup */
$installer = $this;

$installer->startSetup();

$installer->getConnection()->modifyColumn(
    $installer->getTable('admin/user'), 'password', 'VARCHAR(800) default NULL'
);

$installer->updateAttribute('customer', 'password_hash', 'backend_type', 'text');

// TODO copy all passwords to the eav_entity_text table and encrypt the hashes with PBKDF2

$installer->endSetup();

<?php
/* @var $installer Ikonoshirt_Pbkdf2_Model_Mysql4_Setup */
$installer = $this;

$installer->startSetup();

$installer->getConnection()->modifyColumn(
    $installer->getTable('admin/user'), 'password', 'VARCHAR(800) default NULL'
);

$newAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'password_hash');
$currentAttribute = clone $newAttribute;
if ('text' !== $currentAttribute->getBackendType()) {
    $newAttribute = clone $currentAttribute;
    $newAttribute->setBackendType('text');

    $currentTable = $currentAttribute->getBackend()->getTable();
    $newTable = $newAttribute->getBackend()->getTable();

    // Copy password hashes over to the text attribute value table
    $cols = array('entity_type_id', 'attribute_id', 'entity_id', 'value');
    $sql = $installer->getConnection()->select()
            ->from($currentTable, $cols)
            ->where('attribute_id=?', $currentAttribute->getId())
            ->insertFromSelect($newTable, $cols);
    $installer->getConnection()->query($sql);

    $installer->updateAttribute('customer', 'password_hash', 'backend_type', 'text');

    // Delete values from old value table
    $installer->getConnection()->delete($currentTable, array('attribute_id=?' => $currentAttribute->getId()));
}

// TODO encrypt the hashes with PBKDF2

$installer->endSetup();

Implement copy of existing password hashes to new value table


<?php

/*
 * Provides a GoogleMap() function to DataObject objects.
 *
 * @author Uncle Cheese
 * @package mappable
 */
class MappableDataObjectSet extends Extension {

	public function GoogleMap($width = null, $height = null) {
		$gmap = GoogleMapUtil::get_map($this->owner);
		$w = $width ? $width : GoogleMapUtil::$map_width;
		$h = $height ? $height : GoogleMapUtil::$map_height;
		$gmap->setSize($w,$h);
		return $gmap;
	}

}

<?php

/*
 * Provides a GoogleMap() function to DataObject objects.
 *
 * @author Uncle Cheese
 * @package mappable
 */
class MappableDataObjectSet extends Extension {

	public function RenderMap($width = null, $height = null) {
		$gmap = MapUtil::get_map($this->owner);
		$w = $width ? $width : MapUtil::$map_width;
		$h = $height ? $height : MapUtil::$map_height;
		$gmap->setSize($w,$h);
		return $gmap;
	}

}

WIP: Change reference from google map to be generic


<?php
/**
 * This file is part of phpDocumentor.
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 *
 *  @copyright 2010-2017 Mike van Riel<mike@phpdoc.org>
 *  @license   http://www.opensource.org/licenses/mit-license.php MIT
 *  @link      http://phpdoc.org
 */

namespace phpDocumentor\Application\Stage;

use phpDocumentor\Application\Configuration\ConfigurationFactory;
use phpDocumentor\Application\Configuration\Factory\Version3;
use phpDocumentor\DomainModel\Uri;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \phpDocumentor\Application\Stage\Configure
 */
class ConfigureTest extends TestCase
{
    /**
     * @use \phpDocumentor\Application\Configuration\ConfigurationFactory;
     * @use \phpDocumentor\Application\Configuration\Factory\Version3;
     * @use \phpDocumentor\DomainModel\Uri;
     */
    public function testInvokeOverridesConfig()
    {
        $configFactory = new ConfigurationFactory(
            [new Version3(__DIR__ . '/../../../../../data/xsd/phpdoc.xsd')],
            new Uri(__DIR__ . '/../../../data/phpDocumentor3XML.xml')
        );

        $fixture = new Configure($configFactory);

        $result = $fixture(['force' => true]);

        $this->assertFalse($result['phpdocumentor']['use-cache']);
    }
}

<?php
/**
 * This file is part of phpDocumentor.
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 *
 *  @copyright 2010-2017 Mike van Riel<mike@phpdoc.org>
 *  @license   http://www.opensource.org/licenses/mit-license.php MIT
 *  @link      http://phpdoc.org
 */

namespace phpDocumentor\Application\Stage;

use phpDocumentor\Application\Configuration\ConfigurationFactory;
use phpDocumentor\Application\Configuration\Factory\Version3;
use phpDocumentor\DomainModel\Uri;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \phpDocumentor\Application\Stage\Configure
 */
class ConfigureTest extends TestCase
{
    /**
     * @use \phpDocumentor\Application\Configuration\ConfigurationFactory;
     * @use \phpDocumentor\Application\Configuration\Factory\Version3;
     * @use \phpDocumentor\DomainModel\Uri;
     */
    public function testInvokeOverridesConfig()
    {
        $configFactory = new ConfigurationFactory(
            [new Version3(__DIR__ . '/../../../../../data/xsd/phpdoc.xsd')],
            new Uri(__DIR__ . str_replace('/', DIRECTORY_SEPARATOR, '/../../../data/phpDocumentor3XML.xml'))
        );

        $fixture = new Configure($configFactory);

        $result = $fixture(['force' => true]);

        $this->assertFalse($result['phpdocumentor']['use-cache']);
    }
}

Replace dir separator for windows

Replace dir separator for windows


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

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

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
$allowedIps = [gethostbyname('development'), '127.0.0.1', 'fe80::1', '::1'];

if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], $allowedIps) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check ' . basename(__FILE__) . ' for more information.');
}

$loader = require_once __DIR__ . '/../app/bootstrap.php.cache';
Debug::enable();

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

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request  = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Add development ip to allowed ips

Add development ip to allowed ips


<?php

namespace Kunstmaan\SitemapBundle\Controller;

use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SitemapController extends Controller
{
    /**
     * Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
     *
     * @Route("/sitemap.{mode}", name="KunstmaanSitemapBundle_sitemap")
     * @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
     *
     * @param $mode
     *
     * @return array
     */
    public function sitemapAction($mode)
    {
        $em = $this->getDoctrine()->getManager();
        $locale = $this->getRequest()->getLocale();
        $securityContext = $this->container->get('security.context');
        $aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
        $nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);

        return array(
            'nodemenu' => $nodeMenu,
        );
    }

}

<?php

namespace Kunstmaan\SitemapBundle\Controller;

use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SitemapController extends Controller
{
    /**
     * Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
     *
     * @Route("/sitemap.{_format}", name="KunstmaanSitemapBundle_sitemap", requirements={"_format" = "xml"})
     * @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
     *
     * @param $mode
     *
     * @return array
     */
    public function sitemapAction()
    {
        $em = $this->getDoctrine()->getManager();
        $locale = $this->getRequest()->getLocale();
        $securityContext = $this->container->get('security.context');
        $aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
        $nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);

        return array(
            'nodemenu' => $nodeMenu,
        );
    }

}

Use built-in _format to enable xml output


<?php

namespace Padam87\CronBundle\Command;

use Doctrine\Common\Annotations\AnnotationReader;
use Padam87\CronBundle\Util\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DumpCommand extends ConfigurationAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('cron:dump')
            ->setDescription('Dumps jobs to a crontab file')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->dump($input);

        return 0;
    }

    protected function dump(InputInterface $input): string
    {
        $reader = new AnnotationReader();
        $helper = new Helper($this->getApplication(), $reader);

        $tab = $helper->createTab($input, $this->getConfiguration());

        $path = strtolower(
            sprintf(
                '%s.crontab',
                $this->getApplication()->getName()
            )
        );

        file_put_contents($path, (string) $tab);

        return $path;
    }
}

<?php

namespace Padam87\CronBundle\Command;

use Doctrine\Common\Annotations\AnnotationReader;
use Padam87\CronBundle\Util\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DumpCommand extends ConfigurationAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('cron:dump')
            ->setDescription('Dumps jobs to a crontab file')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->dump($input);

        return self::SUCCESS;
    }

    protected function dump(InputInterface $input): string
    {
        $reader = new AnnotationReader();
        $helper = new Helper($this->getApplication(), $reader);

        $tab = $helper->createTab($input, $this->getConfiguration());

        $path = strtolower(
            sprintf(
                '%s.crontab',
                $this->getApplication()->getName()
            )
        );

        file_put_contents($path, (string) $tab);

        return $path;
    }
}

Use the exit code constant

Use the exit code constant


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Namespace Tablenames
    |--------------------------------------------------------------------------
    |
    | If this option is set to true, all tablenames will be auto-generated from
    | namespace. For example a class with the namespace 'Acme\User' will have
    | the tablename 'acme_user'.
    |
    */

    'namespace_tablenames' => true,

    /*
    |--------------------------------------------------------------------------
    | Morph Class Abbreviations
    |--------------------------------------------------------------------------
    |
    | If this option is enabled, all morph classnames will be converted to a
    | short lower case abbreviation. For example 'Acme\User' will be shortened
    | to 'user'.
    |
    */

    'morphclass_abbreviations' => true,

    /*
    |--------------------------------------------------------------------------
    | Models Namespace
    |--------------------------------------------------------------------------
    |
    | If a models namespace is defined, only the entities and value objects in
    | the sub-namespace will be scanned by the schema commands. Also you only
    | have to name the sub-namespace in annotations (i. e. for the
    | relatedEntity parameter of the @Relation annotation).
    |
    */

    'models_namespace' => 'Examunity\Test',

    /*
    |--------------------------------------------------------------------------
    | Presenters Namespace
    |--------------------------------------------------------------------------
    |
    | If a presenters namespace is defined, only the classes in the sub-namespace
    | will be scanned by the schema commands.
    |
    */

    'presenters_namespace' => 'Examunity\Test',

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Namespace Tablenames
    |--------------------------------------------------------------------------
    |
    | If this option is set to true, all tablenames will be auto-generated from
    | namespace. For example a class with the namespace 'Acme\User' will have
    | the tablename 'acme_user'.
    |
    */

    'namespace_tablenames' => true,

    /*
    |--------------------------------------------------------------------------
    | Morph Class Abbreviations
    |--------------------------------------------------------------------------
    |
    | If this option is enabled, all morph classnames will be converted to a
    | short lower case abbreviation. For example 'Acme\User' will be shortened
    | to 'user'.
    |
    */

    'morphclass_abbreviations' => true,

    /*
    |--------------------------------------------------------------------------
    | Models Namespace
    |--------------------------------------------------------------------------
    |
    | If a models namespace is defined, only the entities and value objects in
    | the sub-namespace will be scanned by the schema commands. Also you only
    | have to name the sub-namespace in annotations (i. e. for the
    | relatedEntity parameter of the @Relation annotation).
    |
    */

    'models_namespace' => '',

    /*
    |--------------------------------------------------------------------------
    | Presenters Namespace
    |--------------------------------------------------------------------------
    |
    | If a presenters namespace is defined, only the classes in the sub-namespace
    | will be scanned by the schema commands.
    |
    */

    'presenters_namespace' => '',

];

Reset config to default values

Reset config to default values


<?php

use GuzzleHttp\Client;
use VDB\Spider\RequestHandler\GuzzleRequestHandler;
use VDB\Spider\Spider;

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

// Create Spider
$spider = new Spider('http://httpbin.org/basic-auth/foo/bar');

// Set a custom request handler that does basic auth
$requestHandler = new GuzzleRequestHandler();
$requestHandler->setClient(new Client(['auth' => ['foo', 'bar'], 'http_errors' => false]));
$spider->getDownloader()->setRequestHandler($requestHandler);

// Execute crawl
$spider->crawl();

// Finally we could do some processing on the downloaded resources
// In this example, we will echo the title of all resources
echo "\n\nRESPONSE: ";
foreach ($spider->getDownloader()->getPersistenceHandler() as $resource) {
    echo "\n" . $resource->getResponse()->getStatusCode() . ": " . $resource->getResponse()->getReasonPhrase();
    echo "\n" . $resource->getResponse()->getBody();
}

<?php

use GuzzleHttp\Client;
use VDB\Spider\RequestHandler\GuzzleRequestHandler;
use VDB\Spider\Spider;

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

// Create Spider
$spider = new Spider('http://httpbin.org/basic-auth/foo/bar');

$requestHandler = new GuzzleRequestHandler();
// Set a custom Guzzle client that does basic auth. See Guzzle docs on how to use other types of authentication.
$requestHandler->setClient(new Client(['auth' => ['foo', 'bar', 'basic'], 'http_errors' => false]));
$spider->getDownloader()->setRequestHandler($requestHandler);

// Execute crawl
$spider->crawl();

// Finally we could do some processing on the downloaded resources
// In this example, we will echo the title of all resources
echo "\n\nRESPONSE: ";
foreach ($spider->getDownloader()->getPersistenceHandler() as $resource) {
    echo "\n" . $resource->getResponse()->getStatusCode() . ": " . $resource->getResponse()->getReasonPhrase();
    echo "\n" . $resource->getResponse()->getBody();
}

Clarify how to force Basic Auth

Clarify how to force Basic Auth


<?php

/**
 * @package ConLayout
 * @author Cornelius Adams (conlabz GmbH) <cornelius.adams@conlabz.de>
 */

namespace ConLayout\Filter;

use Laminas\Filter\FilterInterface;
use Laminas\View\Helper\ViewModel;
use Laminas\View\Model\ModelInterface;
use Laminas\View\Renderer\PhpRenderer;
use Laminas\View\Variables;

class DebugFilter implements FilterInterface
{
    /**
     * @var PhpRenderer
     */
    private PhpRenderer $phpRenderer;

    /**
     * DebugFilter constructor.
     * @param PhpRenderer $phpRenderer
     */
    public function __construct(PhpRenderer $phpRenderer)
    {
        $this->phpRenderer = $phpRenderer;
    }

    /**
     * @inheritDoc
     */
    public function filter($value)
    {
        /** @var ViewModel $viewModel */
        $viewModel = $this->phpRenderer->viewModel()->getCurrent();

        if (!$viewModel instanceof ModelInterface) {
            return $value;
        }

        /** @var Variables $vars */
        $vars = $this->phpRenderer->vars();
        $blockId = $viewModel->getOption('block_id');
        if ($blockId && !$vars->count()) {
            $opening = sprintf('<!--[%s]-->', $blockId);
            $closing = sprintf('<!--[/%s]-->', $blockId);
            if (0 !== strpos($value, $opening)) {
                $value = $opening . $value . $closing;
            }
        }
        return $value;
    }
}

<?php

/**
 * @package ConLayout
 * @author Cornelius Adams (conlabz GmbH) <cornelius.adams@conlabz.de>
 */

namespace ConLayout\Filter;

use Laminas\Filter\FilterInterface;
use Laminas\View\Helper\ViewModel;
use Laminas\View\Model\ModelInterface;
use Laminas\View\Renderer\PhpRenderer;
use Laminas\View\Variables;

class DebugFilter implements FilterInterface
{
    /**
     * @var PhpRenderer
     */
    private $phpRenderer;

    /**
     * DebugFilter constructor.
     * @param PhpRenderer $phpRenderer
     */
    public function __construct(PhpRenderer $phpRenderer)
    {
        $this->phpRenderer = $phpRenderer;
    }

    /**
     * @inheritDoc
     */
    public function filter($value)
    {
        /** @var ViewModel $viewModel */
        $viewModel = $this->phpRenderer->viewModel()->getCurrent();

        if (!$viewModel instanceof ModelInterface) {
            return $value;
        }

        /** @var Variables $vars */
        $vars = $this->phpRenderer->vars();
        $blockId = $viewModel->getOption('block_id');
        if ($blockId && !$vars->count()) {
            $opening = sprintf('<!--[%s]-->', $blockId);
            $closing = sprintf('<!--[/%s]-->', $blockId);
            if (0 !== strpos($value, $opening)) {
                $value = $opening . $value . $closing;
            }
        }
        return $value;
    }
}

Revert typed property to retain php 7.3 compatibility


<?php

namespace Step\Acceptance;

use \AcceptanceTester as Tester;

class EditView extends Tester
{
    /**
     * Wait for for the edit view to become visible
     */
    public function waitForEditViewVisible()
    {
        $I = $this;
        $I->waitForElementVisible('#EditView');
    }

    public function clickSaveButton()
    {
        $I = $this;
        $I->executeJS('window.scrollTo(0,0); return true;');
        $I->waitForText('Save');
        $I->click('Save');
    }
}

<?php

namespace Step\Acceptance;

use \AcceptanceTester as Tester;

class EditView extends Tester
{
    /**
     * Wait for for the edit view to become visible
     */
    public function waitForEditViewVisible()
    {
        $I = $this;
        $I->waitForElementVisible('#EditView');
    }

    public function clickSaveButton()
    {
        $I = $this;
        $I->executeJS('window.scrollTo(0,0); return true;');
        $I->click('Save');
    }
}

Remove waitForText in Save function.

Remove waitForText in Save function.

It doesn't work quite right.


<?php
// Copyright 2019 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

error_reporting((E_ALL | E_STRICT) & ~E_WARNING);
ini_set('display_errors', 1);

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

Header('Access-Control-Allow-Origin: *');
Header('Content-Type: application/json');

$environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']);
if (!$environment->isValid())
    dieWithError('Unrecognized volunteer portal environment.');

echo json_encode([
    'contactName'   => 'Peter',
    'contactTarget' => 'mailto:' . $environment->getContact(),
    'title'         => $environment->getName(),

    'events' => [
        [
            'name'                  => 'AnimeCon 2021',
            'enablePortal'          => false,
            'enableRegistration'    => true,
            'timezone'              => 'Europe/Amsterdam',
            'website'               => 'https://www.animecon.nl/',
        ],
    ],
]);

<?php
// Copyright 2019 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

error_reporting((E_ALL | E_STRICT) & ~E_WARNING);
ini_set('display_errors', 1);

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

Header('Access-Control-Allow-Origin: *');
Header('Content-Type: application/json');

$environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']);
if (!$environment->isValid())
    dieWithError('Unrecognized volunteer portal environment.');

echo json_encode([
    'contactName'   => 'Peter',
    'contactTarget' => 'mailto:' . $environment->getContact(),
    'title'         => $environment->getName(),

    'events' => [
        [
            'name'                  => 'AnimeCon 2021',
            'enablePortal'          => false,
            'enableRegistration'    => false,
            'timezone'              => 'Europe/Amsterdam',
            'website'               => 'https://www.animecon.nl/',
        ],
    ],
]);

Disable the registration portal for now

Disable the registration portal for now


<?php

use Illuminate\Database\Migrations\Migration;

class AlterConversionsRemoveOnUpdateFromPaidAtColumn extends Migration
{
    public function up()
    {
        // Due to the doctrine bug updating manually
        // https://github.com/laravel/framework/issues/16526
        $sql = 'ALTER TABLE `conversions` CHANGE `paid_at` `paid_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP';
        DB::update($sql);
    }

    public function down()
    {
        $sql = 'ALTER TABLE `conversions` CHANGE `paid_at` `paid_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
        DB::update($sql);
    }
}

<?php

use Illuminate\Database\Migrations\Migration;

class AlterConversionsRemoveOnUpdateFromPaidAtColumn extends Migration
{
    public function up()
    {
        // Due to the doctrine bug updating manually
        // https://github.com/laravel/framework/issues/16526
        $sql = 'ALTER TABLE `conversions` CHANGE `paid_at` `paid_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP';
        DB::update($sql);
        $sql = 'ALTER TABLE `conversions` ALTER COLUMN `paid_at` DROP DEFAULT';
        DB::update($sql);
    }

    public function down()
    {
        $sql = 'ALTER TABLE `conversions` CHANGE `paid_at` `paid_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
        DB::update($sql);
    }
}

Drop default value from `paid_at` column in Conversions table

remp/remp#739


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$app->group(['namespace' => 'Begin\Http\Controllers\Api\v1','prefix' => 'api/v1'], function ($app)
{
	$app->post('register','AuthController@postRegister');
	$app->post('login','AuthController@postLogin');
});

$app->group(['namespace' => 'Begin\Http\Controllers\Api\v1',
			 'prefix' => 'api/v1', 'middleware' => 'jwt.auth'], function ($app)
{
	$app->get('validate_token', 'AuthController@validateToken');
	$app->get('tasks', 'TasksController@index');

});

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$app->group(['namespace' => 'Begin\Http\Controllers\Api\v1','prefix' => 'api/v1'], function ($app)
{
	$app->post('register','AuthController@postRegister');
	$app->post('login','AuthController@postLogin');
});

$app->group(['namespace' => 'Begin\Http\Controllers\Api\v1',
			 'prefix' => 'api/v1', 'middleware' => 'jwt.auth'], function ($app)
{
	$app->get('validate_token', 'AuthController@validateToken');
	$app->get('tasks', 'TasksController@index');
	$app->get('tasks/{task}', 'TasksController@show');
});

Add the route to get a specific task created by the authenticated user


<?php namespace TightenCo\Jigsaw;

use Exception;
use TightenCo\Jigsaw\IterableObject;

class ViewData extends IterableObject
{
    private $data;
    private $globals = ['extends', 'section', 'content', 'link'];
    public $item;

    public static function withCollectionItem($data, $collectionName, $itemName)
    {
        $viewData = new static($data);
        $viewData->setCollectionItem($collectionName, $itemName);

        return $viewData;
    }

    public function __call($method, $args)
    {
        return $this->getHelper($method)->__invoke($this, ...$args);
    }

    private function getHelper($name)
    {
        $helper = $this->has('helpers') ? $this->helpers->{$name} : null;

        return $helper ?: function() use ($name) {
            throw new Exception("No helper function named '$name' in 'config.php'.");
        };
    }

    private function setCollectionItem($collection, $item)
    {
        if ($this->has($collection)) {
            $this->item = $this->get($collection)->get($item);
            $this->setGloballyAvailableItemVariables();
        }
    }

    private function setGloballyAvailableItemVariables()
    {
        collect($this->globals)->each(function ($variable) {
            $this[$variable] = $this->item->{$variable};
        });
    }
}

<?php namespace TightenCo\Jigsaw;

use Exception;
use TightenCo\Jigsaw\IterableObject;

class ViewData extends IterableObject
{
    private $data;
    private $globals = ['extends', 'section', 'content', 'link'];
    public $item;

    public static function withCollectionItem($data, $collectionName, $itemName)
    {
        $viewData = new static($data);
        $viewData->setCollectionItem($collectionName, $itemName);

        return $viewData;
    }

    public function __call($method, $args)
    {
        return $this->getHelper($method)->__invoke($this, ...$args);
    }

    private function getHelper($name)
    {
        $helper = $this->has('helpers') ? $this->helpers->{$name} : null;

        return $helper ?: function() use ($name) {
            throw new Exception("No helper function named '$name' in 'config.php'.");
        };
    }

    private function setCollectionItem($collection, $item)
    {
        if ($this->has($collection)) {
            $this->item = $this->get($collection)->get($item);
            $this->addSingularCollectionReference($collection);
            $this->setGloballyAvailableItemVariables();
        }
    }

    private function addSingularCollectionReference($collection)
    {
        if (str_singular($collection) != $collection) {
            $this->{str_singular($collection)} = $this->item;
        };
    }

    private function setGloballyAvailableItemVariables()
    {
        collect($this->globals)->each(function ($variable) {
            $this[$variable] = $this->item->{$variable};
        });
    }
}

Add reference to CollectionItems by singular collection name, if possible


<?php

/**
 * Autoload register file.
 *
 * @copyright Copyright (c) 2015 Hervé Guenot
 * @license https://github.com/hguenot/phpstream/blob/master/LICENSE The MIT License (MIT)
 * @link https://github.com/hguenot/phpstream#readme Readme
 */

spl_autoload_register(function ($class) {
	$basePackage = 'phpstream\\';
	if (substr($class, 0, strlen($basePackage)) == $basePackage) {
	   include __DIR__ . DIRECTORY_SEPARATOR . ereg_replace('\\\\', DIRECTORY_SEPARATOR, $class) . '.php';
	}
});

<?php

/**
 * Autoload register file.
 *
 * @copyright Copyright (c) 2015 Hervé Guenot
 * @license https://github.com/hguenot/phpstream/blob/master/LICENSE The MIT License (MIT)
 * @link https://github.com/hguenot/phpstream#readme Readme
 */

spl_autoload_register(function ($class) {
	$basePackage = 'phpstream\\';
	if (substr($class, 0, strlen($basePackage)) == $basePackage) {
	   include __DIR__ . DIRECTORY_SEPARATOR . preg_replace('/\\\/', DIRECTORY_SEPARATOR, $class) . '.php';
	}
});

Use preg_replace instead of ereg_replace


<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

Package :: <?php echo $context->name; ?>

<?php echo $context->summary; ?>

            <?php
            echo nl2br(trim($context->description));
            ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Releases

            <?php
             foreach ($context as $version => $release): ?>

                <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?>
                <?php echo $release['stability']; ?>
                <?php echo $version; ?> <?php echo $release['stability']; ?>
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>
                <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download

            <?php endforeach; ?>

<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

Package :: <?php echo $context->name; ?>

<?php echo $context->summary; ?>

            <?php
            echo nl2br(trim($context->description));
            ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Releases

            <?php
             foreach ($context as $version => $release): ?>

                <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?>
                <?php echo $release['stability']; ?>
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>
                <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download

            <?php endforeach; ?>

Remove duplicate version number and stability.


                {!! Form::open(['route' => 'blog::admin.auth.logout.post']) !!}
                <button type="submit" class="btn-link nav-link">Log out</button>
                {!! Form::close() !!}

            {{-- TODO: fix padding (check which class adds the padding)--}}

                {!! Form::open(['route' => 'blog::admin.auth.logout.post']) !!}
                <button type="submit" class="btn-link nav-link padding-none text-muted">Log out</button>
                {!! Form::close() !!}

Remove excessive padding from footer elements


<?php namespace App\Providers;

use InspireCommand;
use Illuminate\Support\ServiceProvider;

class ArtisanServiceProvider extends ServiceProvider {

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->commands('App\Console\InspireCommand');
	}

}

<?php namespace App\Providers;

use InspireCommand;
use Illuminate\Support\ServiceProvider;

class ArtisanServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->commands('App\Console\InspireCommand');
	}

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

}

Make Artisan service provider be deferred.


<?php

namespace Oro\Bundle\SecurityBundle\Http\Firewall;

use Oro\Bundle\OrganizationBundle\Entity\Manager\OrganizationManager;
use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;

class ContextListener
{
    /**
     * @var SecurityContextInterface
     */
    protected $context;

    /**
     * @var OrganizationManager
     */
    protected $manager;

    /**
     * @param SecurityContextInterface $context
     * @param OrganizationManager      $manager
     */
    public function __construct(SecurityContextInterface $context, OrganizationManager $manager)
    {
        $this->context = $context;
        $this->manager = $manager;
    }

    /**
     * Refresh organization context in token
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $token = $this->context->getToken();
        if ($token instanceof UsernamePasswordOrganizationToken) {
            $token->setOrganizationContext(
                $this->manager->getOrganizationById($token->getOrganizationContext()->getId())
            );
        }
    }
}

<?php

namespace Oro\Bundle\SecurityBundle\Http\Firewall;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;

use Oro\Bundle\OrganizationBundle\Entity\Manager\OrganizationManager;
use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;

class ContextListener
{
    /**
     * @var SecurityContextInterface
     */
    protected $context;

    /**
     * @var OrganizationManager
     */
    protected $manager;

    /**
     * @param SecurityContextInterface $context
     * @param OrganizationManager      $manager
     */
    public function __construct(SecurityContextInterface $context, OrganizationManager $manager)
    {
        $this->context = $context;
        $this->manager = $manager;
    }

    /**
     * Refresh organization context in token
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $token = $this->context->getToken();
        if ($token instanceof UsernamePasswordOrganizationToken) {
            $token->setOrganizationContext(
                $this->manager->getOrganizationById($token->getOrganizationContext()->getId())
            );
        }
    }
}

OEE-54: Modify ACL. Refactor ACL Walker.
   - Add set organization listener


<?php

namespace Isotop\Cargo\Pusher;

class HTTP extends Abstract_Pusher {

	/**
	 * Send data to receiver.
	 *
	 * @param  mixed $data
	 *
	 * @return mixed
	 */
	public function send( $data ) {
		$options = $this->cargo->config( 'pusher.http', ['url' => ''] );
		$options = is_array( $options ) ? $options : ['url' => ''];

		$json = $this->to_json( $data );

		if ( empty( $json ) ) {
			return false;
		}

		$args = array_merge( [
			'headers' => [
				'Content-Type' => 'application/json; charset=utf-8'
			],
			'body'    => $json,
			'timeout' => 30
		], $options );

		$res = wp_remote_post( $options['url'], $args );

		if ( is_wp_error( $res ) ) {
			$this->save( $args['body'], $res );

			return $res;
		}

		$body = (array) json_decode( $res['body'] );

		if ( empty( $body ) ) {
			return false;
		}

		if ( $body['success'] ) {
			return true;
		}

		$this->save( $args['body'], $res );

		return false;
	}
}

<?php

namespace Isotop\Cargo\Pusher;

class HTTP extends Abstract_Pusher {

	/**
	 * Send data to receiver.
	 *
	 * @param  mixed $data
	 *
	 * @return mixed
	 */
	public function send( $data ) {
		$options = $this->cargo->config( 'pusher.http', ['url' => ''] );
		$options = is_array( $options ) ? $options : ['url' => ''];

		$json = $this->to_json( $data );

		if ( empty( $json ) ) {
			return false;
		}

		$args = array_merge( [
			'headers' => [
				'Content-Type' => 'application/json; charset=utf-8'
			],
			'body'    => $json,
			'timeout' => 30
		], $options );

		$res = wp_remote_post( $options['url'], $args );

		if ( is_wp_error( $res ) ) {
			$this->save( $args['body'], $res );

			return $res;
		}

		$body = (array) json_decode( $res['body'] );

		if ( empty( $body ) ) {
			return false;
		}

		if ( isset( $body['success'] ) && $body['success'] ) {
			return true;
		}

		$this->save( $args['body'], $res );

		return false;
	}
}

Check success exists before using it

Check success exists before using it


<?php /* vim: set colorcolumn= expandtab shiftwidth=2 softtabstop=2 tabstop=4 smarttab: */
namespace BNETDocs\Models\Packet;
class Form extends \BNETDocs\Models\ActiveUser
{
  // possible values for $error:
  const ERROR_ACL_DENIED = 'ACL_DENIED';
  const ERROR_INTERNAL = 'INTERNAL';
  const ERROR_NONE = 'NONE';
  const ERROR_NOT_FOUND = 'NOT_FOUND';
  const ERROR_OUTOFBOUNDS_DIRECTION = 'OUTOFBOUNDS_DIRECTION';
  const ERROR_OUTOFBOUNDS_FORMAT = 'OUTOFBOUNDS_FORMAT';
  const ERROR_OUTOFBOUNDS_ID = 'OUTOFBOUNDS_ID';
  const ERROR_OUTOFBOUNDS_NAME = 'OUTOFBOUNDS_NAME';
  const ERROR_OUTOFBOUNDS_PACKET_ID = 'OUTOFBOUNDS_PACKET_ID';
  const ERROR_OUTOFBOUNDS_REMARKS = 'OUTOFBOUNDS_REMARKS';
  const ERROR_OUTOFBOUNDS_USED_BY = 'OUTOFBOUNDS_USED_BY';
  const ERROR_SUCCESS = 'SUCCESS';

  public $comments;
  public $error;
  public $form_fields;
  public $packet;
  public $products;
}

<?php /* vim: set colorcolumn= expandtab shiftwidth=2 softtabstop=2 tabstop=4 smarttab: */
namespace BNETDocs\Models\Packet;
class Form extends \BNETDocs\Models\ActiveUser implements \JsonSerializable
{
  // possible values for $error:
  const ERROR_ACL_DENIED = 'ACL_DENIED';
  const ERROR_INTERNAL = 'INTERNAL';
  const ERROR_NONE = 'NONE';
  const ERROR_NOT_FOUND = 'NOT_FOUND';
  const ERROR_OUTOFBOUNDS_DIRECTION = 'OUTOFBOUNDS_DIRECTION';
  const ERROR_OUTOFBOUNDS_FORMAT = 'OUTOFBOUNDS_FORMAT';
  const ERROR_OUTOFBOUNDS_ID = 'OUTOFBOUNDS_ID';
  const ERROR_OUTOFBOUNDS_NAME = 'OUTOFBOUNDS_NAME';
  const ERROR_OUTOFBOUNDS_PACKET_ID = 'OUTOFBOUNDS_PACKET_ID';
  const ERROR_OUTOFBOUNDS_REMARKS = 'OUTOFBOUNDS_REMARKS';
  const ERROR_OUTOFBOUNDS_USED_BY = 'OUTOFBOUNDS_USED_BY';
  const ERROR_SUCCESS = 'SUCCESS';

  public $comments;
  public $error;
  public $form_fields;
  public $packet;
  public $products;

  /**
   * Implements the JSON serialization function from the JsonSerializable interface.
   */
  public function jsonSerialize()
  {
    return [
      'comments' => $this->comments,
      'error' => $this->error,
      'form_fields' => $this->form_fields,
      'packet' => $this->packet,
      'products' => $this->products,
    ];
  }
}

Add jsonSerialize() and implement JsonSerializable


<?php

namespace Bob\BuildConfig;

task("default", array("test"));

desc('Sets up development dependencies');
task('dev', array('deps', 'composer.json'));

task('deps', function() {
    if (!is_file('composer.phar')) {
        $src = fopen('http://getcomposer.org/composer.phar', 'rb');
        $dest = fopen('composer.phar', 'w+');

        stream_copy_to_stream($src, $dest);

        fclose($src);
        fclose($dest);

        chmod('composer.phar', 0755);
    }

    if (!is_file('box.phar')) {
        sh('curl -s http://kherge.github.com/Box/installer.php | php');
    }
});

desc("Runs all tests.");
task("test", array("deps", "phpunit.xml", "composer.json"), function() {
    sh("phpunit");
});

fileTask("phpunit.xml", array("phpunit.dist.xml"), function($task) {
    copy($task->prerequisites[0], $task->name);
});

fileTask("composer.json", array("composer.lock", "deps"), function($task) {
    php("composer.phar update --dev");
});

<?php

namespace Bob\BuildConfig;

task("default", array("build"));

desc('Sets up development dependencies');
task('dev', array('deps', 'composer.json'));

task('deps', function() {
    if (!is_file('composer.phar')) {
        $src = fopen('http://getcomposer.org/composer.phar', 'rb');
        $dest = fopen('composer.phar', 'w+');

        stream_copy_to_stream($src, $dest);

        fclose($src);
        fclose($dest);

        chmod('composer.phar', 0755);
    }

    if (!is_file('box.phar')) {
        sh('curl -s http://kherge.github.com/Box/installer.php | php');
    }
});

desc("Runs all tests.");
task("test", array("deps", "phpunit.xml", "composer.json"), function() {
    sh("phpunit");
});

fileTask("phpunit.xml", array("phpunit.dist.xml"), function($task) {
    copy($task->prerequisites[0], $task->name);
});

fileTask("composer.lock", array("composer.json", "deps"), function($task) {
    php("composer.phar update --dev");
});

$libFiles = fileList("*.php")->in("lib/");

fileTask("spark.phar", $libFiles, function($task) {
    sh("php box.phar build", null, ["fail_on_error" => true]);
    println("Built PHAR successfully to 'spark.phar'");
});

desc("Builds the PHAR");
task("build", ["composer.json", "spark.phar"]);

Add 'build' task to build PHAR

Add 'build' task to build PHAR


<?php
/**
 * @title            Advertisement Model Class.
 *
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Mvc / Model
 */

namespace PH7\Framework\Mvc\Model;

defined('PH7') or exit('Restricted access');

use PH7\DbTableName;
use PH7\Framework\Mvc\Model\Engine\Db;

class Ads extends Engine\Model
{
    /**
     * Adding an Advertisement Click.
     *
     * @param int $iAdsId
     *
     * @return void
     */
    public static function setClick($iAdsId)
    {
        $rStmt = Db::getInstance()->prepare('UPDATE' . Db::prefix(DbTableName::AD) . 'SET clicks = clicks+1 WHERE adsId = :id LIMIT 1');
        $rStmt->bindValue(':id', $iAdsId, \PDO::PARAM_INT);
        $rStmt->execute();
        Db::free($rStmt);
    }
}

<?php
/**
 * @title            Advertisement Model Class.
 *
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Mvc / Model
 */

namespace PH7\Framework\Mvc\Model;

defined('PH7') or exit('Restricted access');

use PH7\DbTableName;
use PH7\Framework\Mvc\Model\Engine\Db;

class Ads extends Engine\Model
{
    /**
     * Adding an Advertisement Click.
     *
     * @param int $iAdsId
     *
     * @return void
     */
    public static function setClick($iAdsId)
    {
        $sSql = 'UPDATE' . Db::prefix(DbTableName::AD) . 'SET clicks = clicks+1 WHERE adsId = :id LIMIT 1';
        $rStmt = Db::getInstance()->prepare($sSql);
        $rStmt->bindValue(':id', $iAdsId, \PDO::PARAM_INT);
        $rStmt->execute();
        Db::free($rStmt);
    }
}

Store SQL query into variable

[Readability] Store SQL query into variable


<?php

namespace MyTravel\Core\Controller;

use Patchwork\JSqueeze;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class Js {

  public function viewJsBundle(Request $request) {
    $sq = new JSqueeze();
    $minifiedJs = array();
    // Fetch all js files from view
    $dirFiles = Finder::create()
      ->files()
      ->in(Config::get()->directories['views'] . '/' . Config::get()->view . '/js')
      ->name('*.js');

    foreach ($dirFiles as $splFile) {

      if (App::get()->inDevelopment()) {
        array_push($minifiedJs, $splFile->getContents() . PHP_EOL);
      } else {
        array_push($minifiedJs, $sq->squeeze($splFile->getContents()));
      }
    }
    $response = new Response(implode('', $minifiedJs));
    $response->headers->set('Content-Type', 'application/javascript');
    return $response;
  }

}

<?php

namespace MyTravel\Core\Controller;

use Patchwork\JSqueeze;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use MyTravel\Core\OutputInterface;

class Js implements OutputInterface {

  public function viewJsBundle(Request $request) {
    $sq = new JSqueeze();
    $minifiedJs = array();
    // Fetch all js files from view
    $dirFiles = Finder::create()
      ->files()
      ->in(Config::get()->directories['views'] . '/' . Config::get()->view . '/js')
      ->name('*.js');

    foreach ($dirFiles as $splFile) {

      if (App::get()->inDevelopment()) {
        array_push($minifiedJs, $splFile->getContents() . PHP_EOL);
      } else {
        array_push($minifiedJs, $sq->squeeze($splFile->getContents()));
      }
    }

    return implode('', $minifiedJs);
  }

  public function output(GetResponseForControllerResultEvent $event) {
    $response = new Response($event->getControllerResult());
    $response->headers->set('Content-Type', 'application/javascript');
    return $response;
  }

}

Make use of outputcontroller for caching js resonse


<?php
/* ------------------------------------------------------------------------ *\
 * Functions: Rewrites
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___pwa_rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top");
}
add_action("init", "__gulp_init_namespace___pwa_rewrite_rules");

<?php
/* ------------------------------------------------------------------------ *\
 * Functions: Rewrites
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top");
}
add_action("init", "__gulp_init_namespace___rewrite_rules");

Update function name to be more accurate


<?php

return array(

    //-------------------------------
    // Timezone for insert dates in database
    // If you want IPay not set timezone, just leave it empty
    //--------------------------------
    'timezone' => 'Asia/Tehran',

    //--------------------------------
    // Database configuration
    //--------------------------------
    'database-poolticket' => array(
        'host'     => '127.0.0.1',
        'dbname'   => '',
        'username' => '',
        'password' => '',
        'create' => true             // For first time you must set this to true for create tables in database
    ),

    //--------------------------------
    // Zarinpal gateway
    //--------------------------------
    'zarinpal' => array(
        'merchant-id'  => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'type'         => 'zarin-gate',                           // Types: [zarin-gate || normal]
        'callback-url' => 'http://www.example.org/result',
        'server'       => 'germany',                              // Servers: [germany || iran]
        'email'        => 'email@gmail.com',
        'mobile'       => '09xxxxxxxxx',
        'description'  => 'description',
    ),

    //--------------------------------
    // Mellat gateway
    //--------------------------------
    'mellat' => array(
        'username'     => '',
        'password'     => '',
        'terminalId'   => 0000000,
        'callback-url' => 'http://www.example.org/result'
    )
);

<?php

return array(

    //-------------------------------
    // Timezone for insert dates in database
    // If you want IPay not set timezone, just leave it empty
    //--------------------------------
    'timezone' => 'Asia/Tehran',

    //--------------------------------
    // Database configuration
    //--------------------------------
    'database' => array(
        'host'     => '127.0.0.1',
        'dbname'   => '',
        'username' => '',
        'password' => '',
        'create' => true             // For first time you must set this to true for create tables in database
    ),

    //--------------------------------
    // Zarinpal gateway
    //--------------------------------
    'zarinpal' => array(
        'merchant-id'  => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'type'         => 'zarin-gate',                           // Types: [zarin-gate || normal]
        'callback-url' => 'http://www.example.org/result',
        'server'       => 'germany',                              // Servers: [germany || iran]
        'email'        => 'email@gmail.com',
        'mobile'       => '09xxxxxxxxx',
        'description'  => 'description',
    ),

    //--------------------------------
    // Mellat gateway
    //--------------------------------
    'mellat' => array(
        'username'     => '',
        'password'     => '',
        'terminalId'   => 0000000,
        'callback-url' => 'http://www.example.org/result'
    )
);

Fix bug in ipay config sample

Fix bug in ipay config sample


<?php defined('C5_EXECUTE') or die(_("Access Denied."));?>
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="hidden" value="" name="stripeToken" id="stripeToken" />
<script>
    $(document).ready(function() {
        var handler = StripeCheckout.configure({
            key: '<?= $publicAPIKey; ?>',
            locale: 'auto',
            token: function (token) {
                // Use the token to create the charge with a server-side script.
                // You can access the token ID with `token.id`
                $('#stripeToken').val(token.id);
                $('#store-checkout-form-group-payment').submit();
            }
        });

        $('.store-btn-complete-order').on('click', function (e) {
            // Open Checkout with further options
            var currentpmid = $('input[name="payment-method"]:checked:first').data('payment-method-id');

            if (currentpmid == <?= $pmID; ?>) {
                handler.open({
                    currency: "<?= strtolower($currency);?>",
                    amount: <?= $amount; ?>,
                    email: $('#store-email').val() ? $('#store-email').val() : '<?= ($email); ?>'
                });
                e.preventDefault();
            }
        });

        // Close Checkout on page navigation
        $(window).on('popstate', function () {
            handler.close();
        });
    });
</script>

<?php defined('C5_EXECUTE') or die(_("Access Denied."));?>
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="hidden" value="" name="stripeToken" id="stripeToken" />
<script>
    $(document).ready(function() {
        var handler = StripeCheckout.configure({
            key: '<?= $publicAPIKey; ?>',
            locale: 'auto',
            token: function (token) {
                // Use the token to create the charge with a server-side script.
                // You can access the token ID with `token.id`
                $('#stripeToken').val(token.id);
                $('#store-checkout-form-group-payment').submit();
            }
        });

        $('.store-btn-complete-order').on('click', function (e) {
            // Open Checkout with further options
            var currentpmid = $('input[name="payment-method"]:checked:first').data('payment-method-id');

            if (currentpmid == <?= $pmID; ?>) {
                handler.open({
                    currency: "<?= strtolower($currency);?>",
                    amount: $('.store-total-amount').data('total-cents') ?  $('.store-total-amount').data('total-cents') : '<?= ($amount); ?>',
                    email: $('#store-email').val() ? $('#store-email').val() : '<?= ($email); ?>'
                });
                e.preventDefault();
            }
        });

        // Close Checkout on page navigation
        $(window).on('popstate', function () {
            handler.close();
        });
    });
</script>

Use dynamically updated cents value if available (total may change as shipping methods are changed, etc)


<?php

namespace GeoIP2\Record;

abstract class AbstractPlaceRecord extends AbstractRecord
{
  private $languages;

  public function __construct($record, $languages){
    $this->languages = $languages;
    parent::__construct($record);
  }

  public function name() {
    foreach($this->languages as $language) {
      if (isset($this->names[$language])) return $this->names[$language];
    }
  }
}

<?php

namespace GeoIP2\Record;

abstract class AbstractPlaceRecord extends AbstractRecord
{
  private $languages;

  public function __construct($record, $languages){
    $this->languages = $languages;
    parent::__construct($record);
  }

  public function __get($attr) {
    if ($attr == 'name') {
      return $this->name();
    } else {
      return parent::__get($attr);
    }
  }

  private function name() {
    foreach($this->languages as $language) {
      if (isset($this->names[$language])) return $this->names[$language];
    }
  }
}

Make 'name' a property rather than a function


<?php

namespace Craft;

use Symfony\Component\Yaml\Yaml;

/**
 * Schematic Data Model.
 *
 * Encapsulates data that has been exported via schematic.
 *
 * @author    Itmundi
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://www.itmundi.nl
 */
class Schematic_DataModel extends BaseModel
{
    /**
     * Define attributes.
     *
     * @inheritdoc
     */
    protected function defineAttributes()
    {
        return array(
            'assets'            => AttributeType::Mixed,
            'fields'            => AttributeType::Mixed,
            'globals'           => AttributeType::Mixed,
            'plugins'           => AttributeType::Mixed,
            'sections'          => AttributeType::Mixed,
            'userGroups'        => AttributeType::Mixed,
            'pluginData'        => array(AttributeType::Mixed, 'default' => array()),
        );
    }

    /**
     * Populate data model from yaml.
     *
     * @param string $yaml
     *
     * @return Schematic_DataModel
     */
    public static function fromYaml($yaml)
    {
        $data = Yaml::parse($yaml);

        return $data === null ? null : new static($data);
    }

    /**
     * Populate yaml from data model.
     *
     * @param array $data
     *
     * @return Schematic_DataModel
     */
    public static function toYaml(array $data)
    {
        $data = $data === null ? null : new static($data);

        return Yaml::dump($data->attributes, 12);
    }
}

<?php

namespace Craft;

use Symfony\Component\Yaml\Yaml;

/**
 * Schematic Data Model.
 *
 * Encapsulates data that has been exported via schematic.
 *
 * @author    Itmundi
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://www.itmundi.nl
 */
class Schematic_DataModel extends BaseModel
{
    /**
     * Define attributes.
     *
     * @inheritdoc
     */
    protected function defineAttributes()
    {
        return array(
            'assets'            => AttributeType::Mixed,
            'fields'            => AttributeType::Mixed,
            'globals'           => AttributeType::Mixed,
            'plugins'           => AttributeType::Mixed,
            'sections'          => AttributeType::Mixed,
            'userGroups'        => AttributeType::Mixed,
            'pluginData'        => array(AttributeType::Mixed, 'default' => array()),
        );
    }

    /**
     * Populate data model from yaml.
     *
     * @param string $yaml
     *
     * @return Schematic_DataModel
     */
    public static function fromYaml($yaml)
    {
        $data = Yaml::parse($yaml);

        return $data === null ? null : new static($data);
    }

    /**
     * Populate yaml from data model.
     *
     * @param array $data
     *
     * @return Schematic_DataModel
     */
    public static function toYaml(array $data)
    {
        $data = $data === null ? null : new static($data);

        return Yaml::dump($data->attributes, 12, 2);
    }
}

Use 2 spaces indents in Yaml file

Use 2 spaces indents in Yaml file


<?php

use PHPUnit\Framework\TestCase;
use TwinDigital\WPTools\PluginTools;

class PluginToolsTest extends WP_UnitTestCase {

  /**
   * Instance of the class.
   *
   * @var \TwinDigital\WPTools\PluginTools $class
   */
  public $class;

  /**
   * Tests if the plugin_list is loaded.
   *
   * @covers PluginTools::loadPluginList()
   * @return void
   */
  public function testLoadPluginList() {
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }
  /**
   * Tests if the plugin_list is loaded.
   *
   * @covers PluginTools::loadPluginList()
   * @return void
   */
  public function testLoadPluginListForced() {
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }

  public function testRefreshLoadedPlugins() {
    PluginTools::$loadedPlugins = null;
    PluginTools::refreshLoadedPlugins();
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }

  protected function setUp() {
    $this->class = PluginTools::class;
  }

  public function tearDown() {
    parent::tearDown(); // TODO: Change the autogenerated stub
  }
}

<?php

use PHPUnit\Framework\TestCase;
use TwinDigital\WPTools\PluginTools;

class PluginToolsTest extends TestCase {

  /**
   * Instance of the class.
   *
   * @var \TwinDigital\WPTools\PluginTools $class
   */
  public $class;

  /**
   * Tests if the plugin_list is loaded.
   *
   * @covers PluginTools::loadPluginList()
   * @return void
   */
  public function testLoadPluginList() {
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }
  /**
   * Tests if the plugin_list is loaded.
   *
   * @covers PluginTools::loadPluginList()
   * @return void
   */
  public function testLoadPluginListForced() {
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }

  public function testRefreshLoadedPlugins() {
    PluginTools::$loadedPlugins = null;
    PluginTools::refreshLoadedPlugins();
    $this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
  }

  public function setUp() {
    $this->class = PluginTools::class;
  }

  public function tearDown() {
    parent::tearDown();
  }
}

Use TestCase instead of WP_UnitTestCase

Use TestCase instead of WP_UnitTestCase


<?php

declare(strict_types=1);

namespace Budgegeria\Bundle\IntlFormatBundle\DependencyInjection;

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

class BudgegeriaIntlFormatExtension extends Extension
{
    /**
     * @param mixed[]          $configs
     * @param ContainerBuilder $container
     *
     * @return void
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
        $loader->load('services.xml');

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('budgegeria_intl_format.locale', $config['locale']);
        $container->setParameter('budgegeria_intl_format.currency', $config['currency']);
    }
}

<?php

declare(strict_types=1);

namespace Budgegeria\Bundle\IntlFormatBundle\DependencyInjection;

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

class BudgegeriaIntlFormatExtension extends Extension
{
    /**
     * @param mixed[]          $configs
     * @param ContainerBuilder $container
     *
     * @return void
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
        $loader->load('services.xml');

        $configuration = new Configuration();
        /** @phpstan-var array{locale: string, currency: string} $config */
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('budgegeria_intl_format.locale', $config['locale']);
        $container->setParameter('budgegeria_intl_format.currency', $config['currency']);
    }
}

Set array type for PHPStan

Set array type for PHPStan