<?php
namespace MathPHP\Statistics;

/**
 * Effect size is a quantitative measure of the strength of a phenomenon.
 * https://en.wikipedia.org/wiki/Effect_size
 */
class EffectSize
{
    /**
     * η² (Eta-squared)
     *
     * Eta-squared describes the ratio of variance explained in the dependent
     * variable by a predictor while controlling for other predictors, making
     * it analogous to the r².
     *
     *      SSB
     * η² = ---
     *      SST
     *
     * where:
     *  SSB = sum of squares between (treatment)
     *  SST = sum of squares total
     *
     * @param  number $SSB Sum of squares between (treatment)
     * @param  number $SST Sum of squares total
     *
     * @return number
     */
    public static function etaSquared($SSB, $SST)
    {
        return $SSB / $SST;
    }
}

<?php
namespace MathPHP\Statistics;

/**
 * Effect size is a quantitative measure of the strength of a phenomenon.
 * https://en.wikipedia.org/wiki/Effect_size
 */
class EffectSize
{
    /**
     * η² (Eta-squared)
     *
     * Eta-squared describes the ratio of variance explained in the dependent
     * variable by a predictor while controlling for other predictors, making
     * it analogous to the r².
     *
     *      SSB
     * η² = ---
     *      SST
     *
     * where:
     *  SSB = sum of squares between (treatment)
     *  SST = sum of squares total
     *
     * @param  number $SSB Sum of squares between (treatment)
     * @param  number $SST Sum of squares total
     *
     * @return number
     */
    public static function etaSquared($SSB, $SST)
    {
        return $SSB / $SST;
    }

    /**
     * η²p (Partial eta-squared)
     *
     *          SSB
     * η²p = ---------
     *       SSB + SSE
     *
     * where:
     *  SSB = sum of squares between (treatment)
     *  SSE = sum of squares error
     *
     * @param  number $SSB Sum of squares between (treatment)
     * @param  number $SSE Sum of squares error
     *
     * @return number
     */
    public static function partialEtaSquared($SSB, $SSE)
    {
        return $SSB / ($SSB + $SSE);
    }
}

Add partial eta-squared effect size.

Add partial eta-squared effect size.


<?php
/**
 * User: casperlai
 * Date: 2016/9/2
 * Time: 下午9:34
 */

namespace Casperlaitw\LaravelFbMessenger\Messages;

use Casperlaitw\LaravelFbMessenger\Contracts\Messages\Message;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\ThreadInterface;
use pimax\Messages\MessageButton;

/**
 * Class PersistentMenuMessage
 * @package Casperlaitw\LaravelFbMessenger\Messages
 */
class PersistentMenuMessage extends Message implements ThreadInterface
{
    use Deletable;

    /**
     * @var
     */
    private $buttons;

    /**
     * PersistentMenuMessage constructor.
     *
     * @param $buttons
     */
    public function __construct($buttons = [])
    {
        parent::__construct(null);
        $this->buttons = $buttons;
    }

    /**
     * Message to send
     * @return array
     */
    public function toData()
    {
        $buttons = collect($this->buttons);
        return [
            'setting_type' => 'call_to_actions',
            'thread_state' => 'existing_thread',
            'call_to_actions' => $buttons->map(function (MessageButton $item) {
                return $item->getData();
            })->toArray(),
        ];
    }
}

<?php
/**
 * User: casperlai
 * Date: 2016/9/2
 * Time: 下午9:34
 */

namespace Casperlaitw\LaravelFbMessenger\Messages;

use Casperlaitw\LaravelFbMessenger\Contracts\Messages\Message;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\ThreadInterface;

/**
 * Class PersistentMenuMessage
 * @package Casperlaitw\LaravelFbMessenger\Messages
 */
class PersistentMenuMessage extends Message implements ThreadInterface
{
    use Deletable;

    /**
     * @var
     */
    private $buttons;

    /**
     * PersistentMenuMessage constructor.
     *
     * @param $buttons
     */
    public function __construct($buttons = [])
    {
        parent::__construct(null);
        $this->buttons = $buttons;
    }

    /**
     * Message to send
     * @return array
     */
    public function toData()
    {
        $buttons = collect($this->buttons);
        return [
            'setting_type' => 'call_to_actions',
            'thread_state' => 'existing_thread',
            'call_to_actions' => $buttons->map(function (Button $item) {
                return $item->toData();
            })->toArray(),
        ];
    }
}

Fix persisten menu command fail.

fix: Fix persisten menu command fail.


<?php namespace Orchestra\Routing;

use Illuminate\Http\Request;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerRequestOnConsole();

        parent::register();
    }

    /**
     * Register the requst on console interface.
     *
     * @return void
     */
    protected function registerRequestOnConsole()
    {
        if ($this->app->runningInConsole()) {
            $this->app->instance('request', Request::createFromGlobals());
        }
    }

    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

<?php namespace Orchestra\Routing;

use Illuminate\Http\Request;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerRequestOnConsole();

        parent::register();
    }

    /**
     * Register the requst on console interface.
     *
     * @return void
     */
    protected function registerRequestOnConsole()
    {
        $app = $this->app;

        if ($app->runningInConsole()) {
            $url = $app['config']->get('app.url', 'http://localhost');

            $app->instance('request', Request::create($url, 'GET', [], [], [], $_SERVER));
        }
    }

    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

Tweak how request is generated for commandline.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php namespace system\Email;

class EmailTest extends \CIUnitTestCase
{
	public function testEmailValidation()
	{
		$config           = config('Email');
		$config->validate = true;
		$email            = new \CodeIgniter\Email\Email($config);
		$email->setTo('invalid');
		$this->assertStringContainsString('Invalid email address: invalid', $email->printDebugger());
	}
}

<?php namespace system\Email;

class EmailTest extends \CodeIgniter\Test\CIUnitTestCase
{
	public function testEmailValidation()
	{
		$config           = config('Email');
		$config->validate = true;
		$email            = new \CodeIgniter\Email\Email($config);
		$email->setTo('invalid');
		$this->assertStringContainsString('Invalid email address: invalid', $email->printDebugger());
	}
}

Update new tests for refactor

Update new tests for refactor


<?php
/**
 * Created by PhpStorm.
 * User: s216121
 * Date: 12.10.16
 * Time: 09:34
 */

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ProjectController extends Controller
{
    /**
     * @param $request Request
     * @param $dbversion string
     * @return Response
     * @Route("/{dbversion}/project/overview", name="project_overview")
     */
    public function overviewAction(Request $request, $dbversion){
        return $this->render(
            'project/overview.html.twig',
            [
                'dbversion' => $dbversion,
                'type' => 'project',
                'title' => 'Projects'
            ]
        );
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: s216121
 * Date: 12.10.16
 * Time: 09:34
 */

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ProjectController extends Controller
{
    /**
     * @param $request Request
     * @param $dbversion string
     * @return Response
     * @Route("/{dbversion}/project/overview", name="project_overview")
     */
    public function overviewAction(Request $request, $dbversion){
        return $this->render(
            'project/overview.html.twig',
            [
                'dbversion' => $dbversion,
                'type' => 'project',
                'title' => 'Projects'
            ]
        );
    }

    /**
     * @param $request Request
     * @param $dbversion string
     * @param $project_id string
     * @return Response
     * @Route("/{dbversion}/project/details/{project_id}", name="project_details")
     */
    public function detailsAction(Request $request, $dbversion, $project_id){
        $projectDetails = $this->get('app.api.webservice')->factory('details', 'projects');
        $query = $request->query;
        $query->set('dbversion', $dbversion);
        $query->set('ids', array($project_id));
        $projectResult = $projectDetails->execute($query, $request->getSession());
        return $this->render(
            'project/details.html.twig',
            [
                'dbversion' => $dbversion,
                'type' => 'project',
                'title' => 'Projects',
                'project' => $projectResult
            ]
        );
    }
}

Add route for project details

Add route for project details


<?php
/**
 * @package silverstripe-multisites
 */
class MultisitesFileFieldExtension extends Extension {

	/**
	 * prepends an assets/currentsite folder to the upload folder name.
	 **/
	public function useMultisitesFolder(){
		$site = Multisites::inst()->getActiveSite();
		$multisiteFolder = $site->Folder();

		if(!$multisiteFolder->exists()){
			$site->createAssetsSubfolder(true);
			$multisiteFolder = $site->Folder();
		}

		$this->owner->setFolderName($multisiteFolder->Name . '/' . $this->owner->getFolderName());

		return $this->owner;
	}

}

<?php
/**
 * @package silverstripe-multisites
 */
class MultisitesFileFieldExtension extends Extension {

	/**
	 * prepends an assets/currentsite folder to the upload folder name.
	 **/
	public function useMultisitesFolder(){
		$site = Multisites::inst()->getActiveSite();
        if (!$site) {
            return $this->owner;
        }
		$multisiteFolder = $site->Folder();

		if(!$multisiteFolder->exists()){
			$site->createAssetsSubfolder(true);
			$multisiteFolder = $site->Folder();
		}

		$this->owner->setFolderName($multisiteFolder->Name . '/' . $this->owner->getFolderName());

		return $this->owner;
	}

}

FIX Catch null active site reference

FIX Catch null active site reference

In some contexts (unsaved element) the $site object may not be available yet


<?php

namespace Timetorock\LaravelMonologSentry\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;

class MonologSentryServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->bootstrapRaven();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // Nothing to register
    }

    /**
     * Bootstraps Raven and Monolog together
     */
    private function bootstrapRaven()
    {
        $sentryDsn = config('sentry.dsn', null);
        $sentryOptions = config('sentry.options', []);

        if (!empty($sentryDsn)) {
            $client = new Raven_Client($sentryDsn, $sentryOptions);
            $handler = new RavenHandler($client);
            $handler->setFormatter(new LineFormatter("%message% %context% %extra%\n"));

            $monolog = Log::getMonolog();
            $monolog->pushHandler($handler);
        }
    }
}

<?php

namespace Timetorock\LaravelMonologSentry\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;

class MonologSentryServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->bootstrapRaven();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // Nothing to register
    }

    /**
     * Bootstraps Raven and Monolog together
     */
    private function bootstrapRaven()
    {
        $sentryDsn = config('sentry.dsn', null);

        if (!empty($sentryDsn)) {
            $handler = new RavenHandler(app('sentry'));
            $handler->setFormatter(new LineFormatter("%message% %context% %extra%\n"));

            $monolog = Log::getMonolog();
            $monolog->pushHandler($handler);
        }
    }
}

Use Sentry Laravel object as client.

Use Sentry Laravel object as client.


<?php

class TestRemoveIncludeParentheses extends PHPUnit_Framework_TestCase {

	/**
	 * @var string Code to test
	 */
	private $code = <<<CODE
<?php
include ('a.php');
?>
CODE;

	public function testEnabled() {
		$output = executeCommand(
			array(
				'--passes' => 'RemoveIncludeParentheses',
			),
			$this->code
		);

		$this->assertContains( "include 'a.php';", $output );
	}

	public function testDisabled() {
		$output = executeCommand(
			array(
				'--exclude' => 'RemoveIncludeParentheses',
			),
			$this->code
		);

		$this->assertContains( "include ('a.php');", $output );
	}

}

<?php

class TestRemoveIncludeParentheses extends PHPUnit_Framework_TestCase {

	/**
	 * @var string Code to test
	 */
	private $code = <<<CODE
<?php
include ('a.php');
require ('a.php');
?>
CODE;

	public function testEnabled() {
		$output = executeCommand(
			array(
				'--passes' => 'RemoveIncludeParentheses',
			),
			$this->code
		);

		$this->assertContains( "include 'a.php';", $output );
		$this->assertContains( "require 'a.php';", $output );
	}

	public function testDisabled() {
		$output = executeCommand(
			array(
				'--exclude' => 'RemoveIncludeParentheses',
			),
			$this->code
		);

		$this->assertContains( "include ('a.php');", $output );
		$this->assertContains( "require ('a.php');", $output );
	}

}

Test both require & include

Test both require & include


<?php

use Aedart\Scaffold\Console\BaseCommand;
use Mockery as m;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class BaseCommandTest
 *
 * @group console
 * @group baseCommand
 *
 * @coversDefaultClass Aedart\Scaffold\Console\BaseCommand
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class BaseCommandTest extends BaseUnitTest
{
    /**
     * Returns an instance of a BaseCommand mock
     *
     * @param string $name
     *
     * @return m\Mock|BaseCommand
     */
    public function makeBaseCommand($name)
    {
        return m::mock(BaseCommand::class, [$name])->makePartial();
    }

    /********************************************************
     * Actual tests
     *******************************************************/

    // TODO: It appears that it's not possible to mock the command - Mockery yield error, cannot find setName() on mock!?

//    /**
//     * @test
//     *
//     * @covers ::execute
//     * @covers ::runCommand
//     */
//    public function canExecuteRunCommand()
//    {
//        $name = 'baseCommand';
//        $baseCommand = $this->makeBaseCommand($name);
//        $baseCommand->shouldReceive('runCommand')
//            ->andReturn(0);
//
//        $app = new Application();
//        $app->add($baseCommand);
//
//        $command = $app->find($name);
//        $commandTester = new CommandTester($command);
//        $commandTester->execute([
//           'command' => $command->getName()
//        ]);
//    }
}

<?php

use Aedart\Scaffold\Console\BaseCommand;
use Mockery as m;
use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Class BaseCommandTest
 *
 * @group console
 * @group baseCommand
 *
 * @coversDefaultClass Aedart\Scaffold\Console\BaseCommand
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class BaseCommandTest extends ConsoleTest
{
    /**
     * Returns an instance of a BaseCommand mock
     *
     * @return m\Mock|BaseCommand
     */
    public function makeBaseCommand()
    {
        return m::mock(BaseCommand::class)->makePartial();
    }

    /********************************************************
     * Actual tests
     *******************************************************/

    /**
     * @test
     *
     * @covers ::execute
     * @covers ::runCommand
     */
    public function canExecuteRunCommand()
    {

        $input = $this->makeInputMock();
        $input->shouldDeferMissing();

        // Output is very hard to mock at this point!
        $output = new ConsoleOutput();

        $command = $this->makeBaseCommand();
        $command->shouldReceive('runCommand')
            ->once();

        $command->execute($input, $output);
    }
}

Fix Base Command unit test

Fix Base Command unit test

No need to test the command via Symfony's CommandTester. We only need
to ensure that the runCommand gets executed.


<?php
  namespace ActiveCollab\Resistance\Test;

  use ActiveCollab\Resistance;

  /**
   * @package ActiveCollab\Resistance\Test
   */
  abstract class TestCase extends \PHPUnit_Framework_TestCase
  {
    /**
     * Switch to test database
     */
    public function setUp()
    {
      if (getenv('TEST_REDIS_CLUSTER')) {
        Resistance::connectToCluster([ '127.0.0.1:30001', '127.0.0.1:30002', '127.0.0.1:30003', '127.0.0.1:30004', '127.0.0.1:30005' ]);
      } else {
        Resistance::connect();
      }

      Resistance::reset();
    }

    /**
     * Tear down test database
     */
    public function tearDown()
    {
      Resistance::reset();
    }
  }

<?php
  namespace ActiveCollab\Resistance\Test;

  use ActiveCollab\Resistance;

  /**
   * @package ActiveCollab\Resistance\Test
   */
  abstract class TestCase extends \PHPUnit_Framework_TestCase
  {
    /**
     * Switch to test database
     */
    public function setUp()
    {
      if (getenv('TEST_REDIS_CLUSTER')) {
        print "Resistance: Connecting to Redis Cluster...\n";
        Resistance::connectToCluster([ '127.0.0.1:30001', '127.0.0.1:30002', '127.0.0.1:30003', '127.0.0.1:30004', '127.0.0.1:30005' ]);
      } else {
        print "Resistance: Connecting to Standalone Redis...\n";
        Resistance::connect();
      }

      Resistance::reset();
    }

    /**
     * Tear down test database
     */
    public function tearDown()
    {
      Resistance::reset();
    }
  }

Make sure that we are connected to the cluster


<?php

return [

    /**
     * By default Glide uses the GD library. However you can also use Glide with ImageMagick
     * if the Imagick PHP extension is installed.
     */
    'driver' => env( 'GLIDE_DRIVER', 'gd' ),

    /**
     * Name of the disk where source images are stored
     */
    'source_disk' => env( 'GLIDE_SOURCE_DISK', 'local' ),

    /**
     * Name of the disk where processed images must be stored
     */
    'cache_disk' => env( 'GLIDE_SOURCE_DISK', 'public' ),

    /**
     * Name of the disk where watermarks are stored
     */
    'watermarks_disk' => env( 'GLIDE_WATERMARKS_DISK', 'local' ),

    /**
     * In certain situations you may want to define default image manipulations.
     * For example, maybe you want to specify that all images are outputted as JPEGs (fm=jpg).
     * Or maybe you have a watermark that you want added to all images.
     * Glide makes this possible using default manipulations.
     */
    'defaults' => [],

    /**
     * Glide also makes it possible to define groups of defaults, known as presets.
     * This is helpful if you have standard image manipulations that you use throughout your app.
     */
    'presets' => [
        'thumbnail_200x200' => [
            'w' => 200,
            'h' => 200,
            'fit' => 'crop',
        ],
    ],
];

<?php

return [

    /*
     * By default Glide uses the GD library. However you can also use Glide with ImageMagick
     * if the Imagick PHP extension is installed.
     */
    'driver' => env( 'GLIDE_DRIVER', 'gd' ),

    /*
     * Name of the disk where source images are stored
     */
    'source_disk' => env( 'GLIDE_SOURCE_DISK', 'local' ),

    /*
     * Name of the disk where processed images must be stored
     */
    'cache_disk' => env( 'GLIDE_CACHE_DISK', 'public' ),

    /*
     * Name of the disk where watermarks are stored
     */
    'watermarks_disk' => env( 'GLIDE_WATERMARKS_DISK', 'local' ),

    /*
     * In certain situations you may want to define default image manipulations.
     * For example, maybe you want to specify that all images are outputted as JPEGs (fm=jpg).
     * Or maybe you have a watermark that you want added to all images.
     * Glide makes this possible using default manipulations.
     */
    'defaults' => [],

    /*
     * Glide also makes it possible to define groups of defaults, known as presets.
     * This is helpful if you have standard image manipulations that you use throughout your app.
     */
    'presets' => [
        'thumbnail_200x200' => [
            'w' => 200,
            'h' => 200,
            'fit' => 'crop',
        ],
    ],
];

Fix typo in environment variable name

Fix typo in environment variable name


	<?php if(is_front_page()) : ?>

	<?php endif ?>

      <?php
      if (has_nav_menu('primary_navigation')) :
        wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav-collapse']);
      endif;
      ?>

    <a class="navbar-brand" href="<?= esc_url(home_url('/')); ?>">Hamilton Wellness Resources
      <?php if(is_front_page()) : ?>

				Free Consultation

<?php echo get_bloginfo ( 'description' ); ?>

	<?php endif ?>

<?php if ( !is_front_page() && !is_home() && function_exists('yoast_breadcrumb') ) {
  yoast_breadcrumb('
','
');
} ?>

	<?php if(is_front_page()) : ?>

	<?php endif ?>

    <a class="navbar-brand" href="<?= esc_url(home_url('/')); ?>">Hamilton Wellness Resources

      <?php
      if (has_nav_menu('primary_navigation')) :
        wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav-collapse']);
      endif;
      ?>

      <?php if(is_front_page()) : ?>

				Free Consultation

<?php echo get_bloginfo ( 'description' ); ?>

	<?php endif ?>

<?php if ( !is_front_page() && !is_home() && function_exists('yoast_breadcrumb') ) {
  yoast_breadcrumb('
','
');
} ?>

Switch back order of nav and logo.

Switch back order of nav and logo.


<?php

/*
 * Copyright 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// [START index.php]
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function () {
    return 'Hello World';
});

$app->get('/goodbye', function () {
    return 'Goodbye World';
});

// @codeCoverageIgnoreStart
if (PHP_SAPI != 'cli') {
    $app->run();
}
// @codeCoverageIgnoreEnd

return $app;
// [END index.php]

<?php

/*
 * Copyright 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// [START index_php]
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function () {
    return 'Hello World';
});

$app->get('/goodbye', function () {
    return 'Goodbye World';
});

// @codeCoverageIgnoreStart
if (PHP_SAPI != 'cli') {
    $app->run();
}
// @codeCoverageIgnoreEnd

return $app;
// [END index_php]

Remove the periods from the region tags.


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.5';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.6';
}

Set release version to 0.8.6

Set release version to 0.8.6


<?php

namespace Modularity\Helper;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
use RegexIterator;

class Acf
{
    public function __construct()
    {
        add_action('init', array($this, 'includeAcf'), 11);
        add_filter('acf/settings/l10n', function () {
            return true;
        });
    }

    /**
     * Includes Advanced Custom Fields if missing, notifies user to activate ACF PRO to get full expirience
     * @return void
     */
    public function includeAcf()
    {
        include_once ABSPATH . 'wp-admin/includes/plugin.php';

        if (!is_plugin_active('advanced-custom-fields-pro/acf.php')
            && !is_plugin_active('advanced-custom-fields/acf.php')
        ) {
            require_once MODULARITY_PATH . 'plugins/acf/acf.php';

            add_action('admin_notices', function () {
                echo '

' .
                        __('To get the full expirience of the Modularity plugin, please activate the Advanced Custom Fields Pro plugin.', 'modularity') .
                     '

';
            });
        }
    }
}

<?php

namespace Modularity\Helper;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
use RegexIterator;

class Acf
{
    public function __construct()
    {
        add_action('init', array($this, 'includeAcf'), 11);
        add_filter('acf/settings/l10n', function () {
            return true;
        });
    }

    /**
     * Includes Advanced Custom Fields if missing, notifies user to activate ACF PRO to get full expirience
     * @return void
     */
    public function includeAcf()
    {
        if (!(class_exists('acf_pro') || class_exists('ACF'))) {
            require_once MODULARITY_PATH . 'plugins/acf/acf.php';

            add_action('admin_notices', function () {
                echo '

' .
                        __('To get the full expirience of the Modularity plugin, please activate the Advanced Custom Fields Pro plugin.', 'modularity') .
                     '

';
            });
        }
    }
}

Change how Modularity checks for ACF

Change how Modularity checks for ACF

Checking if the classes 'acf_pro' or 'ACF' are loaded instead of using
'is_plugin_active'. This is more accurate since the 'is_plugin_active'
function for instance won't notice 'must-use' plugins.


<?php
$CONFIG = array(
  "loglevel" => "3",
  "logfile" => "/dev/stdout"
);

<?php
$CONFIG = array(
  "loglevel" => 3,
  "logfile" => "/dev/stdout"
);

Set loglevel to integer value

Set loglevel to integer value


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Console\Commands;

use Illuminate\Console\Command;
use LaravelRedis;

class EsIndexScoresSetSchema extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'es:index-scores:set-schema
        {--schema= : Schema version to be set (can also be specified using environment variable "schema")}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set schema version of score index.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $schema = presence($this->option('schema')) ?? presence(env('schema'));

        if ($schema === null) {
            return $this->error('Index schema must be specified');
        }

        LaravelRedis::set('osu-queue:score-index:'.config('osu.elasticsearch.prefix').'schema', $schema);
        $this->info("Set score index schema version to {$schema}");
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Console\Commands;

use App\Libraries\Search\ScoreSearch;
use Illuminate\Console\Command;

class EsIndexScoresSetSchema extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'es:index-scores:set-schema
        {--schema= : Schema version to be set (can also be specified using environment variable "schema")}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set schema version of score index.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $schema = presence($this->option('schema')) ?? presence(env('schema'));

        if ($schema === null) {
            return $this->error('Index schema must be specified');
        }

        (new ScoreSearch())->setSchema($schema);

        $this->info("Set score index schema version to {$schema}");
    }
}

Use existing score search set schema function for artisan command


<?php
/**
 * A record iterator
 * @package Jivoo\Models
 */
interface IRecordIterator extends Iterator {
  /**
   * Return the current element
   * @return IRecord A record
   */
  public function current();
}

<?php
/**
 * A record iterator
 * @package Jivoo\Models
 */
interface IRecordIterator extends Iterator {
  /**
   * Return the current element
   * @return IRecord A record
   */
//   public function current();
}

Remove override of abstract method

Remove override of abstract method


<?php

namespace Aurora\Console\Commands;

use Aurora\Services\Fastly;
use Aurora\Resources\Redirect;
use Illuminate\Console\Command;

class FastlyImportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fastly:import {path}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import Fastly dictionaries to this app\'s service.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Fastly $fastly)
    {
        $input = file_get_contents($this->argument('path'));

        $redirects = array_map(function ($redirect) {
            return new Redirect($redirect);
        }, json_decode($input, true));

        $url = config('services.fastly.service_url');
        $confirmation = 'Would you like to create ' . count($redirects) . ' redirects on ' . $url . '?';
        if ($this->confirm($confirmation)) {
            $progress = $this->output->createProgressBar(count($redirects));
            foreach ($redirects as $redirect) {
                $fastly->createRedirect($redirect->path, $redirect->target, $redirect->status);
                $progress->advance();
            }

            $progress->finish();
        }

    }
}

<?php

namespace Aurora\Console\Commands;

use Aurora\Services\Fastly;
use Aurora\Resources\Redirect;
use Illuminate\Console\Command;

class FastlyImportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fastly:import {path}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import Fastly dictionaries to this app\'s service.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Fastly $fastly)
    {
        $input = file_get_contents($this->argument('path'));

        $redirects = array_map(function ($redirect) {
            return new Redirect($redirect);
        }, json_decode($input, true));

        $url = config('services.fastly.service_url');
        $confirmation = 'Would you like to create ' . count($redirects) . ' redirects on ' . $url . '?';
        if ($this->confirm($confirmation)) {
            foreach ($redirects as $redirect) {
                $this->line('Redirecting "' . $redirect->path . '" to "' . $redirect->target . '" (' . $redirect->status . ')');
                $fastly->createRedirect($redirect->path, $redirect->target, $redirect->status);
            }
        }

    }
}

Use more verbose progress output.

Use more verbose progress output.


<?php

namespace Nbj\Cockroach\Builder;

use Illuminate\Database\Schema\Builder;

class CockroachBuilder extends Builder
{
    /**
     * Determine if the given table exists.
     *
     * @param  string  $table
     * @return bool
     */
    public function hasTable($table)
    {
        if (is_array($schema = $this->connection->getConfig('schema'))) {
            $schema = head($schema);
        }

        $schema = $schema ? $schema : 'public';

        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select(
                $this->grammar->compileTableExists(), [$schema, $table]
            )) > 0;
    }

    /**
     * Drop all tables from the database.
     *
     * @return void
     */
    public function dropAllTables()
    {
        $tables = [];

        foreach ($this->getAllTables() as $row) {
            $row = (array) $row;

            $tables[] = reset($row);
        }

        if (empty($tables)) {
            return;
        }

        $this->connection->statement(
            $this->grammar->compileDropAllTables($tables)
        );
    }

    /**
     * Get all of the table names for the database.
     *
     * @return array
     */
    protected function getAllTables()
    {
        return $this->connection->select(
            $this->grammar->compileGetAllTables($this->connection->getConfig('schema'))
        );
    }
}

<?php

namespace Nbj\Cockroach\Builder;

use Illuminate\Database\Schema\Builder;

class CockroachBuilder extends Builder
{
    /**
     * Determine if the given table exists.
     *
     * @param  string  $table
     * @return bool
     */
    public function hasTable($table)
    {
        if (is_array($schema = $this->connection->getConfig('schema'))) {
            $schema = head($schema);
        }

        $schema = $schema ? $schema : 'public';

        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select(
                $this->grammar->compileTableExists(), [$schema, $table]
            )) > 0;
    }

    /**
     * Drop all tables from the database.
     *
     * @return void
     */
    public function dropAllTables()
    {
        $tables = [];

        foreach ($this->getAllTables() as $row) {
            $row = (array) $row;

            $tables[] = reset($row);
        }

        if (empty($tables)) {
            return;
        }

        $this->connection->statement(
            $this->grammar->compileDropAllTables($tables)
        );
    }

    /**
     * Get all of the table names for the database.
     *
     * @return array
     */
    public function getAllTables()
    {
        return $this->connection->select(
            $this->grammar->compileGetAllTables($this->connection->getConfig('schema'))
        );
    }
}

Fix for new builder of laravel

Fix for new builder of laravel


<?php

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Carbon;

use ReflectionMethod;
use Symfony\Contracts\Translation\TranslatorInterface;

$transMethod = new ReflectionMethod(TranslatorInterface::class, 'trans');

require $transMethod->hasReturnType()
    ? __DIR__ . '/TranslatorStrongType.php'
    : __DIR__ . '/TranslatorWeakType.php';

<?php

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Carbon;

use ReflectionMethod;
use Symfony\Contracts\Translation\TranslatorInterface;

require class_exists(TranslatorInterface::class) &&
    (new ReflectionMethod(TranslatorInterface::class, 'trans'))->hasReturnType()
    ? __DIR__ . '/TranslatorStrongType.php'
    : __DIR__ . '/TranslatorWeakType.php';

Use weak type if interface is not available


<?php

/*
 * This file is part of Evenement.
 *
 * (c) Igor Wiedler <igor@wiedler.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

const ITERATIONS = 100000;

use Evenement\EventEmitter;

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

$emitter = new EventEmitter();

for ($i = 0; $i < ITERATIONS; $i++) {
    $emitter->once('event', function ($a, $b, $c) {});
}

$start = microtime(true);
$emitter->emit('event', [1, 2, 3]);
$time = microtime(true) - $start;

echo 'Emitting one event to ', number_format(ITERATIONS), ' once listeners took: ', number_format($time, 2), 's', PHP_EOL;

<?php

/*
 * This file is part of Evenement.
 *
 * (c) Igor Wiedler <igor@wiedler.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

ini_set('memory_limit', '512M');

const ITERATIONS = 100000;

use Evenement\EventEmitter;

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

$emitter = new EventEmitter();

for ($i = 0; $i < ITERATIONS; $i++) {
    $emitter->once('event', function ($a, $b, $c) {});
}

$start = microtime(true);
$emitter->emit('event', [1, 2, 3]);
$time = microtime(true) - $start;

echo 'Emitting one event to ', number_format(ITERATIONS), ' once listeners took: ', number_format($time, 2), 's', PHP_EOL;

Set memory limit to avoid hitting it

Set memory limit to avoid hitting it


<?php

namespace APP\viewers;

/**
 * @package examples/blog
 * @author Xenophon Spafaridis <nohponex@gmail.com>
 */
class viewer implements \Phramework\API\viewers\IViewer {

    /**
     * Display output as html using a header and footer
     *
     * @param array $parameters Output parameters to display
     * @param $VIEWER_page $page Page's file name
     * @param $VIEWER_title Page's title
     */
    public function view($parameters) {
        $VIEWER_page = func_get_arg(1);
        $VIEWER_title = func_get_arg(2);

        extract($parameters);

        if (!isset($VIEWER_page) || !$VIEWER_page) { //In case page parameter is not set
            $VIEWER_page = 'error';
        }

        //copy title if not set as funtion argument and set in parameters
        if ((!isset($VIEWER_title) || !$VIEWER_title) && isset($parameters['title'])) {
            $VIEWER_title = $parameters['title'];
        }

        include(__DIR__ . '/header.php');

        //Include the page file
        include(__DIR__ . '/pages/' . $VIEWER_page . '.php');

        include(__DIR__ . '/footer.php');
    }

}

<?php

namespace APP\viewers;

/**
 * @package examples/blog
 * @author Xenophon Spafaridis <nohponex@gmail.com>
 */
class viewer implements \Phramework\API\viewers\IViewer {

    /**
     * Display output as html using a header and footer
     *
     * @param array $parameters Output parameters to display
     * @param $VIEWER_page $page Page's file name
     * @param $VIEWER_title Page's title
     */
    public function view($parameters) {
        $num_args = func_num_args();

        if ($num_args >1) {
            $VIEWER_page = func_get_arg(1);
        }
        if ($num_args >1) {
            $VIEWER_title = func_get_arg(2);
        }

        extract($parameters);

        if (!isset($VIEWER_page) || !$VIEWER_page) { //In case page parameter is not set
            $VIEWER_page = 'error';
        }

        //copy title if not set as funtion argument and set in parameters
        if ((!isset($VIEWER_title) || !$VIEWER_title) && isset($parameters['title'])) {
            $VIEWER_title = $parameters['title'];
        }

        include(__DIR__ . '/header.php');

        //Include the page file
        include(__DIR__ . '/pages/' . $VIEWER_page . '.php');

        include(__DIR__ . '/footer.php');
    }

}

Fix additional argument parsing at examples/blog.

Additional arguments might not be set (in case of error call etc)


<?php

/*
 * This file is part of NotifyMe.
 *
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NotifyMeHQ\NotifyMe;

use InvalidArgumentException;

class NotifyMeFactory implements FactoryInterface
{
    /**
     * Create a new gateway instance.
     *
     * @param string[] $config
     *
     * @return \NotifyMeHQ\NotifyMe\GatewayInterface
     */
    public function make(array $config)
    {
        return $this->createFactory($config)->make($config);
    }

    /**
     * Create a connector instance based on the configuration.
     *
     * @param string[] $config
     *
     * @throws \InvalidArgumentException
     *
     * @return \NotifyMeHQ\NotifyMe\FactoryInterface
     */
    public function createFactory(array $config)
    {
        if (!isset($config['driver'])) {
            throw new InvalidArgumentException("A driver must be specified.");
        }

        $dirver = ucfirst($config['driver']);
        $class = "NotifyMeHQ\\{$dirver}\\{$dirver}Factory";

        if (class_exists($class)) {
            return new $class();
        }

        throw new InvalidArgumentException("Unsupported driver [{$config['driver']}].");
    }
}

<?php

/*
 * This file is part of NotifyMe.
 *
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NotifyMeHQ\NotifyMe;

use InvalidArgumentException;

class NotifyMeFactory implements FactoryInterface
{
    /**
     * Create a new gateway instance.
     *
     * @param string[] $config
     *
     * @return \NotifyMeHQ\NotifyMe\GatewayInterface
     */
    public function make(array $config)
    {
        return $this->createFactory($config)->make($config);
    }

    /**
     * Create a connector instance based on the configuration.
     *
     * @param string[] $config
     *
     * @throws \InvalidArgumentException
     *
     * @return \NotifyMeHQ\NotifyMe\FactoryInterface
     */
    public function createFactory(array $config)
    {
        if (!isset($config['driver'])) {
            throw new InvalidArgumentException("A driver must be specified.");
        }

        $driver = ucfirst($config['driver']);
        $class = "NotifyMeHQ\\{$driver}\\{$driver}Factory";

        if (class_exists($class)) {
            return new $class();
        }

        throw new InvalidArgumentException("Unsupported driver [{$config['driver']}].");
    }
}

Correct spelling of $driver variable

Correct spelling of $driver variable


@extends('fluxbb::layout.main')

@section('main')
{{-- TODO: Escape all the variables!!! --}}

@foreach ($categories as $cat_info)
<?php $category = $cat_info['category']; ?>

		{{ $category->cat_name }}

@foreach ($cat_info['forums'] as $forum)

				id)) }}">{{ $forum->forum_name }}
				{{ $forum->forum_desc }}

{{ $forum->numTopics() }} topics

{{ $forum->numPosts() }} posts

@endforeach

@endforeach

@endsection

@extends('fluxbb::layout.main')

@section('main')

{{-- TODO: Escape all the variables!!! --}}

@foreach ($categories as $cat_info)
<?php $category = $cat_info['category']; ?>

		{{ $category->cat_name }}

@foreach ($cat_info['forums'] as $forum)

				id)) }}">{{ $forum->forum_name }}
				{{ $forum->forum_desc }}

{{ $forum->numTopics() }} topics

{{ $forum->numPosts() }} posts

@endforeach

@endforeach

@stop

Fix section end tag in Blade view.

Fix section end tag in Blade view.


<?php

class CM_Page_ExampleTest extends CMTest_TestCase {

    public function testAccessible() {
        $debugBackup = CM_Bootloader::getInstance()->isDebug();
        $page = new CM_Page_Example();

        CM_Bootloader::getInstance()->setDebug(true);
        $this->_renderPage($page);

        CM_Bootloader::getInstance()->setDebug(false);
        $this->assertPageNotRenderable($page);

        CM_Bootloader::getInstance()->setDebug($debugBackup);
    }

    public function testTidy() {
        $debugBackup = CM_Bootloader::getInstance()->isDebug();

        CM_Bootloader::getInstance()->setDebug(true);
        $page = $this->_createPage('CM_Page_Example');
        $html = $this->_renderPage($page);
        $this->assertTidy($html, false);

        CM_Bootloader::getInstance()->setDebug($debugBackup);
    }
}

<?php

class CM_Page_ExampleTest extends CMTest_TestCase {

    /** @var bool */
    private $_debugBackup;

    protected function setUp() {
        $this->_debugBackup = CM_Bootloader::getInstance()->isDebug();
    }

    protected function tearDown() {
        CM_Bootloader::getInstance()->setDebug($this->_debugBackup);
    }

    public function testAccessible() {
        $page = new CM_Page_Example();

        CM_Bootloader::getInstance()->setDebug(true);
        $this->_renderPage($page);

        CM_Bootloader::getInstance()->setDebug(false);
        $this->assertPageNotRenderable($page);
    }

    public function testTidy() {
        CM_Bootloader::getInstance()->setDebug(true);
        $page = $this->_createPage('CM_Page_Example');
        $html = $this->_renderPage($page);
        $this->assertTidy($html, false);
    }
}

Make sure to always restore "debug" state in page-example test


Witaj,

@if (count($data['added']) > 0)

Poniżej znajduja się twoje NOWE dodane do dziennika oceny.

@foreach($data['added'] as $grade)
Data: {{ $grade->date  }}

Ocena: {{ $grade->value  }}

Waga: {{ $grade->weight  }}

Przedmiot: {{ $grade->subject->name }}

Tytuł: {{ $grade->abbreviation }} - {{ $grade->title  }}

@endforeach

@endif
@if (count($data['deleted']) > 0)

Poniższe oceny zostały USUNIĘTE z dziennika:
@foreach($data['deleted'] as $grade)
Data: {{ $grade->date  }}

Ocena: {{ $grade->value  }}

Waga: {{ $grade->weight  }}

Przedmiot: {{ $grade->subject->name }}

Tytuł: {{ $grade->abbreviation }} - {{ $grade->title  }}

@endforeach

@endif

Z poważaniem,

DziennikLogin

Witaj,

@if (count($data['added']) > 0)

Poniżej znajduja się twoje NOWE dodane do dziennika oceny.

@foreach($data['added'] as $grade)
Data: {{ $grade->date  }}

Ocena: {{ $grade->value  }}

Waga: {{ $grade->weight  }}

Przedmiot: {{ $grade->subject->name }}

Tytuł: {{ $grade->abbreviation }} - {{ $grade->title  }}

@endforeach

@endif
@if (count($data['deleted']) > 0)

Poniższe oceny zostały USUNIĘTE z dziennika:
@foreach($data['deleted'] as $grade)
Data: {{ $grade->date  }}

Ocena: {{ $grade->value  }}

Waga: {{ $grade->weight  }}

Przedmiot: {{ $grade->subject->name }}

Tytuł: {{ $grade->abbreviation }} - {{ $grade->title  }}

@endforeach

@endif
@if(count($data['added']) === 0 && count($data['deleted']) === 0)

Brak nowych zmian.

@endif

Z poważaniem,

DziennikLogin

Update when 0 new grades

Update when 0 new grades


<?php declare(strict_types=1);

namespace Rector\Rector;

use Nette\Utils\Strings;
use PhpParser\Node;
use Rector\Node\Attribute;

abstract class AbstractPHPUnitRector extends AbstractRector
{
    /**
     * Check if the file is a PHPUnit TestCase. By default, it should end with "Test", as it is the standard.
     *
     * @see https://phpunit.de/getting-started-with-phpunit.html
     */
    protected function isInTestClass(Node $node): bool
    {
        $className = $node->getAttribute(Attribute::CLASS_NAME);

        return Strings::endsWith((string) $className, 'Test');
    }
}

<?php declare(strict_types=1);

namespace Rector\Rector;

use Nette\Utils\Strings;
use PhpParser\Node;
use Rector\Node\Attribute;

abstract class AbstractPHPUnitRector extends AbstractRector
{
    /**
     * Check if the file is a PHPUnit TestCase. By default, it should end with "Test", as it is the standard.
     *
     * @see https://phpunit.de/getting-started-with-phpunit.html
     */
    protected function isInTestClass(Node $node): bool
    {
        $className = (string) $node->getAttribute(Attribute::CLASS_NAME);

        return Strings::endsWith($className, 'Test');
    }
}

Move cast to variable attribution

[CS] Move cast to variable attribution


<?php

namespace Lily\Example\Application;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Middleware as MW;

use Lily\Util\Response;

use Lily\Example\Controller\AdminController;

class AdminApplication extends MiddlewareApplication
{
    protected function middleware()
    {
        return array(
            $this->routedApplication(),
            $this->adminAuthMiddleware(),
            new MW\Cookie(array('salt' => 'random')),
        );
    }

    private function routedApplication()
    {
        return new RoutedApplication(array(
            array('GET', '/admin', $this->action('index')),

            array('GET',  '/admin/login', $this->action('login')),
            array('POST', '/admin/login', $this->action('login_process')),

            array('GET', '/admin/logout', $this->action('logout')),
        ));
    }

    private function action($action)
    {
        return function ($request) use ($action) {
            $controller = new AdminController;
            return $controller->{$action}($request);
        };
    }

    private function adminAuthMiddleware()
    {
        return function ($handler) {
            return function ($request) use ($handler) {
                $isLogin = $request['uri'] === '/admin/login';
                $isAuthed = isset($request['cookies']['authed']);

                if ($isLogin AND $isAuthed) {
                    return Response::redirect('/admin');
                } else if ( ! $isLogin AND ! $isAuthed) {
                    return Response::redirect('/admin/login');
                }

                return $handler($request);
            };
        };
    }
}

<?php

namespace Lily\Example\Application;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Middleware as MW;

use Lily\Util\Response;

use Lily\Example\Controller\AdminController;

class AdminApplication extends MiddlewareApplication
{
    protected function middleware()
    {
        return array(
            $this->routedApplication(),
            $this->ensureAuthenticated(),
            new MW\Cookie(array('salt' => 'random')),
        );
    }

    private function routedApplication()
    {
        return new RoutedApplication(array(
            array('GET', '/admin', $this->action('index')),

            array('GET',  '/admin/login', $this->action('login')),
            array('POST', '/admin/login', $this->action('login_process')),

            array('GET', '/admin/logout', $this->action('logout')),
        ));
    }

    private function action($action)
    {
        return function ($request) use ($action) {
            $controller = new AdminController;
            return $controller->{$action}($request);
        };
    }

    private function ensureAuthenticated()
    {
        return function ($handler) {
            return function ($request) use ($handler) {
                $isLogin = $request['uri'] === '/admin/login';
                $isAuthed = isset($request['cookies']['authed']);

                if ($isLogin AND $isAuthed) {
                    return Response::redirect('/admin');
                } else if ( ! $isLogin AND ! $isAuthed) {
                    return Response::redirect('/admin/login');
                }

                return $handler($request);
            };
        };
    }
}

Update method name to explain what the method does


<?php
/**
 * controllers/About.php
 *
 *
 * @package ITC260
 * @subpackage About
 * @author Ron Redmond
 * @version 1.0 2015/05/14
 * @link
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @see
 * @todo
 */

class About extends CI_Controller {

        public function index()
        {
                $this->load->view('pages/about');
        }
}

<?php
/**
 * controllers/About.php
 *
 *
 * @package ITC260
 * @subpackage About
 * @author Ron Redmond
 * @version 1.0 2015/05/14
 * @link
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @see view/pages/about.php
 * @todo
 */

class About extends CI_Controller {

        public function index()
        {
                $this->load->view('pages/about');
        }
}

Update docblock with @see view/pages/about.php


<?php

class AlgorithmConnectedComponents extends Algorithm{

    /**
     *
     * @var Graph
     */
    private $graph;

    /**
     *
     * @param Graph $graph
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * check whether this graph consists of only a single component
     *
     * could be improved by not checking for actual number of components but stopping when there's more than one
     *
     * @return boolean
     * @uses AlgorithmConnectedComponents::getNumberOfComponents()
     */
    public function isSingle(){
        return ($this->getNumberOfComponents() === 1);
    }

    /**
     * @return int number of components
     * @uses Graph::getVertices()
     * @uses AlgorithmSearchDepthFirst::getVertices()
     */
    public function getNumberOfComponents(){
        $visitedVertices = array();
        $components = 0;

        foreach ($this->graph->getVertices() as $vertex){                        //for each vertices
            if ( ! isset( $visitedVertices[$vertex->getId()] ) ){                    //did I visit this vertex before?

                $alg = new AlgorithmSearchDepthFirst($vertex);
                $newVertices = $alg->getVertices();                                    //get all vertices of this component

                $components++;

                foreach ($newVertices as $v){                                            //mark the vertices of this component as visited
                    $visitedVertices[$v->getId()] = true;
                }
            }
        }

        return $components;                                                        //return number of components
    }
}

<?php

class AlgorithmConnectedComponents extends Algorithm{

    /**
     *
     * @var Graph
     */
    private $graph;

    /**
     *
     * @param Graph $graph
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * check whether this graph consists of only a single component
     *
     * could be improved by not checking for actual number of components but stopping when there's more than one
     *
     * @return boolean
     * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices()
     */
    public function isSingle(){
        $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst());
        return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices());
    }

    /**
     * @return int number of components
     * @uses Graph::getVertices()
     * @uses AlgorithmSearchDepthFirst::getVertices()
     */
    public function getNumberOfComponents(){
        $visitedVertices = array();
        $components = 0;

        foreach ($this->graph->getVertices() as $vertex){                        //for each vertices
            if ( ! isset( $visitedVertices[$vertex->getId()] ) ){                    //did I visit this vertex before?

                $alg = new AlgorithmSearchDepthFirst($vertex);
                $newVertices = $alg->getVertices();                                    //get all vertices of this component

                $components++;

                foreach ($newVertices as $v){                                            //mark the vertices of this component as visited
                    $visitedVertices[$v->getId()] = true;
                }
            }
        }

        return $components;                                                        //return number of components
    }
}

Improve check for single by only issuing search once


<?php

$url = $_POST['url'];
$name = preg_split("/\//", $url, 0, PREG_SPLIT_NO_EMPTY);
$fileName = dirname(__FILE__) . '/pdf/' . $name[sizeof($name) - 1] . '.pdf';

$baseUrl = $name[0] . '//' . $name[1] . '/cached/';

// $baseUrl = $name[0] . '//' . $name[1] . '/' . $name[2] . '/' . $name[3] . '/';

$output  = 'phantomjs --ignore-ssl-errors=true "' . dirname(__FILE__) . '/js/rasterize.js" "' . $baseUrl . $name[sizeof($name) - 1] . '.html' . '" "' . $fileName . '"';
exec($output);

if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fileName));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileName));
    readfile($fileName);
    exit;
}
?>

<?php

$url = $_POST['url'];
$name = preg_split("/\//", $url, 0, PREG_SPLIT_NO_EMPTY);
$fileName = dirname(__FILE__) . '/pdf/' . $name[sizeof($name) - 1] . '.pdf';

$baseUrl = $name[0] . '//' . $name[1] . '/cache/';

// $baseUrl = $name[0] . '//' . $name[1] . '/' . $name[2] . '/' . $name[3] . '/';

$output  = 'phantomjs --ignore-ssl-errors=true "' . dirname(__FILE__) . '/js/rasterize.js" "' . $baseUrl . $name[sizeof($name) - 1] . '.html' . '" "' . $fileName . '"';
exec($output);

if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fileName));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileName));
    readfile($fileName);
    exit;
}
?>

Update path filename for printing

Update path filename for printing


<?php

if (!function_exists('isUsingDarkMode')) {
    /**
     * Check if the site should be rendered using dark mode.
     *
     * @return boolean
     */
    function isUsingDarkMode()
    {
        if (request()->user() && request()->user()->theme == 'dark') {
            return true;
        }

        return app('settings')->get('app.theme') == 'dark';
    }
}

<?php

if (!function_exists('isUsingDarkMode')) {
    /**
     * Check if the site should be rendered using dark mode.
     *
     * @return boolean
     */
    function isUsingDarkMode()
    {
        if (request()->user() && request()->user()->theme !== null) {
            return request()->user()->theme == 'dark';
        }

        return app('settings')->get('app.theme') == 'dark';
    }
}

Fix user theme swap working when going from dark to light mode


<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/common-schema
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/common-schema
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');

Update Dotenv config to the new version

Update Dotenv config to the new version


<?php namespace VotingApp\Models;

use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Database\Eloquent\Model;

class Page extends Model implements SluggableInterface
{

    use SluggableTrait;

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'content'
    ];

    /**
     * Configuration for generating slug with Eloquent-Sluggable.
     *
     * @var array
     */
    protected $sluggable = [
        'build_from' => 'title',
        'save_to' => 'slug'
    ];

    public function setContentAttribute($content)
    {
        $this->attributes['content'] = $content;
        $this->attributes['content_html'] = Parsedown::instance()->text($content);
    }

}

<?php namespace VotingApp\Models;

use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Database\Eloquent\Model;
use Parsedown;

class Page extends Model implements SluggableInterface
{

    use SluggableTrait;

    /**
     * The attributes which may be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'content'
    ];

    /**
     * Configuration for generating slug with Eloquent-Sluggable.
     *
     * @var array
     */
    protected $sluggable = [
        'build_from' => 'title',
        'save_to' => 'slug'
    ];

    public function setContentAttribute($content)
    {
        $this->attributes['content'] = $content;
        $this->attributes['content_html'] = Parsedown::instance()->text($content);
    }

}

Fix error when saving pages.

Fix error when saving pages.


<?php
/**
 * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP\Files\Storage;

/**
 * Creates storage instances and manages and applies storage wrappers
 */
interface IStorageFactory {
	/**
	 * allow modifier storage behaviour by adding wrappers around storages
	 *
	 * $callback should be a function of type (string $mountPoint, Storage $storage) => Storage
	 *
	 * @param string $wrapperName
	 * @param callable $callback
	 * @return true if the wrapper was added, false if there was already a wrapper with this
	 * name registered
	 */
	public function addStorageWrapper($wrapperName, $callback);

	/**
	 * @param string|boolean $mountPoint
	 * @param string $class
	 * @param array $arguments
	 * @return \OCP\Files\Storage
	 */
	public function getInstance($mountPoint, $class, $arguments);
}

<?php
/**
 * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP\Files\Storage;

/**
 * Creates storage instances and manages and applies storage wrappers
 */
interface IStorageFactory {
	/**
	 * allow modifier storage behaviour by adding wrappers around storages
	 *
	 * $callback should be a function of type (string $mountPoint, Storage $storage) => Storage
	 *
	 * @param string $wrapperName
	 * @param callable $callback
	 * @return bool true if the wrapper was added, false if there was already a wrapper with this
	 * name registered
	 */
	public function addStorageWrapper($wrapperName, $callback);

	/**
	 * @param string|boolean $mountPoint
	 * @param string $class
	 * @param array $arguments
	 * @return \OCP\Files\Storage
	 */
	public function getInstance($mountPoint, $class, $arguments);
}

Fix return type of addStorageWrapper in PHPDoc


<?php

namespace OpsWay\ZohoBooks\Api;

class ItemAdjustments extends BaseApi
{
    const API_PATH = 'inventoryadjustments';
    const API_KEY = 'inventoryadjustment';
}

<?php

namespace OpsWay\ZohoBooks\Api;

class ItemAdjustments extends BaseApi
{
    const API_PATH = 'inventoryadjustments';
    const API_KEY = 'inventory_adjustment';
}

Fix Inventory Adjustment api key

Fix Inventory Adjustment api key


<?php

namespace Realm\Model;

use RuntimeException;

trait PropertyTrait
{
    protected $properties = [];

    public function addProperty(Property $property)
    {
        $languageCode = $this->normaliseLanguageCode($property->getLanguage());
        $this->properties[$languageCode][$property->getName()] = $property;
        return $this;
    }

    public function getProperties()
    {
        $p = [];
        array_walk_recursive(
            $this->properties,
            function ($x) use (&$p) {
                $p[] = $x;
            }
        );
        return $p;
    }

    public function hasProperty($name, $languageCode)
    {
        return isset(
            $this->properties[$this->normaliseLanguageCode($languageCode)][$name]
        );
    }

    public function getProperty($name, $languageCode)
    {
        $languageCode = $this->normaliseLanguageCode($languageCode);

        if (!$this->hasProperty($name, $languageCode)) {
            throw new RuntimeException("No such property: $languageCode/$name");
        }
        return $this->properties[$languageCode][$name];
    }

    public function getPropertyValue($name, $languageCode)
    {
        return $this->getProperty($name, $languageCode)->getValue();
    }

    private function normaliseLanguageCode($languageCode)
    {
        if (null === $languageCode || '' === $languageCode) {
            return '';
        }
        return str_replace('-', '_', $languageCode);
    }
}

<?php

namespace Realm\Model;

use RuntimeException;

trait PropertyTrait
{
    protected $properties = [];

    public function addProperty(Property $property)
    {
        $languageCode = $this->normaliseLanguageCode($property->getLanguage());
        $this->properties[$languageCode][$property->getName()] = $property;
        return $this;
    }

    public function getProperties()
    {
        $p = [];
        array_walk_recursive(
            $this->properties,
            function ($x) use (&$p) {
                $p[] = $x;
            }
        );
        return $p;
    }

    public function hasProperty($name, $languageCode)
    {
        return isset(
            $this->properties[$this->normaliseLanguageCode($languageCode)][$name]
        );
    }

    public function getProperty($name, $languageCode)
    {
        $languageCode = $this->normaliseLanguageCode($languageCode);

        if (!$this->hasProperty($name, $languageCode)) {
            throw new RuntimeException("No such property: $name/$languageCode");
        }
        return $this->properties[$languageCode][$name];
    }

    public function getPropertyValue($name, $languageCode)
    {
        return $this->getProperty($name, $languageCode)->getValue();
    }

    private function normaliseLanguageCode($languageCode)
    {
        if (null === $languageCode || '' === $languageCode) {
            return '';
        }
        return str_replace('-', '_', $languageCode);
    }
}

Fix debug message order (matching function argument order)


<?php

namespace Bolt\Nut;

use Stecman\Component\Symfony\Console\BashCompletion\CompletionCommand;
use Symfony\Component\Console\Application as ConsoleApplication;

/**
 * Nut application
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class NutApplication extends ConsoleApplication
{
    /**
     * Gets the default commands that should always be available.
     *
     * @return Command[] An array of default Command instances
     */
    protected function getDefaultCommands()
    {
        // Get the Symfony defaults
        $commands = parent::getDefaultCommands();

        return $commands;
    }
}

<?php

namespace Bolt\Nut;

use Stecman\Component\Symfony\Console\BashCompletion\CompletionCommand;
use Symfony\Component\Console\Application as ConsoleApplication;

/**
 * Nut application
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class NutApplication extends ConsoleApplication
{
    /**
     * Gets the default commands that should always be available.
     *
     * @return Command[] An array of default Command instances
     */
    protected function getDefaultCommands()
    {
        // Get the Symfony defaults
        $commands = parent::getDefaultCommands();

        // Add command completion
        $commands[] = new CompletionCommand();

        return $commands;
    }
}

Add a CompletionCommand to Nut's default command list


<?php

namespace OpenCFP\Domain\Model;

class TalkMeta extends Eloquent
{
    protected $table = 'talk_meta';

    const CREATED_AT = 'created';
    const UPDATED_AT = null;

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    public function talk()
    {
        return $this->belongsTo(Talk::class, 'talk_id');
    }

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

    public function setUpdatedAt($value)
    {
        /**
         * This is the dirty way to tell Illuminate that we don't have an updated at field
         * while still having a created_at field.
         */
    }
}

<?php

namespace OpenCFP\Domain\Model;

class TalkMeta extends Eloquent
{
    protected $table = 'talk_meta';

    const CREATED_AT = 'created';
    const UPDATED_AT = null;

    const DEFAULT_RATING = 0;
    const DEFAULT_VIEWED = 0;

    protected $attributes = [
        'rating' => self::DEFAULT_RATING,
        'viewed' => self::DEFAULT_VIEWED,
    ];

    public function talk()
    {
        return $this->belongsTo(Talk::class, 'talk_id');
    }

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

    public function setUpdatedAt($value)
    {
        /**
         * This is the dirty way to tell Illuminate that we don't have an updated at field
         * while still having a created_at field.
         */
    }
}

Add default values to the TalksMeta model


<?php

/**
 * This file is part of the php-utils.php package.
 *
 * Copyright (C) 2015 Tadatoshi Tokutake <tadatoshi.tokutake@gmail.com>
 *
 * Licensed under the MIT License
 */

function create_path(array $dirs)
{
   return array_reduce($dirs, function ($path, $dir) { return $path . $dir . DIRECTORY_SEPARATOR; }, '');
}

function demand_lib($php_file)
{
   require_once create_path(array(__DIR__, 'lib')) . $php_file;
}

demand_lib('general.inc'       );
demand_lib('debug.inc'         );
demand_lib('string.inc'        );
demand_lib('array.inc'         );
demand_lib('array_of_array.inc');

<?php

/**
 * This file is part of the php-utils.php package.
 *
 * Copyright (C) 2015 Tadatoshi Tokutake <tadatoshi.tokutake@gmail.com>
 *
 * Licensed under the MIT License
 */

function create_path(array $dirs)
{
   return array_reduce($dirs, function ($path, $dir) { return $path . $dir . DIRECTORY_SEPARATOR; }, '');
}

define('PATH_TO_LIB_FOR_PHP_UTILS', create_path(array(__DIR__, 'lib')));

require_once PATH_TO_LIB_FOR_PHP_UTILS . 'general.inc'       ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'debug.inc'         ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'string.inc'        ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array.inc'         ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array_of_array.inc';

Use the constant instead of demand_lib()


<?php
declare(strict_types=1);

namespace MyVendor\MyNamespace;

use LotGD\Core\Game;
use LotGD\Core\Module as ModuleInterface;
use LotGD\Core\Models\Module as ModuleModel;

class Module implements ModuleInterface {
    public static function handleEvent(Game $g, string $event, array $context) { }
    public static function onRegister(Game $g, ModuleModel $module) { }
    public static function onUnregister(Game $g, ModuleModel $module) { }
}

<?php
declare(strict_types=1);

namespace MyVendor\MyNamespace;

use LotGD\Core\Game;
use LotGD\Core\Module as ModuleInterface;
use LotGD\Core\Models\Module as ModuleModel;

class Module implements ModuleInterface {
    public static function handleEvent(Game $g, string $event, array &$context) { }
    public static function onRegister(Game $g, ModuleModel $module) { }
    public static function onUnregister(Game $g, ModuleModel $module) { }
}

Fix handleEvent callsite to match latest spec


<?php

$router = $di->get("router");

foreach ($application->getModules() as $key => $module) {
    $namespace = str_replace('Module','Controllers', $module["className"]);
    $router->add('/'.$key.'/:params', array(
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 'index',
        'action' => 'index',
        'params' => 1
    ))->setName($key);
    $router->add('/'.$key.'/:controller/:params', array(
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 'index',
        'params' => 2
    ));
    $router->add('/'.$key.'/:controller/:action/:params', array(
        'namespace' => $namespace,
        'module' => $key,
        'controller' => 1,
        'action' => 2,
        'params' => 3
    ));
}

$di->set("router", $router);

Send router back to DI

Send router back to DI

The routes set here are not actually being set, it just coincidentally works with a single demo module due to the "defaultNamespace" set in services.php


<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;

use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;

class DelegatingLoaderTest extends \PHPUnit_Framework_TestCase
{
    /** @var ControllerNameParser */
    private $controllerNameParser;

    public function setUp()
    {
        $this->controllerNameParser = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')
            ->disableOriginalConstructor()
            ->getMock();
    }

    /**
     * @group legacy
     */
    public function testLegacyConstructorApi()
    {
        new DelegatingLoader($this->controllerNameParser, new NullLogger(), new LoaderResolver());
        $this->assertTrue(true, '__construct() accepts a LoggerInterface instance as its second argument');
    }

    /**
     * @group legacy
     */
    public function testLegacyConstructorApiAcceptsNullAsSecondArgument()
    {
        new DelegatingLoader($this->controllerNameParser, null, new LoaderResolver());
        $this->assertTrue(true, '__construct() accepts null as its second argument');
    }

    public function testConstructorApi()
    {
        new DelegatingLoader($this->controllerNameParser, new LoaderResolver());
        $this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.');
    }
}

<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;

use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;

class DelegatingLoaderTest extends \PHPUnit_Framework_TestCase
{
    /** @var ControllerNameParser */
    private $controllerNameParser;

    protected function setUp()
    {
        $this->controllerNameParser = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')
            ->disableOriginalConstructor()
            ->getMock();
    }

    /**
     * @group legacy
     */
    public function testLegacyConstructorApi()
    {
        new DelegatingLoader($this->controllerNameParser, new NullLogger(), new LoaderResolver());
        $this->assertTrue(true, '__construct() accepts a LoggerInterface instance as its second argument');
    }

    /**
     * @group legacy
     */
    public function testLegacyConstructorApiAcceptsNullAsSecondArgument()
    {
        new DelegatingLoader($this->controllerNameParser, null, new LoaderResolver());
        $this->assertTrue(true, '__construct() accepts null as its second argument');
    }

    public function testConstructorApi()
    {
        new DelegatingLoader($this->controllerNameParser, new LoaderResolver());
        $this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.');
    }
}

Change few occurences of a public setUp() method to protected


<?php

namespace src;

$current = 'mysql:connect1';

$db = array(
	'mysql' => array(
		'connect1' => array(
			'hostname' => 'localhost',
			'username' => 'root',
			'password' => '',
			'database' => 'aa_atacms',
			'dbprefix' => 'aa_'

		)
	)
);

Set the database connection file refactor


<?php namespace Lio\ServiceProviders;

use Illuminate\Support\ServiceProvider;
use Hashids\Hashids;

class HashidsServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->bind('Hashids\Hashids', function() {
            $key = $this->app['config']->get('app.key');
            return new Hashids($key, 2);
        });
    }

    public function register() {
        return ['hashids'];
    }
}

<?php namespace Lio\ServiceProviders;

use Illuminate\Support\ServiceProvider;
use Hashids\Hashids;

class HashidsServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(['Hashids\Hashids' => 'hashids'], function() {
            $key = $this->app['config']->get('app.key');
            return new Hashids($key, 2);
        });
    }
}

Move Hashids binding to register method & fix alias

The `register()` method is more appropriate than `boot()` to register bindings with the container. This change also fixes the registration of the alias.


<?php
return array(
    'zf-content-negotiation' => array(
        'controllers' => array(),
        'selectors' => array(),
    ),
    /*
    'controllers' => array(
        'initializers' => array(
            'ZF\ContentNegotiation\ControllerInitializer'
        )
    ),
    */
    'controller_plugins' => array(
        'invokables' => array(
            'routeParam' => 'ZF\ContentNegotiation\ControllerPlugin\RouteParam',
            'queryParam' => 'ZF\ContentNegotiation\ControllerPlugin\QueryParam',
            'bodyParam' => 'ZF\ContentNegotiation\ControllerPlugin\BodyParam',
            'routeParams' => 'ZF\ContentNegotiation\ControllerPlugin\RouteParams',
            'queryParams' => 'ZF\ContentNegotiation\ControllerPlugin\QueryParams',
            'bodyParams' => 'ZF\ContentNegotiation\ControllerPlugin\BodyParams',
            'contentNegotiatedViewModel' => 'ZF\ContentNegotiation\ControllerPlugin\ContentNegotiatedViewModel'
        )
    )
);

<?php
return array(
    'zf-content-negotiation' => array(
        'controllers' => array(),
        'selectors' => array(
            'Json' => array(
                'ZF\ContentNegotiation\JsonModel' => array(
                    'application/json',
                ),
            ),
        ),
    ),
    'controller_plugins' => array(
        'invokables' => array(
            'routeParam'                 => 'ZF\ContentNegotiation\ControllerPlugin\RouteParam',
            'queryParam'                 => 'ZF\ContentNegotiation\ControllerPlugin\QueryParam',
            'bodyParam'                  => 'ZF\ContentNegotiation\ControllerPlugin\BodyParam',
            'routeParams'                => 'ZF\ContentNegotiation\ControllerPlugin\RouteParams',
            'queryParams'                => 'ZF\ContentNegotiation\ControllerPlugin\QueryParams',
            'bodyParams'                 => 'ZF\ContentNegotiation\ControllerPlugin\BodyParams',
            'contentNegotiatedViewModel' => 'ZF\ContentNegotiation\ControllerPlugin\ContentNegotiatedViewModel'
        )
    )
);

Add a Json selector by default

Add a Json selector by default

- Creates a Json selector that uses ZF\ContentNegotiation\JsonModel for
  application/json Accept headers.
- Remove commented configuration (no longer relevant)
- Align invokable plugin definitions


<?php
/**
 * @version     $Id$
 * @category	Koowa
 * @package     Koowa_Event
 * @copyright   Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
 * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 * @link        http://www.koowa.org
 */

/**
 * Class to handle events.
 *
 * @author 		Johan Janssens <johan@koowa.org>
 * @category	Koowa
 * @package 	Koowa_Event
 */
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
	/**
	 * Get the object identifier
	 *
	 * @return	KIdentifier
	 * @see 	KObjectIdentifiable
	 */
	public function getIdentifier()
	{
		return $this->_identifier;
	}

	/**
	 * Method to trigger events
	 *
	 * @param  object	The event arguments
	 * @return mixed Routine return value
	 */
	public function update(ArrayObject $args)
	{
		if (in_array($args['event'], $this->getMethods())) {
			return $this->{$args['event']}($args);
		}

		return null;
	}
}

<?php
/**
 * @version     $Id$
 * @category	Koowa
 * @package     Koowa_Event
 * @copyright   Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
 * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 * @link        http://www.koowa.org
 */

/**
 * Class to handle events.
 *
 * @author 		Johan Janssens <johan@koowa.org>
 * @category	Koowa
 * @package 	Koowa_Event
 */
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
	/**
	 * Get the object identifier
	 *
	 * @return	KIdentifier
	 * @see 	KObjectIdentifiable
	 */
	public function getIdentifier()
	{
		return $this->_identifier;
	}

	/**
	 * Method to trigger events
	 *
	 * @param  object	The event arguments
	 * @return mixed Routine return value
	 */
	public function update(KConfig $args)
	{
		if (in_array($args->event, $this->getMethods())) {
			return $this->{$args->event}($args);
		}

		return null;
	}
}

Update method should use KConfig instead of ArrayObject as parameter.


<?php
include 'config.php';

list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2);

$payload = file_get_contents('php://input');

$payloadHash = hash_hmac($algo, $payload, $secret);

if ($hash !== $payloadHash) {
    http_response_code(401);
    echo "Bad secret";
    exit;
}

$data = json_decode($payload, true);

echo "Authenticated properly\nDelivery ID: ".$_SERVER["HTTP_X_GITHUB_DELIVERY"]."\nRepository to deploy: ".$data["repository"]["full_name"]."\n";

echo passthru("/bin/bash ".$_SERVER['DOCUMENT_ROOT']."/pullsimple.sh ".$data["repository"]["name"]." ".$data["repository"]["full_name"]." ".$auth." 2>&1");

if (isset($email_from, $email_to)) {
    mail($email_to, "[".$data["repository"]["full_name"]."] New ".$_SERVER["HTTP_X_GITHUB_EVENT"]." triggered a deployment", ob_get_contents(), "From: ".$email_from);
}

if (file_exists('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php')) {
    include('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php');
}

<?php
include 'config.php';

list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2);

$payload = file_get_contents('php://input');

$payloadHash = hash_hmac($algo, $payload, $secret);

if ($hash !== $payloadHash) {
    http_response_code(401);
    echo "Bad secret";
    exit;
}

$data = json_decode($payload, true);

echo "Authenticated properly\nDelivery ID: ".$_SERVER["HTTP_X_GITHUB_DELIVERY"]."\nRepository to deploy: ".$data["repository"]["full_name"]."\n";

echo passthru("/bin/bash ".__DIR__."/pullsimple.sh ".$data["repository"]["name"]." ".$data["repository"]["full_name"]." ".$auth." 2>&1");

if (isset($email_from, $email_to)) {
    mail($email_to, "[".$data["repository"]["full_name"]."] New ".$_SERVER["HTTP_X_GITHUB_EVENT"]." triggered a deployment", ob_get_contents(), "From: ".$email_from);
}

if (file_exists('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php')) {
    include('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php');
}

Fix shell script reference - note to self add to other hooks


<?php

namespace Lsw\MemcacheBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * EnableSessionSupport is a compiler pass to set the session handler.
 * Based on Emagister\MemcachedBundle by Christian Soronellas
 */
class EnableSessionSupport implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        // If there is no active session support, return
        if (!$container->hasAlias('session.storage')) {
            return;
        }
        // If the memcache.session_handler service is loaded set the alias
        if ($container->hasDefinition('memcache.session_handler')) {
            $container->setAlias('session.handler', 'memcache.session_handler');
        }
    }
}

<?php

namespace Lsw\MemcacheBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * EnableSessionSupport is a compiler pass to set the session handler.
 * Based on Emagister\MemcachedBundle by Christian Soronellas
 */
class EnableSessionSupport implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        // If there is no active session support, return
        if (!$container->hasAlias('session.storage')) {
            return;
        }
        // If the memcache.session_handler service is loaded set the alias
        if ($container->hasDefinition('memcache.session_handler')) {
            if (!$container->hasAlias('session.handler')) {
                $container->setAlias('session.handler', 'memcache.session_handler');
            }
        }
    }
}

Fix for session handler overriding

Fix for session handler overriding

This fixes a bug where setting a session.handler_id in your symfony
configuration didn't work, due to this bundle overriding it.

The setting is now only overridden if the handler_id is not null.


<?php

namespace Omnipay\Buckaroo\Message;

/**
 * Buckaroo iDeal Purchase Request
 */
class SepaDirectDebitPurchaseRequest extends AbstractRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['Brq_payment_method'] = 'sepadirectdebit';

//        if ($this->getIssuer()) {
//            $data['Brq_service_sepa_direct_debit_issuer'] = $this->getIssuer();
//        }

        return $data;
    }
}

<?php

namespace Omnipay\Buckaroo\Message;

/**
 * Buckaroo SEPA Direct Debit Purchase Request
 */
class SepaDirectDebitPurchaseRequest extends AbstractRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['Brq_payment_method'] = 'sepadirectdebit';

        return $data;
    }
}

Remove issuer for SEPADD Update class doc


<?php namespace GeneaLabs\LaravelGovernor\Http\Controllers\Nova;

use GeneaLabs\LaravelGovernor\Http\Controllers\Controller;
use Illuminate\Support\Collection;

class UserController extends Controller
{
    public function __construct()
    {
        //
    }

    public function index() : Collection
    {
        $userClass = config('genealabs-laravel-governor.models.auth');
        return (new $userClass)
            ->get();
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Http\Controllers\Nova;

use GeneaLabs\LaravelGovernor\Http\Controllers\Controller;
use Illuminate\Support\Collection;

class UserController extends Controller
{
    public function __construct()
    {
        // prevent default construct
    }

    public function index() : Collection
    {
        $userClass = config('genealabs-laravel-governor.models.auth');
        return (new $userClass)
            ->get();
    }
}

Clarify use of empty construct method

Clarify use of empty construct method


<?php namespace professionalweb\payment\contracts\recurring;

use professionalweb\payment\contracts\PayService;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param string $accountId
     * @param string $paymentId
     * @param float  $amount
     * @param string $description
     * @param string $currency
     * @param array  $extraParams
     *
     * @return bool
     */
    public function initPayment(string $token, string $accountId, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;

    /**
     * Remember payment fo recurring payments
     *
     * @return RecurringPayment
     */
    public function makeRecurring(): self;

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

<?php namespace professionalweb\payment\contracts\recurring;

use professionalweb\payment\contracts\PayService;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param string $paymentId
     * @param float  $amount
     * @param string $description
     * @param string $currency
     * @param array  $extraParams
     *
     * @return bool
     */
    public function initPayment(string $token, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;

    /**
     * Remember payment fo recurring payments
     *
     * @return RecurringPayment
     */
    public function makeRecurring(): self;

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

Remove account id from method

Remove account id from method


<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Redirect as RedirectModel;
use \BNETDocs\Views\RedirectHtml as RedirectHtmlView;

class Redirect extends Controller {

  protected $redirect_code;
  protected $redirect_to;

  public function __construct($redirect_to, $redirect_code = 302) {
    parent::__construct();
    $this->redirect_code = $redirect_code;
    $this->redirect_to   = $redirect_to;
  }

  public function run(Router &$router) {
    switch ($router->getRequestPathExtension()) {
      case "htm": case "html": case "":
        $view = new RedirectHtmlView();
      break;
      default:
        throw new UnspecifiedViewException();
    }
    $model = new RedirectModel($this->redirect_code, $this->redirect_to);
    ob_start();
    $view->render($model);
    $router->setResponseCode($this->redirect_code);
    $router->setResponseTTL(0);
    $router->setResponseHeader("Content-Type", $view->getMimeType());
    $router->setResponseHeader("Location", $this->redirect_to);
    $router->setResponseContent(ob_get_contents());
    ob_end_clean();
  }

}

<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Redirect as RedirectModel;
use \BNETDocs\Views\RedirectHtml as RedirectHtmlView;

class Redirect extends Controller {

  protected $redirect_code;
  protected $redirect_to;

  public function __construct($redirect_to, $redirect_code = 302) {
    parent::__construct();
    $this->redirect_code = $redirect_code;
    $this->redirect_to   = $redirect_to;
  }

  public function run(Router &$router) {
    $view = new RedirectHtmlView();
    $model = new RedirectModel($this->redirect_code, $this->redirect_to);
    ob_start();
    $view->render($model);
    $router->setResponseCode($this->redirect_code);
    $router->setResponseTTL(0);
    $router->setResponseHeader("Content-Type", $view->getMimeType());
    $router->setResponseHeader("Location", $this->redirect_to);
    $router->setResponseContent(ob_get_contents());
    ob_end_clean();
  }

}

Fix redirect controller having no view available


<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_comments-stat_include.php
| Author: Digitanium
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }

if ($profile_method == "input") {
	//Nothing here
} elseif ($profile_method == "display") {
	echo "
\n";
	echo "".$locale['uf_comments-stat']."	\n";
	echo "".number_format(dbcount("(comment_id)", DB_COMMENTS, "comment_name='".$user_data['user_id']."'"))."	\n";
	echo "
\n";
} elseif ($profile_method == "validate_insert") {
	//Nothing here
} elseif ($profile_method == "validate_update") {
	//Nothing here
}
?>

<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_comments-stat_include.php
| Author: PHP-Fusion Development Team
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }

if ($profile_method == "input") {
	$user_fields = '';
	if (defined('ADMIN_PANEL')) {
	$user_fields = "
".$locale['uf_comments-stat']."
";
	}
} elseif ($profile_method == "display") {
	$user_fields = array('title'=>$locale['uf_comments-stat'], 'value'=>number_format(dbcount("(comment_id)", DB_COMMENTS, "comment_name='".$user_data['user_id']."'"))."");
} elseif ($profile_method == "validate_insert") {
	//Nothing here
} elseif ($profile_method == "validate_update") {
	//Nothing here
}
?>

Convert comment stats to new UF

Convert comment stats to new UF

Convert comment stats to new UF


<?php

//Global configuration
define('CS_CONSUMER_KEY', '');
define('CS_CONSUMER_SECRET', '');
define('CS_RETURN_PATH', 'http://cs.local/connect.php?response=true');

Add example return path to config and use constant