<?php

class BaseTest extends PHPUnit_Framework_TestCase {

    /**
     * @var \BulkSmsCenter\Auth
     */
    protected $auth;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockClient;

    public function setUp()
    {
        $this->auth = new \BulkSmsCenter\Auth('YOUR_USERNAME','YOUR_PASSWORD');
        $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
    }

    public function testConstructor()
    {
        $client = new \BulkSmsCenter\Client();
        $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
    }

    public function testHttpClientMock()
    {
        $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');
        $client = new \BulkSmsCenter\Client($this->auth,$this->mockClient);
    }

}

<?php

class BaseTest extends PHPUnit_Framework_TestCase {

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockAuth;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockClient;

    public function setUp()
    {
        $this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([
            'YOUR_USERNAME',
            'YOUR_PASSWORD',
        ])->getMock();
        $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
    }

    public function testConstructor()
    {
        $client = new \BulkSmsCenter\Client();
        $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
    }

    public function testHttpClientMock()
    {
        $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');
        $client = new \BulkSmsCenter\Client($this->auth,$this->mockClient);
    }

}

Use a mock for Auth object

Use a mock for Auth object


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console;

use Illuminate\Database\Console\Migrations\MigrateMakeCommand as BaseMigrateMakeCommand;

class MigrateMakeCommand extends BaseMigrateMakeCommand
{
    /**
     * The console command signature.
     *
     * @var string
     */
    protected $signature = 'make:migration {name : The name of the migration.}
        {--module= : The name of the module.}
        {--create= : The table to be created.}
        {--table= : The table to migrate.}
        {--path= : The location where the migration file should be created.}';

    /**
     * Get migration path (either specified by '--path' option or module location).
     *
     * @return string
     */
    protected function getMigrationPath()
    {
        if (! is_null($targetPath = $this->input->getOption('path'))) {
            return $this->laravel->basePath().'/'.$targetPath;
        }

        if (! is_null($module = $this->input->getOption('module')) && $this->laravel->files->exists($modulePath = $this->laravel->path().DIRECTORY_SEPARATOR.$module)) {
            return $modulePath.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'migrations';
        }

        return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Database\Console\Migrations\MigrateMakeCommand as BaseMigrateMakeCommand;

class MigrateMakeCommand extends BaseMigrateMakeCommand
{
    /**
     * The console command signature.
     *
     * @var string
     */
    protected $signature = 'make:migration {name : The name of the migration.}
        {--module= : The name of the module.}
        {--create= : The table to be created.}
        {--table= : The table to migrate.}
        {--path= : The location where the migration file should be created.}';

    /**
     * Get migration path (either specified by '--path' option or module location).
     *
     * @return string
     */
    protected function getMigrationPath()
    {
        if (! is_null($targetPath = $this->input->getOption('path'))) {
            return $this->laravel->basePath().'/'.$targetPath;
        }

        if (! is_null($module = $this->input->getOption('module')) && $this->laravel->files->exists($modulePath = $this->laravel->path().DIRECTORY_SEPARATOR.$module)) {
            return $modulePath.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'migrations';
        }

        return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
    }
}

Fix wrong console command namespace

Fix wrong console command namespace


<?php

/*
 * This file is part of Psy Shell
 *
 * (c) 2013 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Test\Formatter;

use Psy\Formatter\CodeFormatter;

class CodeFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testFormat()
    {
        $expected = <<<EOS
    private function ignoreThisMethod(\$arg)
    {
        echo "whot!";
    }
EOS;

        $this->assertEquals(
            preg_replace("/\n/", PHP_EOL, $expected),
            CodeFormatter::format(new \ReflectionMethod($this, 'ignoreThisMethod'))
        );
    }

    /**
     * @dataProvider filenames
     * @expectedException Psy\Exception\RuntimeException
     */
    public function testCodeFormatterThrowsException($filename)
    {
        $reflector = $this->getMockBuilder('ReflectionClass')
            ->disableOriginalConstructor()
            ->getMock();

        $reflector
            ->expects($this->once())
            ->method('getFileName')
            ->will($this->returnValue($filename));

        CodeFormatter::format($reflector);
    }

    public function filenames()
    {
        return array(array(null), array('not a file'));
    }

    private function ignoreThisMethod($arg)
    {
        echo "whot!";
    }
}

<?php

/*
 * This file is part of Psy Shell
 *
 * (c) 2013 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Test\Formatter;

use Psy\Formatter\CodeFormatter;

class CodeFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testFormat()
    {
        $expected = <<<EOS
    private function ignoreThisMethod(\$arg)
    {
        echo "whot!";
    }
EOS;

        $this->assertEquals(
            str_replace("\n", PHP_EOL, $expected),
            CodeFormatter::format(new \ReflectionMethod($this, 'ignoreThisMethod'))
        );
    }

    /**
     * @dataProvider filenames
     * @expectedException Psy\Exception\RuntimeException
     */
    public function testCodeFormatterThrowsException($filename)
    {
        $reflector = $this->getMockBuilder('ReflectionClass')
            ->disableOriginalConstructor()
            ->getMock();

        $reflector
            ->expects($this->once())
            ->method('getFileName')
            ->will($this->returnValue($filename));

        CodeFormatter::format($reflector);
    }

    public function filenames()
    {
        return array(array(null), array('not a file'));
    }

    private function ignoreThisMethod($arg)
    {
        echo "whot!";
    }
}

Use `str_replace` instead of `preg_replace`


<?php

class PlanningApplication extends Module {

    const MAX_DISTANCE = 1;  // In Km
    public $url = "https://data.bathhacked.org/resource/uyh5-eygi.json";

    function getData() {
        $aps = json_decode($this->fetch());
        $relevant = array();
        foreach($aps as $ap) {
            if(!property_exists($ap, 'locationtext')) {
                continue;
            }
            preg_match(Module::POSTCODE_REGEX, $ap->locationtext, $matches);

            // If we find the planning permission
            if(isset($matches[0])) {
                $apl = $this->getPostCodeLocation($matches[0]);

                // If we can convert it to a location
                if($apl) {
                    $distance = $this->distance($apl[1], $apl[0],
                        self::$postCodeLoc[1], self::$postCodeLoc[0], "K");

                    // Add only planning applications in our area
                    if($distance < self::MAX_DISTANCE) {
                        $relevant[] = array(
                            'casedate'     => $ap->casedate,
                            'casetext'     => $ap->casetext,
                            'locationtext' => $ap->locationtext,
                            'banesstatus'  => $ap->banesstatus
                        );
                    }
                }

            }
        }
        return $relevant;
    }
}

?>

<?php

class PlanningApplication extends Module {

    const MAX_DISTANCE = 1;  // In Km
    public $url = "https://data.bathhacked.org/resource/uyh5-eygi.json";

    function getData() {
        $aps = json_decode($this->fetch());
        $relevant = array();
        foreach($aps as $ap) {
            if(!property_exists($ap, 'locationtext')) {
                continue;
            }
            preg_match(Module::POSTCODE_REGEX, $ap->locationtext, $matches);

            // If we find the planning permission
            if(isset($matches[0])) {
                $apl = $this->getPostCodeLocation($matches[0]);

                // If we can convert it to a location
                if($apl) {
                    $distance = $this->distance($apl[1], $apl[0],
                        self::$postCodeLoc[1], self::$postCodeLoc[0], "K");

                    // Add only planning applications in our area
                    if($distance < self::MAX_DISTANCE) {
                        $relevant[] = array(
                            'casedate'      => $ap->casedate,
                            'casetext'      => $ap->casetext,
                            'locationtext'  => $ap->locationtext,
                            'banesstatus'   => $ap->banesstatus,
                            'casereference' => $ap->casereference
                        );
                    }
                }

            }
        }
        return $relevant;
    }
}

?>

Add case reference for planning permissions


<?php

if (! function_exists('get_license_list')) {

    /**
     * Returns a list of SPDX license identifiers
     *
     * @see http://spdx.org/licenses/
     *
     * @return array
     */
    function get_license_list(){
        // TODO: Download list automatically from https://spdx.org/licenses/
        // TODO: Can be done via DOMDocument, @see https://github.com/composer/spdx-licenses/blob/master/src/SpdxLicensesUpdater.php
        // TODO: Cache license list
        return [
            'Apache-2.0',
            'BSD-2-Clause',
            'BSD-3-Clause',
            'BSD-4-Clause',
            'GPL-2.0',
            'GPL-2.0+',
            'GPL-3.0',
            'GPL-3.0+',
            'LGPL-2.1',
            'LGPL-2.1+',
            'LGPL-3.0',
            'LGPL-3.0+',
            'MIT',
            'proprietary'
        ];
    }
}

if (! function_exists('git_user_name')) {

    /**
     * Returns the git global config user.name
     *
     * @return string
     */
    function git_user_name(){
        return exec('git config --global user.name');
    }
}

if (! function_exists('git_user_email')) {

    /**
     * Returns the git global config user.email
     *
     * @return string
     */
    function git_user_email(){
        return exec('git config --global user.email');
    }
}

Add util for obtaining git user and email

Assuming that git is installed, which would be strange if not... !


<?php

namespace App\Http\Controllers\Auth;

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

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

    use ResetsPasswords;

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

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

<?php

namespace App\Http\Controllers\Auth;

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

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

    use ResetsPasswords;

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

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

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

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

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

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


<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load($pathAndFilename, $allowSplitSource = false)
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load($pathAndFilename, $allowSplitSource = false): array
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

Fix test error with YamlSource

Fix test error with YamlSource


<?php

if ( ! isset( $content_width ) ) {
	$content_width = 600;
}

function enqueue_comment_reply() {
    if ( get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'comment_form_before', 'enqueue_comment_reply' );

function baw_hack_wp_title_for_home( $title ){
	if( empty( $title ) && ( is_home() || is_front_page() ) ):
		return get_bloginfo( 'name' ) . ' | ' . get_bloginfo( 'description' );
	else:
		return get_bloginfo( 'name' ) . ' | ' . $title;
	endif;
	return $title;
}
add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );

add_theme_support( 'automatic-feed-links' );

add_action('after_setup_theme', 'my_theme_setup');

function my_theme_setup(){
    load_theme_textdomain('material-for-coders', get_template_directory() . '/languages');
	add_theme_support( 'infinite-scroll', array(
		'type'           => 'scroll',
		'container'      => 'articles',
		'posts_per_page' => 2
	) );
}
?>

<?php

if ( ! isset( $content_width ) ) {
	$content_width = 600;
}

function enqueue_comment_reply() {
    if ( get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'comment_form_before', 'enqueue_comment_reply' );

function baw_hack_wp_title_for_home( $title ){
	if( empty( $title ) && ( is_home() || is_front_page() ) ):
		return get_bloginfo( 'name' ) . ' | ' . get_bloginfo( 'description' );
	else:
		return get_bloginfo( 'name' ) . ' | ' . $title;
	endif;
	return $title;
}
add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );

add_theme_support( 'automatic-feed-links' );

add_action('after_setup_theme', 'my_theme_setup');

function my_theme_setup(){
    load_theme_textdomain('material-for-coders', get_template_directory() . '/languages');
}
?>

Revert "Test with infinite scroll"

Revert "Test with infinite scroll"

This reverts commit f74a07788b16063fbbd22facbe6f86c95afb111d.


<?php

/**
 * Generates minimal site-wide page chrome.
 * @see https://drupal.org/node/1728148
 **/

?>

<?php if (!empty($tabs['#primary'])): ?><?php print render($tabs); ?><?php endif; ?>
<?php print $messages; ?>

  <?php print $variables['navigation']; ?>
  <?php print $variables['header']; ?>

    <?php print render($page['content']); ?>

  <?php print $variables['footer']; ?>

<?php

/**
 * Generates minimal site-wide page chrome.
 * @see https://drupal.org/node/1728148
 **/

?>

<?php if (!empty($tabs['#primary'])): ?><?php print render($tabs); ?><?php endif; ?>
<?php print $messages; ?>

  <?php print $variables['navigation']; ?>
  <?php if(isset($variables['header'])) print $variables['header']; ?>

    <?php print render($page['content']); ?>

  <?php print $variables['footer']; ?>

Fix 'index "header" not defined' warning.


<?php

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

class RenameSustainingFellowsColumnsToLuminary extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('sustaining_fellow_copy', 'luminary_copy');
            $table->renameColumn('send_sustaining_fellow_test', 'send_luminary_test');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('luminary_copy', 'sustaining_fellow_copy');
            $table->renameColumn('send_luminary_test', 'send_sustaining_fellow_test');
        });
    }
}

<?php

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

class RenameSustainingFellowsColumnsToLuminary extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('sustaining_fellow_copy', 'luminary_copy');
        });

        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('send_sustaining_fellow_test', 'send_luminary_test');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('luminary_copy', 'sustaining_fellow_copy');
        });

        Schema::table('event_email_series', function (Blueprint $table) {
            $table->renameColumn('send_luminary_test', 'send_sustaining_fellow_test');
        });
    }
}

Fix "Luminary" migration for SQLite

Fix "Luminary" migration for SQLite [WEB-1834]


    @foreach($manyForms as $key => $column)

first) pl-2 @endif @if(!$loop->last) pr-2 @endif">
                @foreach($column as $item)
                    {!! $item ?? '' !!}
                @endforeach

    @endforeach

    @foreach($manyForms as $key => $column)

first) pl-md-2 @endif @if(!$loop->last) pr-md-2 @endif">
                @foreach($column as $item)
                    {!! $item ?? '' !!}
                @endforeach

    @endforeach

Disable padding columns for mobile

Disable padding columns for mobile


<?php
class Projects extends CI_Controller {

    public function __construct() {
        parent::__construct ();
        $this->load->helper ( 'file' );
    }

	public function index() {
        $filepath = APPPATH . 'logs/repocache.json';
        $cachefile = read_file($filepath);
        $decoded = json_decode($cachefile);

        $data = array();
        $data['githubFeed'] = $decoded;

		$this->load->view ( "projects" , $data );
	}
}

<?php
class Projects extends CI_Controller {

    public function __construct() {
        parent::__construct ();
        $this->load->helper ( 'file' );
    }

	public function index() {
        $filepath = APPPATH . 'logs/repocache.json';
        $cachefile = read_file($filepath);
        $decoded = json_decode($cachefile);

        usort($decoded, function($a, $b)
        {
            return ($a->pushed_at < $b->pushed_at);
        });

        $data = array();
        $data['githubFeed'] = $decoded;

		$this->load->view ( "projects" , $data );
	}
}

Order the github feed so that the most recently worked on project appears at the top


<?php

namespace Orchestra\Config\Console;

use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;

class ConfigCacheCommand extends BaseCommand
{
    /**
     * Boot a fresh copy of the application configuration.
     *
     * @return array
     */
    protected function getFreshConfiguration()
    {
        $app = require $this->laravel->basePath().'/bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();
        $config = $app->make('config');

        $files = \array_merge(
            $config->get('compile.config', []), $this->getConfigurationFiles()
        );

        foreach ($files as $file) {
            $config[$file];
        }

        return $config->all();
    }

    /**
     * Get all of the configuration files for the application.
     *
     * @return array
     */
    protected function getConfigurationFiles()
    {
        $files = [];
        $path = $this->laravel->configPath();
        $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);

        foreach ($found as $file) {
            $files[] = \basename($file->getRealPath(), '.php');
        }

        return $files;
    }
}

<?php

namespace Orchestra\Config\Console;

use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;

class ConfigCacheCommand extends BaseCommand
{
    /**
     * Boot a fresh copy of the application configuration.
     *
     * @return array
     */
    protected function getFreshConfiguration()
    {
        $app = require $this->laravel->bootstrapPath('app.php');

        $app->make(Kernel::class)->bootstrap();
        $config = $app->make('config');

        $files = \array_merge(
            $this->configToCache(), $this->getConfigurationFiles()
        );

        foreach ($files as $file) {
            $config[$file];
        }

        return $config->all();
    }

    /**
     * Get all of the configuration files for the application.
     *
     * @return array
     */
    protected function getConfigurationFiles()
    {
        $files = [];
        $path = $this->laravel->configPath();
        $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);

        foreach ($found as $file) {
            $files[] = \basename($file->getRealPath(), '.php');
        }

        return $files;
    }

    /**
     * Get all of the package names that should be ignored.
     *
     * @return array
     */
    protected function configToCache()
    {
        if (! file_exists($this->laravel->basePath('composer.json')) {
            return [];
        }
        return json_decode(file_get_contents(
            $this->laravel->basePath('composer.json')
        ), true)['extra']['config-cache'] ?? [];
    }
}

Use config to cache from composer.json

Use config to cache from composer.json

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace OAuthBundle\EventListener;

use ApiPlatform\Core\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;

final class DeserializeListener
{
    private $decorated;
    private $denormalizer;
    private $serializerContextBuilder;

    public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
    {
        $this->denormalizer = $denormalizer;
        $this->serializerContextBuilder = $serializerContextBuilder;
        $this->decorated = $decorated;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
            return;
        }

        if ('POST' === $request->getMethod() && $request->get("_route") === "_token") {
            $this->denormalizeFormRequest($request);
        } else {
            $this->decorated->onKernelRequest($event);
        }
    }

    private function denormalizeFormRequest(Request $request)
    {
        try {
            $body = json_decode($request->getContent());

            foreach ($body as $key => $value) {
                $request->request->set($key, $value);
            }

        } catch (RuntimeException $e) {
            return;
        }

    }
}

<?php

namespace OAuthBundle\EventListener;

use ApiPlatform\Core\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;

final class DeserializeListener
{
    private $decorated;
    private $denormalizer;
    private $serializerContextBuilder;

    public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
    {
        $this->denormalizer = $denormalizer;
        $this->serializerContextBuilder = $serializerContextBuilder;
        $this->decorated = $decorated;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
            return;
        }

        if ('POST' === $request->getMethod() && $request->get("_route") === "_token") {
            $this->denormalizeFormRequest($request);
        } else {
            $this->decorated->onKernelRequest($event);
        }
    }

    private function denormalizeFormRequest(Request $request)
    {
        try {
            $body = $request->getContent();

            if(is_string($body)){
                $body = json_decode($body);
            }

            foreach ($body as $key => $value) {
                $request->request->set($key, $value);
            }

        } catch (RuntimeException $e) {
            return;
        }

    }
}

Improve logical on deserialize listener

:wrench: Improve logical on deserialize listener


<?php
/**
 * SpotifyTest.php
 *
 * @package Embera
 * @author Michael Pratt <yo@michael-pratt.com>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Provider;

use Embera\ProviderTester;

/**
 * Test the Spotify Provider
 */
final class SpotifyTest extends ProviderTester
{
    protected $tasks = [
        'valid_urls' => [
            'https://open.spotify.com/album/4FCuyUjOkT28PnFo6A6vkf/4K4sc36DCTp9YJNVu5zV09',
            'https://open.spotify.com/track/0Wm3w3YiMe7YiS8erpKbOl',
        ],
        'invalid_urls' => [
            'https://open.spotify.com/stuff/3zIzQMHvOlw3ukDhRKR2jO',
        ],
    ];

    public function testProvider()
    {
        $this->validateProvider('Spotify', [ 'width' => 480, 'height' => 270]);
    }
}

<?php
/**
 * SpotifyTest.php
 *
 * @package Embera
 * @author Michael Pratt <yo@michael-pratt.com>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Provider;

use Embera\ProviderTester;

/**
 * Test the Spotify Provider
 */
final class SpotifyTest extends ProviderTester
{
    protected $tasks = [
        'valid_urls' => [
            'https://open.spotify.com/album/4FCuyUjOkT28PnFo6A6vkf/4K4sc36DCTp9YJNVu5zV09',
            'https://open.spotify.com/track/0Wm3w3YiMe7YiS8erpKbOl',
            'https://open.spotify.com/show/3wBfqov60qDZbEVjPHo0a8?si=2ee16a763fd44148',
        ],
        'invalid_urls' => [
            'https://open.spotify.com/stuff/3zIzQMHvOlw3ukDhRKR2jO',
        ],
    ];

    public function testProvider()
    {
        $this->validateProvider('Spotify', [ 'width' => 480, 'height' => 270]);
    }
}

Add test for Spotify show type (podcast)


<?php

$date          =& $_GET["date"];
$user          =& $_GET["user"];
$priority      =& $_GET["priority"];
$text          =& $_GET["text"];

require_once 'icat.php';
$db = init_db();

$_SESSION['entry_username'] = $user;

$result = mysqli_query($db,
    "insert into entries (contest_time, user, priority, text) values " .
    sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
    mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);

if ($result) {
    print("okay");
} else {
    print("error: " . mysqli_error($db));
}

?>

<?php

$date          =& $_REQUEST["date"];
$user          =& $_REQUEST["user"];
$priority      =& $_REQUEST["priority"];
$text          =& $_REQUEST["text"];

require_once 'icat.php';
$db = init_db();

$_SESSION['entry_username'] = $user;

$result = mysqli_query($db,
    "insert into entries (contest_time, user, priority, text) values " .
    sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
    mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);

if ($result) {
    print("okay");
} else {
    print("error: " . mysqli_error($db));
}

?>

Use PHP $_REQUEST variable to also allow POST-ing.


<?php

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

namespace Sylius\Bundle\WebBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;

/**
 * Profile form.
 *
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class ProfileFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', 'text', array(
                'label'    => 'sylius.form.profile.firstName'
            ))
            ->add('lastName', 'text', array(
                'label'    => 'sylius.form.profile.lastName'
            ))
            ->add('username', null, array(
                'label'    => 'sylius.form.profile.username'
            ))
            ->add('email', 'email', array(
                'label'    => 'sylius.form.profile.email'
            ))
        ;
    }

    public function getName()
    {
        return 'sylius_user_profile';
    }
}

<?php

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

namespace Sylius\Bundle\WebBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;

/**
 * Profile form.
 *
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class ProfileFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', 'text', array(
                'label'    => 'sylius.form.profile.firstName'
            ))
            ->add('lastName', 'text', array(
                'label'    => 'sylius.form.profile.lastName'
            ))
            ->add('email', 'email', array(
                'label'    => 'sylius.form.profile.email'
            ))
        ;
    }

    public function getName()
    {
        return 'sylius_user_profile';
    }
}

Delete username from profile form

Delete username from profile form


<?php

namespace Shrikeh\Collection;

use Countable;
use SplFixedArray;

trait FixedArrayStorageTrait
{
    public function __construct(Traversable $objects)
    {
        $arr = [];
        foreach ($objects as $object) {
            $arr[] = $object;
        }
        parent::__construct(new SplFixedArray(count($arr)));

        foreach ($arr as $index => $obj) {
            $this->append($obj, $index);
        }
        $this->getStorage()->rewind();
    }

    abstract protected function getStorage();
}

<?php

namespace Shrikeh\Collection;

use Traversable;
use SplFixedArray;

trait FixedArrayStorageTrait
{
    public function __construct(Traversable $objects)
    {
        $arr = [];
        foreach ($objects as $object) {
            $arr[] = $object;
        }
        parent::__construct(new SplFixedArray(count($arr)));

        foreach ($arr as $index => $obj) {
            $this->append($obj, $index);
        }
        $this->getStorage()->rewind();
    }

    abstract protected function getStorage();
}

Change from Countable to Traversable

Change from Countable to Traversable


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Seeder;

class ItemCategoriesTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('item_categories')->delete();

        $categories = [
            ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'],
            ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'],
            ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'],
        ];

        DB::table('item_categories')->insert($categories);
    }
}

<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Seeder;

class ItemCategoriesTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('item_categories')->delete();

        $categories = [
            ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'],
            ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'],
            ['name' => 'Participações sociais', 'slug' => 'part-sociais', 'code' => '05'],
            ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'],
        ];

        DB::table('item_categories')->insert($categories);
    }
}

Add a new category: "participações sociais"


<?php

namespace Aztech\Layers\Responses;

use Symfony\Component\HttpFoundation\Response;

class JsonResponse
{
    private $response;

    public function __construct(array $content, $code)
    {
        $this->response = new Response(json_encode($content), intval($code), [
            'Content-Type' => 'application/json'
        ]);
    }

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

<?php

namespace Aztech\Layers\Responses;

use Symfony\Component\HttpFoundation\Response;

class JsonResponse
{
    private $response;

    public function __construct($content, $code)
    {
        if (! is_string($content)) {
            json_encode($content);
        }

        $this->response = new Response($content, intval($code), [
            'Content-Type' => 'application/json'
        ]);
    }

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

Allow non array content in JSON response


<?php

namespace Bolt\Extension\royallthefourth\CodeHighlightBolt;

use Bolt\Asset\File\JavaScript;
use Bolt\Asset\Snippet\Snippet;
use Bolt\Asset\File\Stylesheet;
use Bolt\Asset\Target;
use Bolt\Extension\SimpleExtension;

/**
 * CodeHighlightBolt extension class.
 *
 * @author Royall Spence <royall@royall.us>
 */
class CodeHighlightBoltExtension extends SimpleExtension
{
    public function getName()
    {
        return "Code Highlight";
    }

    /**
     * {@inheritdoc}
     */
    protected function registerAssets()
    {
        $config = $this->getConfig();
        $theme = $config['theme'];

        $jsInit = new Snippet();
        $jsInit->setCallback([$this, 'jsInitSnippet'])
            ->setLocation(Target::AFTER_JS)
            ->setPriority(99)
        ;

        return [
            new JavaScript('assets/highlightjs/highlight.pack.min.js'),
            new Stylesheet("assets/highlightjs/styles/{$theme}.css"),
            $jsInit,
        ];
    }

    public function jsInitSnippet()
    {
        return '<script>hljs.initHighlightingOnLoad();</script>';
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultConfig()
    {
        return [
            'theme' => 'monokai'
        ];
    }
}

<?php

namespace Bolt\Extension\royallthefourth\CodeHighlightBolt;

use Bolt\Asset\File\JavaScript;
use Bolt\Asset\Snippet\Snippet;
use Bolt\Asset\File\Stylesheet;
use Bolt\Asset\Target;
use Bolt\Extension\SimpleExtension;

/**
 * CodeHighlightBolt extension class.
 *
 * @author Royall Spence <royall@royall.us>
 */
class CodeHighlightBoltExtension extends SimpleExtension
{
    public function getDisplayName()
    {
        return "Code Highlight";
    }

    /**
     * {@inheritdoc}
     */
    protected function registerAssets()
    {
        $config = $this->getConfig();
        $theme = $config['theme'];

        $jsInit = new Snippet();
        $jsInit->setCallback([$this, 'jsInitSnippet'])
            ->setLocation(Target::AFTER_JS)
            ->setPriority(99)
        ;

        return [
            new JavaScript('assets/highlightjs/highlight.pack.min.js'),
            new Stylesheet("assets/highlightjs/styles/{$theme}.css"),
            $jsInit,
        ];
    }

    public function jsInitSnippet()
    {
        return '<script>hljs.initHighlightingOnLoad();</script>';
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultConfig()
    {
        return [
            'theme' => 'monokai'
        ];
    }
}

Change getName() => getDisplayName() for Bolt ^3.6 compatibility.

Since Bolt 3.6.0-beta, getName() has not been overrideable.


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

use PHPUnit\Framework\TestCase;
use Symfony\Component\RateLimiter\Policy\Rate;

class RateTest extends TestCase
{
    /**
     * @dataProvider provideRate
     */
    public function testFromString(Rate $rate)
    {
        $this->assertEquals($rate, Rate::fromString((string) $rate));
    }

    public function provideRate(): iterable
    {
        yield [new Rate(\DateInterval::createFromDateString('15 seconds'), 10)];
        yield [Rate::perSecond(10)];
        yield [Rate::perMinute(10)];
        yield [Rate::perHour(10)];
        yield [Rate::perDay(10)];
        yield [Rate::perMonth(10)];
        yield [Rate::perYear(10)];
    }
}

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

use PHPUnit\Framework\TestCase;
use Symfony\Component\RateLimiter\Policy\Rate;

class RateTest extends TestCase
{
    /**
     * @dataProvider provideRate
     */
    public function testFromString(Rate $rate)
    {
        $this->assertEquals($rate, Rate::fromString((string) $rate));
    }

    public function provideRate(): iterable
    {
        yield [new Rate(new \DateInterval('PT15S'), 10)];
        yield [Rate::perSecond(10)];
        yield [Rate::perMinute(10)];
        yield [Rate::perHour(10)];
        yield [Rate::perDay(10)];
        yield [Rate::perMonth(10)];
        yield [Rate::perYear(10)];
    }
}

Fix CI on PHP 8.2

[RateLimiter] Fix CI on PHP 8.2


{{--
    $images => array // [['link', 'title', 'relative_url']]
    $class => string // 'image-button-list'
--}}
@if(!empty($class))
@endif

@foreach($images as $image)

        @if(!empty($image['link']))@endif
            @if(!empty($image['relative_url']))
                {{--  --}}

                {{-- @image($image['relative_url'], $image['title']) --}}

                @if($loop->first == true)

                @else
                    @image($image['relative_url'], $image['title'])
                    {{--  --}}
                @endif
            @else
                {{ $image['title'] }}
            @endif
        @if(!empty($image['link']))@endif

@endforeach

@if(!empty($class))
@endif

{{--
    $images => array // [['link', 'title', 'relative_url']]
    $class => string // 'image-button-list'
--}}
@if(!empty($class))
@endif

@foreach($images as $image)

        @if(!empty($image['link']))@endif
            @if(!empty($image['relative_url']))
                @if($loop->first == true)

                @else
                    @image($image['relative_url'], $image['title'])
                @endif
            @else
                {{ $image['title'] }}
            @endif
        @if(!empty($image['link']))@endif

@endforeach

@if(!empty($class))
@endif

Remove the other examples now that we've got the height correct


<?php

namespace GoldenPlanet\WebpackBundle\Service;

class AssetNameGenerator {

	/**
	 * Appending a hash of the asset's full path to the file name
	 * for entry points with same file names (e.g. multiple main.js)
	 *
	 * Thus there's no need to specify a specific
	 * file name for the output (like in Assetic)
	 *
	 * @param string $asset
	 *
	 * @return string
	 */
	public function generateName($asset) {
		return sprintf('%s-%s', pathinfo($asset, PATHINFO_FILENAME), sha1($asset));
	}
}

<?php

namespace GoldenPlanet\WebpackBundle\Service;

class AssetNameGenerator {

	/**
	 * Appending a hash of the asset's full path to the file name
	 * for entry points with same file names (e.g. multiple main.js)
	 *
	 * Thus there's no need to specify a specific
	 * file name for the output (like in Assetic)
	 *
	 * @param string $asset
	 *
	 * @return string
	 */
	public function generateName($asset) {
		return sprintf('%s.%s', pathinfo($asset, PATHINFO_FILENAME), hash('crc32b', $asset));
	}
}

Make hash of the file path smaller

Make hash of the file path smaller


<?php
/**
 * RoboKassa driver for Omnipay PHP payment library.
 *
 * @link      https://github.com/hiqdev/omnipay-robokassa
 * @package   omnipay-robokassa
 * @license   MIT
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

namespace Omnipay\RoboKassa\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

/**
 * RoboKassa Purchase Response.
 */
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
    protected $_redirect = 'https://merchant.roboxchange.com/Index.aspx';

    public function isSuccessful()
    {
        return false;
    }

    public function isRedirect()
    {
        return true;
    }

    public function getRedirectUrl()
    {
        return $this->_redirect;
    }

    public function getRedirectMethod()
    {
        return 'POST';
    }

    public function getRedirectData()
    {
        return $this->data;
    }
}

<?php
/**
 * RoboKassa driver for Omnipay PHP payment library.
 *
 * @link      https://github.com/hiqdev/omnipay-robokassa
 * @package   omnipay-robokassa
 * @license   MIT
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

namespace Omnipay\RoboKassa\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

/**
 * RoboKassa Purchase Response.
 */
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
    protected $_redirect = 'https://auth.robokassa.ru/Merchant/Index.aspx';

    public function isSuccessful()
    {
        return false;
    }

    public function isRedirect()
    {
        return true;
    }

    public function getRedirectUrl()
    {
        return $this->_redirect;
    }

    public function getRedirectMethod()
    {
        return 'POST';
    }

    public function getRedirectData()
    {
        return $this->data;
    }
}

Switch to a new integration URL

Switch to a new integration URL

Closes #8


<?php
/**
 * @author	Marcel Werk
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @category	Community Framework
 */
// ignore direct access
if (!defined('PACKAGE_ID')) {
	@header("HTTP/1.0 404 Not Found");
	exit;
}

// define the wcf-root-dir
define('WCF_DIR', dirname(__FILE__).'/');

// APC below 3.1.4 breaks PHP's late static binding
if (extension_loaded('apc') && strnatcmp(phpversion('apc'), '3.1.4') < 0) {
	apc_clear_cache('opcode');
}

// initiate wcf core
require_once(WCF_DIR.'lib/system/WCF.class.php');
new wcf\system\WCF();

<?php
/**
 * @author	Marcel Werk
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @category	Community Framework
 */
// ignore direct access
if (!defined('PACKAGE_ID')) {
	@header("HTTP/1.0 404 Not Found");
	exit;
}

// define the wcf-root-dir
define('WCF_DIR', dirname(__FILE__).'/');

// initiate wcf core
require_once(WCF_DIR.'lib/system/WCF.class.php');
new wcf\system\WCF();

Remove check for outdated APC version

Remove check for outdated APC version

APC 3.1.4 won’t even run on PHP 5.4, so it’s safe to remove
the check here.


<?php

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

class GendersSeeder extends Seeder
{
    public function run()
    {
        \DB::table('genders_lookup')->insert(
          array(
              array('gender' => "Άντρας"),
              array('gender' => "Γυναίκα")
          )
        );
    }
}

<?php

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

class GendersSeeder extends Seeder
{
    public function run()
    {
        \DB::table('genders_lookup')->insert(
          array(
              array('gender' => "Άντρας"),
              array('gender' => "Γυναίκα"),
              array('gender' => "Άλλο")
          )
        );
    }
}

Add 'other' as gender option

Add 'other' as gender option


<?php namespace CL\Atlas\Test;

use Openbuildings\EnvironmentBackup as EB;
use CL\Atlas\DB;

/**
 * @package Jam
 * @author Ivan Kerin
 */
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase {

	public $env;

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

		$this->env = new EB\Environment(array(
			'static' => new EB\Environment_Group_Static,
		));

		DB::configuration('default', array(
			'class' => 'DB_Test',
			'dsn' => 'mysql:dbname=test-db;host=127.0.0.1',
			'username' => 'root',
		));

		$this->env->backup_and_set(array(
			'CL\Atlas\DB::$instances' => array(),
		));
	}

	public function tearDown()
	{
		$this->env->restore();

		parent::tearDown();
	}
}

<?php namespace CL\Atlas\Test;

use Openbuildings\EnvironmentBackup as EB;
use CL\Atlas\DB;

/**
 * @package Atlas
 * @author Ivan Kerin
 */
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase {

	public $env;

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

		$this->env = new EB\Environment(array(
			'static' => new EB\Environment_Group_Static,
		));

		DB::configuration('default', array(
			'class' => 'DB_Test',
			'dsn' => 'mysql:dbname=test-db;host=127.0.0.1',
			'username' => 'root',
		));

		$this->env->backup_and_set(array(
			'CL\Atlas\DB::$instances' => array(),
		));
	}

	public function tearDown()
	{
		$this->env->restore();

		parent::tearDown();
	}
}

Fix @package annotation from Jam to Atlas


<?php
namespace wapmorgan\PhpCodeFixer;

function password_hash_salt_option(array $usage_tokens) {
    $tree = PhpCodeFixer::makeFunctionCallTree($usage_tokens);
    $data = PhpCodeFixer::delimByComma($tree[1]);
    $data = PhpCodeFixer::trimSpaces($data);

    // getting delimiter
    foreach ($data as $array_element) {
        if ($array_element[0][0] == T_CONSTANT_ENCAPSED_STRING) {
            $element_key = trim($array_element[0][1], '\'"');
            if ($element_key == 'salt')
                return true;
        }
    }

    return false;
}

<?php
namespace wapmorgan\PhpCodeFixer;

function password_hash_salt_option(array $usage_tokens) {
    $tree = PhpCodeFixer::makeFunctionCallTree($usage_tokens);
    // if no extra options passed
    if (!isset($tree[1]))
        return false;
    $data = PhpCodeFixer::delimByComma($tree[1]);
    $data = PhpCodeFixer::trimSpaces($data);

    // searching for 'salt' option
    foreach ($data as $array_element) {
        if ($array_element[0][0] == T_CONSTANT_ENCAPSED_STRING) {
            $element_key = trim($array_element[0][1], '\'"');
            if ($element_key == 'salt')
                return true;
        }
    }

    return false;
}

Fix for checking password_hash() function


<?php
/**
 * By Pierre-Henry SORIA <http://ph7.me>
 */

namespace PFBC\Element;

use PH7\Framework\Security\Spam\Captcha\Captcha;

class CCaptcha extends Textbox
{
    public function render()
    {
        $this->attributes['required'] = 'required'; // Captcha field is always required!

        $this->validation[] = new \PFBC\Validation\CCaptcha;
        echo (new Captcha)->display();
        parent::render();
    }
}

<?php
/**
 * By Pierre-Henry SORIA <http://ph7.me>
 */

namespace PFBC\Element;

use PH7\Framework\Security\Spam\Captcha\Captcha;

class CCaptcha extends Textbox
{
    public function render()
    {
        $this->attributes['required'] = 'required'; // Captcha field is always required!
        $this->attributes['autocomplete'] = 'off';

        $this->validation[] = new \PFBC\Validation\CCaptcha;
        echo (new Captcha)->display();
        parent::render();
    }
}

Disable autocomplete browser feature for Captcha value


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

use App\Console\Helpers\Indexer;

class ReindexSearch extends Command
{

    use Indexer;

    protected $signature = 'search:reindex
                            {source : The name of the index to copy documents from}
                            {dest? : The name of the index to copy documents to}';

    protected $description = 'Copy documents from one index to another';

    public function handle()
    {

        $source = $this->argument('source');
        $dest = env('ELASTICSEARCH_INDEX', 'data_aggregator_test');

        if ($this->argument('dest'))
        {

            $dest = $this->argument('dest');

        }

        $params = [
            'wait_for_completion' => false,
            'body' => [
                'source' => [
                    'index' => $source,
                    'size' => 100,
                ],
                'dest' => [
                    'index' => $dest,
                ],
            ],
        ];

        $return = Elasticsearch::reindex($params);

        $this->info('Reindex has started. You can monitor the process here: ' .$this->baseUrl() .'/_tasks/' .$return['task']);

    }

}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

use App\Console\Helpers\Indexer;

class ReindexSearch extends Command
{

    use Indexer;

    protected $signature = 'search:reindex
                            {dest : The name of the index to copy documents to}
                            {source? : The prefix of the indexes to create the alias from}';

    protected $description = 'Copy documents from one set of indices to another';

    public function handle()
    {

        $source = env('ELASTICSEARCH_INDEX', 'test-latest-prefix');
        $dest = $this->argument('dest');

        if ($this->argument('source'))
        {

            $source = $this->argument('source');

        }

        foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model)
        {

            $endpoint = endpointFor($model);
            $index = $source .'-' .$endpoint;

            $params = [
                'wait_for_completion' => false,
                'body' => [
                    'source' => [
                        'index' => $index,
                        'size' => 100,
                    ],
                    'dest' => [
                        'index' => $dest .'-' .$endpoint,
                    ],
                ],
            ];

            $return = Elasticsearch::reindex($params);

            $this->info('Reindex from ' .$index .'has started. You can monitor the process here: ' .$this->baseUrl() .'/_tasks/' .$return['task']);

        }

    }

}

Update search:reindex to populate set of indices


<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class FullByDbxrefId extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('db')){
            return array();
        }
        $query_get_mapping = <<<EOF
SELECT fennec_id, identifier AS ncbi_taxid
    FROM fennec_dbxref
        WHERE db_id=(SELECT db_id FROM db WHERE name=?)
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute([$query->get('db')]);

        $result = array();
        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $ncbiID = $row['ncbi_taxid'];
            if(!array_key_exists($ncbiID, $result)){
                $result[$ncbiID] = $row['fennec_id'];
            } else {
                if(! is_array($result[$ncbiID]) ){
                    $result[$ncbiID] = [$result[$ncbiID]];
                }
                $result[$ncbiID][] = $row['fennec_id'];
            }
        }

        return $result;
    }
}

<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class FullByDbxrefId
{
    private $manager;

    /**
     * FullByDbxrefId constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute($dbname)
    {
        return $this->manager->getRepository('AppBundle:FennecDbxref')->getFullIds($dbname);
    }
}

Update service for getting full dbxref ids


<?php
namespace DrupalReleaseDate\Controllers;

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

class Charts
{

    public function samples(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/samples.twig',
            array(
                'scripts' => array(
                    '//code.jquery.com/jquery-2.0.2.min.js',
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }

    public function estimates(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/estimates.twig',
            array(
                'scripts' => array(
                    '//code.jquery.com/jquery-2.0.2.min.js',
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }

    public function distribution(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/distribution.twig',
            array(
                'scripts' => array(
                    '//code.jquery.com/jquery-2.0.2.min.js',
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }
}

<?php
namespace DrupalReleaseDate\Controllers;

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

class Charts
{

    public function samples(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/samples.twig',
            array(
                'scripts' => array(
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }

    public function estimates(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/estimates.twig',
            array(
                'scripts' => array(
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }

    public function distribution(Application $app, Request $request)
    {
        return $app['twig']->render(
            'charts/distribution.twig',
            array(
                'scripts' => array(
                    'https://www.google.com/jsapi',
                ),
            )
        );
    }
}

Fix double include of jQuery on chart pages


<? defined('C5_EXECUTE') or die('Access Denied.');

class Concrete5_Helper_Ajax {

	/** Sends a result to the client and ends the execution.
	* @param mixed $result
	*/
	public function sendResult($result) {
		@ob_end_clean();
		header('Content-Type: application/json; charset=' . APP_CHARSET, true);
		echo Loader::helper('json')->encode($result);
		die();
	}

	/** Sends an error to the client and ends the execution.
	* @param string|Exception $result The error to send to the client.
	*/
	public function sendError($error) {
		@ob_end_clean();
		header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);
		header('Content-Type: text/plain; charset=' . APP_CHARSET, true);
		echo ($error instanceof Exception) ? $error->getMessage() : $error;
		die();
	}

}

<? defined('C5_EXECUTE') or die('Access Denied.');

class Concrete5_Helper_Ajax {

	/** Sends a result to the client and ends the execution.
	* @param mixed $result
	*/
	public function sendResult($result) {
		if(@ob_get_length()) {
			@ob_end_clean();
		}
		header('Content-Type: application/json; charset=' . APP_CHARSET, true);
		echo Loader::helper('json')->encode($result);
		die();
	}

	/** Sends an error to the client and ends the execution.
	* @param string|Exception $result The error to send to the client.
	*/
	public function sendError($error) {
		if(@ob_get_length()) {
			@ob_end_clean();
		}
		header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);
		header('Content-Type: text/plain; charset=' . APP_CHARSET, true);
		echo ($error instanceof Exception) ? $error->getMessage() : $error;
		die();
	}

}

Clear output buffer only if it's not empty

Former-commit-id: 622fddc8c4d547ec1853d0b8cffe61d102215216


<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

$election_id = $_GET['id'];
$election_name = get_election_name($election_id);

?>

			<?php echo $election_name; ?>

 Elections

<?php echo $election_name; ?>

Dashboard

We are still working on this page. Please work on your questions and we will email you when this page is ready.

<?php

require_once('page_template_dash_foot.php');

?>

<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

$election_id = $_GET['id'];
$election_name = get_election_name($election_id);

?>

			<?php echo $election_name; ?>

 Elections

<?php echo $election_name; ?>

Dashboard

 Under Construction

					We are still working on this page. Please work on your questions and we will email you when this page is ready.

<?php

require_once('page_template_dash_foot.php');

?>

Make the under construction page less horrible


        {{ trans('manager.vacancies.table.th.date') }}
        @foreach ($business->services as $service)
        {{ $service->name }}
        @endforeach

    @foreach ($dates as $date => $vacancies)

        formatLocalized('%A %d %B') }}">{{ $date }}
        @foreach ($business->services as $service)
        @if(count($vacancies) > 0 && array_key_exists($service->slug, $vacancies))
         {!! Form::text("vacancy[$date][$service->id]", $vacancies[$service->slug]->capacity, array('class'=>'form-control', 'type' => 'numeric', 'step' => '1', 'placeholder'=> "$date {$service->name} ({$vacancies[$service->slug]->capacity})" )) !!}
        @else
         {!! Form::text("vacancy[$date][$service->id]", null, array('class'=>'form-control', 'placeholder'=> "$date {$service->name}" )) !!}
        @endif
        @endforeach

    @endforeach

@if (!$business->services->isEmpty())

        {!! Button::primary(trans('manager.businesses.btn.update'))->block()->large()->submit() !!}

@endif

        {{ trans('manager.vacancies.table.th.date') }}
        @foreach ($business->services as $service)
        {{ $service->name }}
        @endforeach

    @foreach ($dates as $date => $vacancies)

        {{ Carbon::parse($date)->formatLocalized('%A %d %B') }}
        @foreach ($business->services as $service)
        @if(count($vacancies) > 0 && array_key_exists($service->slug, $vacancies))
         {!! Form::text("vacancy[$date][$service->id]", $vacancies[$service->slug]->capacity, array('class'=>'form-control', 'type' => 'numeric', 'step' => '1', 'placeholder'=> "$date {$service->name} ({$vacancies[$service->slug]->capacity})" )) !!}
        @else
         {!! Form::text("vacancy[$date][$service->id]", null, array('class'=>'form-control', 'placeholder'=> "$date {$service->name}" )) !!}
        @endif
        @endforeach

    @endforeach

@if (!$business->services->isEmpty())

        {!! Button::primary(trans('manager.businesses.btn.update'))->block()->large()->submit() !!}

@endif

Switch date labels to make them human friendly


<?php declare(strict_types=1);

namespace Room11\Jeeves\BuiltIn\Commands;

use Amp\Promise;
use function Amp\resolve;
use Room11\Jeeves\Chat\Command as CommandMessage;
use Room11\Jeeves\System\BuiltInCommand;
use Room11\Jeeves\System\BuiltInCommandInfo;
use Room11\StackChat\Client\Client as ChatClient;

class Reboot implements BuiltInCommand
{
    private $chatClient;

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

    public function handleCommand(CommandMessage $command): Promise
    {
        return resolve(function() use ($command) {
            $message = yield $this->chatClient->postMessage($command, 'Restarting in 10 seconds.');

            \Amp\once(function() use ($message) {
                yield $this->chatClient->editMessage($message, 'Restarting now! o/');

                exit;
            }, 10000);
        });
    }

    public function getCommandInfo(): array
    {
        return [
            new BuiltInCommandInfo('reboot', 'Restarts the bot.'),
        ];
    }
}

<?php declare(strict_types=1);

namespace Room11\Jeeves\BuiltIn\Commands;

use Amp\Promise;
use function Amp\resolve;
use Room11\Jeeves\Chat\Command as CommandMessage;
use Room11\Jeeves\Storage\Admin as AdminStorage;
use Room11\Jeeves\System\BuiltInCommand;
use Room11\Jeeves\System\BuiltInCommandInfo;
use Room11\StackChat\Client\Client as ChatClient;

class Reboot implements BuiltInCommand
{
    private $chatClient;

    private $adminStorage;

    public function __construct(ChatClient $chatClient, AdminStorage $adminStorage)
    {
        $this->chatClient   = $chatClient;
        $this->adminStorage = $adminStorage;
    }

    public function handleCommand(CommandMessage $command): Promise
    {
        return resolve(function() use ($command) {
            if (!yield $this->adminStorage->isAdmin($command->getRoom(), $command->getUserId())) {
                return $this->chatClient->postReply($command, "I'm sorry Dave, I'm afraid I can't do that");
            }

            $message = yield $this->chatClient->postMessage($command, 'Restarting in 10 seconds.');

            \Amp\once(function() use ($message) {
                yield $this->chatClient->editMessage($message, 'Restarting now! o/');

                exit;
            }, 10000);
        });
    }

    public function getCommandInfo(): array
    {
        return [
            new BuiltInCommandInfo('reboot', 'Restarts the bot.'),
        ];
    }
}

Make reboot admin only. This means any admin sadly.


<?php

namespace Codeception\Module\Drupal\UserRegistry;

/**
 * Interface TestUserManagerInterface.
 *
 * @package Codeception\Module\DrupalUserRegistry
 */
interface TestUserManagerInterface
{
    /**
     * Create a test user.
     *
     * @param DrupalTestUser $user
     *   The user to create.
     */
    public function createUser($user);

    /**
     * Create multiple test users.
     *
     * @param array $users
     *   An array of DrupalTestUser objects to create.
     */
    public function createUsers($users);

    /**
     * Delete a test user.
     *
     * @param DrupalTestUser $user
     *   The user to delete.
     */
    public function deleteUser($user);

    /**
     * Delete multiple test users.
     *
     * @param array $users
     *   An array of DrupalTestUser objects to delete.
     */
    public function deleteUsers($users);

    /**
     * Determine if a user with a given username exists.
     *
     * @param string $username
     *   The username to check.
     *
     * @return bool
     *   True if the user exists, false otherwise.
     */
    public function userExists($username);
}

<?php

namespace Codeception\Module\Drupal\UserRegistry;

/**
 * Interface TestUserManagerInterface.
 *
 * @package Codeception\Module\DrupalUserRegistry
 */
interface TestUserManagerInterface
{
    /**
     * Create a test user.
     *
     * @param DrupalTestUser $user
     *   The user to create.
     *
     * @return void
     */
    public function createUser($user);

    /**
     * Create multiple test users.
     *
     * @param array $users
     *   An array of DrupalTestUser objects to create.
     *
     * @return void
     */
    public function createUsers($users);

    /**
     * Delete a test user.
     *
     * @param DrupalTestUser $user
     *   The user to delete.
     *
     * @return void
     */
    public function deleteUser($user);

    /**
     * Delete multiple test users.
     *
     * @param array $users
     *   An array of DrupalTestUser objects to delete.
     *
     * @return void
     */
    public function deleteUsers($users);

    /**
     * Determine if a user with a given username exists.
     *
     * @param string $username
     *   The username to check.
     *
     * @return bool
     *   True if the user exists, false otherwise.
     */
    public function userExists($username);
}

Add a '@return void' annotation, so that implementors know what to do in the overridden method.


<?php
define('APP_FOLDER_PATH', dirname(__FILE__) . '/../..');
include(APP_FOLDER_PATH . '/inc/init.php');

$json = file_get_contents(APP_FOLDER_PATH . '/gtfs-data/' . $_GET['file']);
JsonView::dump($json);

<?php
define('APP_FOLDER_PATH', dirname(__FILE__) . '/../..');
include(APP_FOLDER_PATH . '/inc/init.php');

if (isset($_GET['file'])) {
    $file = APP_FOLDER_PATH . '/geojson/' . $_GET['file'];
    if (file_exists($file)) {
        $json = file_get_contents($file);
    } else {
        error_log('GeoJSON error: ' . $file . ' not found !');
        $json = array(
            'error' => 'Cannot load ' . $_GET['file'] . ' !'
        );
    }
} else {
    $json = array(
        'error' => 'Missing file parameter, i.e. file=stations.geojson'
    );
}

JsonView::dump($json);

Check if the file exists - show some meaningful errors


<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

interface ThrowExpectation
{

}

<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

interface ThrowExpectation
{
    public function during($method, array $arguments = array());
}

Add during to the throw expectation interface


<?php

namespace Festitime\DatabaseBundle\Repository;

use Doctrine\ODM\MongoDB\DocumentRepository;

/**
 * ArtistRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ArtistRepository extends DocumentRepository
{
}

Add empty line at the end

Add empty line at the end


<?php

namespace spec\LdapTools\Connection;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ADLastErrorStrategySpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedThrough('getInstance', ['ad', true]);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Connection\ADLastErrorStrategy');
    }
}

<?php
/**
 * This file is part of the LdapTools package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace spec\LdapTools\Connection;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ADLastErrorStrategySpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedThrough('getInstance', ['ad', true]);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Connection\ADLastErrorStrategy');
    }
}

Add a missing license header to a file.

Add a missing license header to a file.


<?php

namespace Frontend\Modules\Tags\Tests\Actions;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Frontend\Core\Tests\FrontendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class IndexTest extends FrontendWebTestCase
{
    public function testTagsIndexShowsTags(Client $client): void
    {
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );

        self::assertPageLoadedCorrectly(
            $client,
            '/en/tags',
            [
                '',
                LoadTagsTags::TAGS_TAG_2_NAME,
                '6',
            ]
        );
    }
}

Fix tags index test because of layout changes


<?php

declare(strict_types=1);

namespace Inowas\ModflowModel\Model\Command;

use Inowas\Common\Id\ModflowId;
use Inowas\Common\Id\UserId;
use Inowas\Common\Soilmodel\LayerId;
use Prooph\Common\Messaging\Command;
use Prooph\Common\Messaging\PayloadConstructable;
use Prooph\Common\Messaging\PayloadTrait;

class RemoveLayer extends Command implements PayloadConstructable
{

    use PayloadTrait;

    public static function forModflowModel(UserId $userId, ModflowId $modelId, LayerId $layerId): RemoveLayer
    {
        $self = new static(
            [
                'model_id' => $modelId->toString(),
                'layer_id' => $layerId->toString()
            ]
        );

        /** @var RemoveLayer $self */
        $self = $self->withAddedMetadata('user_id', $userId->toString());
        return $self;
    }

    public function schema(): string
    {
        return 'file://spec/schema/modflow/command/removeLayerPayload.json';
    }

    public function modelId(): ModflowId
    {
        return ModflowId::fromString($this->payload['model_id']);
    }

    public function userId(): UserId
    {
        return UserId::fromString($this->metadata['user_id']);
    }

    public function layerId(): LayerId
    {
        return LayerId::fromString($this->payload['layer_id']);
    }
}

<?php

declare(strict_types=1);

namespace Inowas\ModflowModel\Model\Command;

use Inowas\Common\Id\ModflowId;
use Inowas\Common\Id\UserId;
use Inowas\Common\Soilmodel\LayerId;
use Prooph\Common\Messaging\Command;
use Prooph\Common\Messaging\PayloadConstructable;
use Prooph\Common\Messaging\PayloadTrait;

class RemoveLayer extends Command implements PayloadConstructable
{

    use PayloadTrait;

    public static function forModflowModel(UserId $userId, ModflowId $modelId, LayerId $layerId): RemoveLayer
    {
        $self = new static(
            [
                'id' => $modelId->toString(),
                'layer_id' => $layerId->toString()
            ]
        );

        /** @var RemoveLayer $self */
        $self = $self->withAddedMetadata('user_id', $userId->toString());
        return $self;
    }

    public function schema(): string
    {
        return 'file://spec/schema/modflow/command/removeLayerPayload.json';
    }

    public function modelId(): ModflowId
    {
        return ModflowId::fromString($this->payload['id']);
    }

    public function userId(): UserId
    {
        return UserId::fromString($this->metadata['user_id']);
    }

    public function layerId(): LayerId
    {
        return LayerId::fromString($this->payload['layer_id']);
    }
}

Fix wrong model id key (1011)

Fix wrong model id key (1011)


<?php
/*
 * Part of tivars_lib
 * (C) 2015 Adrien 'Adriweb' Bertrand
 * https://github.com/adriweb/tivars_lib
 * License: MIT
 */

namespace tivars\TypeHandlers;

include_once "ITIVarTypeHandler.php";

// Type Handler for type 0x00: Real
class TH_0x00 implements ITIVarTypeHandler
{

    public function makeDataFromString($str = '', array $options = [])
    {
        // TODO: Implement makeDataFromString() method.
    }

    public function makeStringFromData(array $data = [], array $options = [])
    {
        if (count($data) !== 9)
        {
            throw new \Exception("Invalid data array. Needs to contain 9 bytes");
        }
        $flags      = $data[0];
        $isNegative = ($flags >> 7 === 1);
//      $isUndef    = ($flags  & 1 === 1); // if true, "used for initial sequence values"
        $exponent   = $data[1] - 0x80;
        $number     = '';
        for ($i = 2; $i < 8; $i++)
        {
            $number .= dechex($data[$i]);
        }
        $number = substr($number, 0, 1) . '.' . substr($number, 1);
        $number = ($isNegative ? -1 : 1) * pow(10, $exponent) * ((float)$number);

        return (string)$number;
    }
}

<?php
/*
 * Part of tivars_lib
 * (C) 2015 Adrien 'Adriweb' Bertrand
 * https://github.com/adriweb/tivars_lib
 * License: MIT
 */

namespace tivars\TypeHandlers;

include_once "ITIVarTypeHandler.php";

// Type Handler for type 0x00: Real
class TH_0x00 implements ITIVarTypeHandler
{

    public function makeDataFromString($str = '', array $options = [])
    {
        // TODO: Implement makeDataFromString() method.
    }

    public function makeStringFromData(array $data = [], array $options = [])
    {
        if (count($data) !== 9)
        {
            throw new \Exception("Invalid data array. Needs to contain 9 bytes");
        }
        $flags      = $data[0];
        $isNegative = ($flags >> 7 === 1);
//      $isUndef    = ($flags  & 1 === 1); // if true, "used for initial sequence values"
        $exponent   = $data[1] - 0x80;
        $number     = '';
        for ($i = 2; $i < 9; $i++)
        {
            $number .= dechex($data[$i]);
        }
        $number = substr($number, 0, 1) . '.' . substr($number, 1);
        $number = ($isNegative ? -1 : 1) * pow(10, $exponent) * ((float)$number);

        return (string)$number;
    }
}

Fix bad bound in Type 0x00 (Real) reading


<?php

namespace Isometriks\Bundle\RedditBotBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class PostFeedsCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this
            ->setName('reddit:bot:rss')
            ->setDescription('Post configured feeds to Reddit')
            ->addArgument('dateOffset', InputArgument::IS_ARRAY, 'A string for \DateTime->modify(), eg "1 day ago", "1 hour ago" etc')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $offset = $input->getArgument('dateOffset');

        if ($offset !== null) {
            $offset = implode(' ', $offset);
        }

        $feedManager = $this->getContainer()->get('isometriks_reddit_bot.feed_manager');
        $feedPoster = $this->getContainer()->get('isometriks_reddit_bot.feed_poster');

        $results = $feedManager->getFeedResults($offset);
        $feedPoster->postFeedResults($results);

        foreach ($results as $feedResult) {
            $output->writeln(sprintf('Posted %d items from %s to: /r/%s', count($feedResult), $feedResult->getFeed()->getUrl(), $feedResult->getFeed()->getSubreddit()));
        }
    }
}

<?php

namespace Isometriks\Bundle\RedditBotBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class PostFeedsCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this
            ->setName('reddit:bot:rss')
            ->setDescription('Post configured feeds to Reddit')
            ->addArgument('dateOffset', InputArgument::IS_ARRAY, 'A string for \DateTime->modify(), eg "1 day ago", "1 hour ago" etc')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $offset = $input->getArgument('dateOffset');
        $offset = count($offset) > 0 ? $offset : null;

        $feedManager = $this->getContainer()->get('isometriks_reddit_bot.feed_manager');
        $feedPoster = $this->getContainer()->get('isometriks_reddit_bot.feed_poster');

        $results = $feedManager->getFeedResults($offset);
        $feedPoster->postFeedResults($results);

        foreach ($results as $feedResult) {
            $output->writeln(sprintf('Posted %d items from %s to: /r/%s', count($feedResult), $feedResult->getFeed()->getUrl(), $feedResult->getFeed()->getSubreddit()));
        }
    }
}

Fix command again. It always returns an array just sometimes empty.


<?php

class DegustationAffectationValidator extends sfValidatorSchema {

      public function __construct($obj, $fields= null, $options = array(), $messages = array()) {

          $this->obj = $obj;
          parent::__construct($fields, $options, $messages);
      }

  		public function configure($options = array(), $messages = array()) {
          $this->addMessage('impossible_table', "La table n'existe pas ".$table);
      }

      protected function doClean($values) {
  			$errorSchema = new sfValidatorErrorSchema($this);
      	$hasError = false;

        $degustation = DegustationClient::getInstance()->find($values['degustation']);
        $infos = $degustation->getInfosDegustation();
      	if ($values['numero_table'] > $infos['nbTables']) {
      	    $errorSchema->addError(new sfValidatorError($this, 'impossible_table'), 'numero_table');
      	    $hasError = true;
      	}

      	if ($hasError) {
      		throw new sfValidatorErrorSchema($this, $errorSchema);
      	}
        return $values;
      }
  }

<?php

class DegustationAffectationValidator extends sfValidatorSchema {

      public function __construct($obj, $fields= null, $options = array(), $messages = array()) {

          $this->obj = $obj;
          parent::__construct($fields, $options, $messages);
      }

  		public function configure($options = array(), $messages = array()) {
          $this->addMessage('impossible_table', "La table selectionnée n'existe pas dans cette dégustation");
      }

      protected function doClean($values) {
  			$errorSchema = new sfValidatorErrorSchema($this);
      	$hasError = false;

        $degustation = DegustationClient::getInstance()->find($values['degustation']);
        $infos = $degustation->getInfosDegustation();

      	if ($values['numero_table'] > $infos['nbTables'] +1) {
      	    $errorSchema->addError(new sfValidatorError($this, 'impossible_table'), 'numero_table');
      	    $hasError = true;
      	}

      	if ($hasError) {
      		throw new sfValidatorErrorSchema($this, $errorSchema);
      	}
        return $values;
      }
  }

Debug : unfund variable $table ->suppression


<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 */

namespace PH7;

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

// Default contents value
$sHtml = '';

/*** Begin Contents ***/

$sHtml .= t('Done!');

/*** End Contents ***/

// Output!
return $sHtml;

<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 */

namespace PH7;

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

// Default contents value
$sHtml = '';

/*** Begin Contents ***/

$sHtml .= t("Hooray! It's all done :)");

/*** End Contents ***/

// Output!
return $sHtml;

Update Conclusion (upgrade done) message


@if (@fopen($file_url.'/'.$name.'/admin_'.$item->$name, 'r'))
	{{ HTML::image($file_url.'/'.$name.'/admin_'.$item->$name) }}
@else
	{{ HTML::image(admin_asset('img/admin.jpg')) }}
@endif

@if ($item->$name && @fopen($file_url.'/'.$name.'/admin_'.$item->$name, 'r'))
	{{ HTML::image($file_url.'/'.$name.'/admin_'.$item->$name) }}
@else
	{{ HTML::image(admin_asset('img/admin.jpg')) }}
@endif

Fix display image for listing

Fix display image for listing


<!DOCTYPE html>

    <meta charset="utf-8">
    <title>A Plea for Colour Analysis Tools in DCC Applications</title>

    <?php include ("common_header_attributes.php"); ?>

<?php include_once("analytics_tracking.php") ?>

<?php include ("navigation.php"); ?>

            <?php include("disqus.php") ?>

        <?php include ("sidebar.php"); ?>

<?php include ("footer.php"); ?>

<?php include ("common_body_attributes.php"); ?>

Update "A Plea for Colour Analysis Tools in DCC Applications" blog post div height.


<?php

use PHPUnit_Framework_TestCase as PHPUnit;
use Application\NativeElements\Math;

class PHPNativeElementsTest extends PHPUnit {

	/**
	 * undocumented function
	 *
	 * @return void
	 **/
	public function setUp()
	{
		$this->math = new Math;
	}

	/**
	 * undocumented function
	 *
	 * @return void
	 **/
	public function tearDown()
	{

	}

	/**
	 * Test Operation Math
	 *
	 * @return void
	 **/
	public function testOperationMath()
	{
		$this->assertEquals(3, $this->math->sum(1, 2), 'Não somou corretamente');
	}

}

<?php

use PHPUnit_Framework_TestCase as PHPUnit;
use Application\NativeElements\Math;

class PHPNativeElementsTest extends PHPUnit {

	/**
	 * undocumented function
	 *
	 * @return void
	 **/
	public function setUp()
	{
		$this->math = new Math;
	}

	/**
	 * undocumented function
	 *
	 * @return void
	 **/
	public function tearDown()
	{

	}

	/**
	 * Test Operation Math
	 *
	 * @return void
	 **/
	public function testOperationMath()
	{
		$this->assertEquals(3, $this->math->sum(1, 2), 'not added correctly');
	}

}

Update message in assert test

Update message in assert test


<?php

namespace MockaTests\Mocka;

use \Mocka\Mocka;

class ClassTraitTest extends \PHPUnit_Framework_TestCase {

    public function testMockClass() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass');
        $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass);
    }

    public function testMockInterface() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockInterface('\MockaMocks\InterfaceMock');
        $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass);
    }

    public function testCallMockedMethod() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass');
        /** @var \MockaMocks\AbstractClass|\Mocka\ClassTrait $object */
        $object = $mockClass->newInstance();
        $this->assertNull($object->foo());
        $this->assertSame('bar', $object->bar());

        $mockClass->mockMethod('foo')->set(function () {
            return 'foo';
        });
        $this->assertSame('foo', $object->foo());

        $object->mockMethod('foo')->set(function () {
            return 'bar';
        });
        $this->assertSame('bar', $object->foo());

        $objectAnother = $mockClass->newInstance();
        $this->assertSame('foo', $objectAnother->foo());
    }
}

<?php

namespace MockaTests\Mocka;

use \Mocka\Mocka;

class ClassTraitTest extends \PHPUnit_Framework_TestCase {

    public function testMockClass() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass');
        $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass);
    }

    public function testMockInterface() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockInterface('\MockaMocks\InterfaceMock');
        $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass);
    }

    public function testCallMockedMethod() {
        $mocka = new Mocka();
        $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass');
        /** @var \MockaMocks\AbstractClass|\Mocka\ClassTrait $object */
        $object = $mockClass->newInstance();
        $this->assertNull($object->foo());
        $this->assertSame('bar', $object->bar());

        $mockClass->mockMethod('foo')->set(function () {
            return 'foo';
        });
        $this->assertSame('foo', $object->foo());

        $object->mockMethod('foo')->set(function () {
            return 'bar';
        });
        $this->assertSame('bar', $object->foo());

        $objectAnother = $mockClass->newInstance();
        $this->assertSame('foo', $objectAnother->foo());

        $mockClass->mockMethod('foo')->set(function () {
            return 'zoo';
        });
        $this->assertSame('bar', $object->foo());
    }
}

Add one more case for testing mockMethod on object/class


<?php

namespace Oro\Bundle\TestFrameworkBundle\Pages\Objects;

use Oro\Bundle\TestFrameworkBundle\Pages\PageFilteredGrid;

class ConfigEntities extends PageFilteredGrid
{
    const URL = 'entity/config';

    public function __construct($testCase, $redirect = true)
    {
        $this->redirectUrl = self::URL;
        parent::__construct($testCase, $redirect);
    }

    public function add()
    {
        $this->test->byXPath("//a[@title='Create Entity']")->click();
        //due to bug BAP-965
        sleep(1);
        $this->waitPageToLoad();
        $this->waitForAjax();
        $entity = new ConfigEntity($this->test);
        return $entity->init(true);
    }

    public function open($entityData = array())
    {
        $contact = $this->getEntity($entityData);
        $contact->click();
        sleep(1);
        $this->waitPageToLoad();
        $this->waitForAjax();

        return new ConfigEntity($this->test);
    }

    public function delete()
    {
        $this->byXPath("//td[@class='action-cell']//a[contains(., '...')]")->click();
        $this->waitForAjax();
        $this->byXpath("//td[@class='action-cell']//a[@title= 'Remove']")->click();
        $this->waitForAjax();

        return $this;
    }
}

<?php

namespace Oro\Bundle\TestFrameworkBundle\Pages\Objects;

use Oro\Bundle\TestFrameworkBundle\Pages\PageFilteredGrid;

class ConfigEntities extends PageFilteredGrid
{
    const URL = 'entity/config/';

    public function __construct($testCase, $redirect = true)
    {
        $this->redirectUrl = self::URL;
        parent::__construct($testCase, $redirect);
    }

    public function add()
    {
        $this->test->byXPath("//a[@title='Create Entity']")->click();
        //due to bug BAP-965
        sleep(1);
        $this->waitPageToLoad();
        $this->waitForAjax();
        $entity = new ConfigEntity($this->test);
        return $entity->init(true);
    }

    public function open($entityData = array())
    {
        $contact = $this->getEntity($entityData);
        $contact->click();
        sleep(1);
        $this->waitPageToLoad();
        $this->waitForAjax();

        return new ConfigEntity($this->test);
    }

    public function delete()
    {
        $this->byXPath("//td[@class='action-cell']//a[contains(., '...')]")->click();
        $this->waitForAjax();
        $this->byXpath("//td[@class='action-cell']//a[@title= 'Remove']")->click();
        $this->waitForAjax();

        return $this;
    }
}

BAP-1793: Create Entity Selenium tests
 - fixed URL for entities config


<?php

final class PhabricatorSourceDocumentEngine
  extends PhabricatorTextDocumentEngine {

  const ENGINEKEY = 'source';

  public function getViewAsLabel(PhabricatorDocumentRef $ref) {
    return pht('View as Source');
  }

  public function canConfigureHighlighting(PhabricatorDocumentRef $ref) {
    return true;
  }

  protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
    return 'fa-code';
  }

  protected function getContentScore(PhabricatorDocumentRef $ref) {
    return 1500;
  }

  protected function newDocumentContent(PhabricatorDocumentRef $ref) {
    $content = $this->loadTextData($ref);

    $highlighting = $this->getHighlightingConfiguration();
    if ($highlighting !== null) {
      $content = PhabricatorSyntaxHighlighter::highlightWithLanguage(
        $highlighting,
        $content);
    } else {
      $content = PhabricatorSyntaxHighlighter::highlightWithFilename(
        $ref->getName(),
        $content);
    }

    return $this->newTextDocumentContent($content);
  }

}

<?php

final class PhabricatorSourceDocumentEngine
  extends PhabricatorTextDocumentEngine {

  const ENGINEKEY = 'source';

  public function getViewAsLabel(PhabricatorDocumentRef $ref) {
    return pht('View as Source');
  }

  public function canConfigureHighlighting(PhabricatorDocumentRef $ref) {
    return true;
  }

  protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
    return 'fa-code';
  }

  protected function getContentScore(PhabricatorDocumentRef $ref) {
    return 1500;
  }

  protected function newDocumentContent(PhabricatorDocumentRef $ref) {
    $content = $this->loadTextData($ref);

    $messages = array();

    $highlighting = $this->getHighlightingConfiguration();
    if ($highlighting !== null) {
      $content = PhabricatorSyntaxHighlighter::highlightWithLanguage(
        $highlighting,
        $content);
    } else {
      $highlight_limit = DifferentialChangesetParser::HIGHLIGHT_BYTE_LIMIT;
      if (strlen($content) > $highlight_limit) {
        $messages[] = $this->newMessage(
          pht(
            'This file is larger than %s, so syntax highlighting was skipped.',
            phutil_format_bytes($highlight_limit)));
      } else {
        $content = PhabricatorSyntaxHighlighter::highlightWithFilename(
          $ref->getName(),
          $content);
      }
    }

    return array(
      $messages,
      $this->newTextDocumentContent($content),
    );
  }

}

Disable default syntax highlighting for large files in DocumentEngine

Summary: Ref T13105. See also T7895. When users render very large files as source via DocumentEngine, skip highlighting.

Test Plan: Fiddled with the limit, viewed files, saw highlighting degrade.

Reviewers: mydeveloperday

Reviewed By: mydeveloperday

Maniphest Tasks: T13105

Differential Revision: https://secure.phabricator.com/D19306


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Channel\Model;

interface ChannelTypeInterface
{
    public const TYPE_WEBSITE = 'Website';

    public const TYPE_MOBILE = 'Mobile';

    public const TYPE_POS = 'POS';
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Channel\Model;

interface ChannelTypeInterface
{
    public const TYPE_WEBSITE = 'website';

    public const TYPE_MOBILE = 'mobile';

    public const TYPE_POS = 'pos';
}

Add channel's form and fixes

Add channel's form and fixes


<?php
/*
This template expects following variables:
- Mandatory
  $d: the object holding the goal
  $p: the object describing the permissions
- Optional
*/

$parent = $d->parent;
$child = $d->child;
?>

@include('field', array('name' => 'name'))
  @if($p['own_page'])
  {{ link_to_route('goals.create', trans('ui.goals.new'),
     array('original' => $d->id),
     array('class' => 'ajax button small')) }}
  @endif

@if(isset($parent))

    {{ link_to_route('goals.show', trans('ui.goals.parent'), $parent->id) }}

@endif
@if(isset($child))

    {{ link_to_route('goals.show', trans('ui.goals.child'), $child->id) }}

@endif
@include('feedback.index', array('d' => $d->feedbacks, 'obj_id' => $d->id, 'obj_type' => 'Goal'))
@include('agrees.widget', array('d' => $d->agrees, 'obj_id' => $d->id, 'obj_type' => 'Goal'))

<?php
/*
This template expects following variables:
- Mandatory
  $d: the object holding the goal
  $p: the object describing the permissions
- Optional
*/

$parent = $d->parent;
$child = $d->child;
?>

@include('field', array('name' => 'name'))
  @if(isset($p['own_page']) and $p['own_page'])
  {{ link_to_route('goals.create', trans('ui.goals.new'),
     array('original' => $d->id),
     array('class' => 'ajax button small')) }}
  @endif

@if(isset($parent))

    {{ link_to_route('goals.show', trans('ui.goals.parent'), $parent->id) }}

@endif
@if(isset($child))

    {{ link_to_route('goals.show', trans('ui.goals.child'), $child->id) }}

@endif
@include('feedback.index', array('d' => $d->feedbacks, 'obj_id' => $d->id, 'obj_type' => 'Goal'))
@include('agrees.widget', array('d' => $d->agrees, 'obj_id' => $d->id, 'obj_type' => 'Goal'))

Fix button for new versions

Fix button for new versions


<?php

namespace Concise\Console\ResultPrinter;

class CIResultPrinter extends DefaultResultPrinter
{
    protected $lastPercentage = -1;

    public function update()
    {
        $percentage = $this->counter->getPercentage($this->getTestCount());
        if ($percentage > $this->lastPercentage) {
            $this->write($this->getAssertionString());
            $this->lastPercentage = $percentage;
        }
    }
}

<?php

namespace Concise\Console\ResultPrinter;

class CIResultPrinter extends DefaultResultPrinter
{
    protected $lastPercentage = -1;

    public function update()
    {
        $percentage = $this->counter->getPercentage($this->getTestCount());
        if ($percentage > $this->lastPercentage) {
            $this->write($this->getAssertionString());
            $this->lastPercentage = $percentage;
        }
    }

    public function appendTextAbove($text)
    {
        parent::appendTextAbove("\n$text");
    }
}

Print new line above issue

Print new line above issue