<?php

namespace Concrete\Core\Page;

class DisplayOrderUpdateEvent extends Event
{
    /**
     * Get the old display order
     *
     * This is the order *before* the page was moved.
     *
     * @return int
     */
    public function getOldDisplayOrder()
    {
        return (int) $this->getArgument('oldDisplayOrder');
    }

    /**
     * Get the new display order
     *
     * This is the order *after* the page was moved.
     *
     * @return int
     */
    public function getNewDisplayOrder()
    {
        return (int) $this->getArgument('newDisplayOrder');
    }

    /**
     * @param int $displayOrder
     */
    public function setOldDisplayOrder($displayOrder)
    {
        $this->setArgument('oldDisplayOrder', (int) $displayOrder);
    }

    /**
     * @param int $displayOrder
     */
    public function setNewDisplayOrder($displayOrder)
    {
        $this->setArgument('newDisplayOrder', (int) $displayOrder);
    }
}

<?php

namespace Concrete\Core\Page;

/**
 * @since 8.5.0
 */
class DisplayOrderUpdateEvent extends Event
{
    /**
     * Get the old display order
     *
     * This is the order *before* the page was moved.
     *
     * @return int
     */
    public function getOldDisplayOrder()
    {
        return (int) $this->getArgument('oldDisplayOrder');
    }

    /**
     * Get the new display order
     *
     * This is the order *after* the page was moved.
     *
     * @return int
     */
    public function getNewDisplayOrder()
    {
        return (int) $this->getArgument('newDisplayOrder');
    }

    /**
     * @param int $displayOrder
     */
    public function setOldDisplayOrder($displayOrder)
    {
        $this->setArgument('oldDisplayOrder', (int) $displayOrder);
    }

    /**
     * @param int $displayOrder
     */
    public function setNewDisplayOrder($displayOrder)
    {
        $this->setArgument('newDisplayOrder', (int) $displayOrder);
    }
}

Add docblock about when this event was introduced


<?php

/**
 * An abstract source to bulk load records from.
 * Provides an iterator for retrieving records from.
 *
 * Useful for holiding source configuration state.
 */
abstract class BulkLoaderSource implements IteratorAggregate{

	/**
	 * Provide iterator for bulk loading from.
	 * Records are expected to be 1 dimensional key-value arrays.
	 * @return Iterator
	 */
	abstract public function getIterator();

}

<?php

if (version_compare(PHP_VERSION, '5.4.0', '<')) {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

	}

} else {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

		/**
		 * Provide iterator for bulk loading from.
		 * Records are expected to be 1 dimensional key-value arrays.
		 * @return Iterator
		 */
		abstract public function getIterator();

	}

}

Fix issue with php version 5.3.3

Fix issue with php version 5.3.3


<?php
/**
 * phpDocumentor
 *
 * PHP Version 5.3
 *
 * @copyright 2010-2013 Mike van Riel / Naenius (http://www.naenius.com)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://phpdoc.org
 */

namespace phpDocumentor\Descriptor;

use \Mockery as m;

/**
 * Tests the functionality for the FunctionDescriptor class.
 */
class FunctionDescriptorTest extends \PHPUnit_Framework_TestCase
{
    /** @var FunctionDescriptor $fixture */
    protected $fixture;

    /**
     * Creates a new (emoty) fixture object.
     */
    protected function setUp()
    {
        $this->fixture = new FunctionDescriptor();
    }

    /**
     * Tests whether all collection objects are properly initialized.
     *
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::__construct
     */
    public function testInitialize()
    {
        $this->assertAttributeInstanceOf('phpDocumentor\Descriptor\Collection', 'arguments', $this->fixture);
    }

    /**
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::setArguments
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::getArguments
     */
    public function testSettingAndGettingArguments()
    {
        $this->assertInstanceOf('phpDocumentor\Descriptor\Collection', $this->fixture->getArguments());

        $mock = &m::mock('phpDocumentor\Descriptor\Collection');

        $this->fixture->setArguments($mock);

        $this->assertSame($mock, $this->fixture->getArguments());
    }
}

<?php
/**
 * phpDocumentor
 *
 * PHP Version 5.3
 *
 * @copyright 2010-2013 Mike van Riel / Naenius (http://www.naenius.com)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://phpdoc.org
 */

namespace phpDocumentor\Descriptor;

use \Mockery as m;

/**
 * Tests the functionality for the FunctionDescriptor class.
 */
class FunctionDescriptorTest extends \PHPUnit_Framework_TestCase
{
    /** @var FunctionDescriptor $fixture */
    protected $fixture;

    /**
     * Creates a new (emoty) fixture object.
     */
    protected function setUp()
    {
        $this->fixture = new FunctionDescriptor();
    }

    /**
     * Tests whether all collection objects are properly initialized.
     *
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::__construct
     */
    public function testInitialize()
    {
        $this->assertAttributeInstanceOf('phpDocumentor\Descriptor\Collection', 'arguments', $this->fixture);
    }

    /**
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::setArguments
     * @covers phpDocumentor\Descriptor\FunctionDescriptor::getArguments
     */
    public function testSettingAndGettingArguments()
    {
        $this->assertInstanceOf('phpDocumentor\Descriptor\Collection', $this->fixture->getArguments());

        $mockInstance = m::mock('phpDocumentor\Descriptor\Collection');
        $mock = &$mockInstance;

        $this->fixture->setArguments($mock);

        $this->assertSame($mockInstance, $this->fixture->getArguments());
    }
}

Fix error in unit test

Fix error in unit test


<?php
/**
 * Roger Dickey, Jr
 * http://rogerdickeyjr.com/
 * http://github.com/rogerd330/
 * 11/15/12 9:59 PM
 */

require_once("includes/functions.php");

$site_name = "Site Shell";
$page_title = empty($page_title) ? "Home" : $page_title;
list($page_name, $page_extension) = explode(".", basename($_SERVER["PHP_SELF"]));

?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title><?php echo sprintf("%s - %s", $page_title, $site_name) ?></title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <!--[if lt IE 9]>
        <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <link rel="stylesheet" href="css/reset.css" />
        <link rel="stylesheet" href="css/text.css">
        <link rel="stylesheet" href="css/960.css" />
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>

    <div id="<?php echo $page_name ?>" class="container_12">

<?php
/**
 * Roger Dickey, Jr
 * http://rogerdickeyjr.com/
 * http://github.com/rogerd330/
 * 11/15/12 9:59 PM
 */

require_once("includes/functions.php");

$site_name = "Site Shell";
$page_title = empty($page_title) ? "Home" : $page_title;
list($page_name, $page_extension) = explode(".", basename($_SERVER["PHP_SELF"]));

?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title><?php echo sprintf("%s - %s", $page_title, $site_name) ?></title>
        <link href="favicon.ico" type="image/x-icon" rel="icon" />
        <link href="favicon.ico" type="image/x-icon" rel="shortcut icon" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <!--[if lt IE 9]>
        <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <link rel="stylesheet" href="css/reset.css" />
        <link rel="stylesheet" href="css/text.css">
        <link rel="stylesheet" href="css/960.css" />
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>

    <div id="<?php echo $page_name ?>" class="container_12">

Include meta tags for favicon support.

Include meta tags for favicon support.


<?php require('../header-navbar.php'); ?>

About me

I'm Rob Dimsdale, a software developer currently based near Boulder, CO, where I work for Oracle in the Tape Storage division (yes that business is still going and is in fact quite healthy). Prior to moving to the US I worked for Softwire in London, UK.

Whilst my primary focus to date has been Java web applications with a decent dose of systems-administration, I'm interested in all sorts of languages and frameworks. At the low-level I've worked on embedded C projects and hardware and at the opposite end I'm working on projects using scripting languages including Python and MATLAB.

For more details, see my resume

<?php require('../buttons.php'); ?>

<?php require('../footer.php'); ?>

Add links on 'about me' to Oracle and Tape Storage.


<?php while (have_posts()) : the_post() ?>
  <article <?php post_class() ?>>

      <?php share_icons(get_the_ID()) ?>

<?php the_title() ?>

      <?php get_template_part('templates/entry-meta') ?>

      <?php the_content() ?>

        By: <?php gds_byline(); ?>
          Category: <?php echo get_the_category_list(', ') ?>

        <?php echo get_the_tag_list('
Tags: ', ',', '
'); ?>

    <?php comments_template('/templates/comments.php') ?>

<?php endwhile ?>

<?php while (have_posts()) : the_post() ?>
  <article <?php post_class() ?>>

<?php the_title() ?>

      <?php get_template_part('templates/entry-meta') ?>

      <?php the_content() ?>

        By: <?php gds_byline(); ?>
          Category: <?php echo get_the_category_list(', ') ?>

        <?php echo get_the_tag_list('
Tags: ', ',', '
'); ?>

    <?php share_icons(get_the_ID()) ?>
    <?php comments_template('/templates/comments.php') ?>

<?php endwhile ?>

Move share_icons to the bottom of the page


<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class MicropubClientTest extends DuskTestCase
{
    /**
     * Test the client is shown for an unauthorised request.
     *
     * @return void
     */
    public function test_client_page_see_authenticated()
    {
        $this->browse(function ($browser) {
            $browser->visit(route('micropub-client'))
                    ->assertSee('You are authenticated');
        });
    }

    public function test_client_page_creates_new_note()
    {
        $faker = \Faker\Factory::create();
        $note = 'Fake note from #LaravelDusk: ' . $faker->text;
        $this->browse(function ($browser) use ($note) {
            $browser->visit(route('micropub-client'))
                    ->type('content', $note)
                    ->press('Submit');
        });
        $this->assertDatabaseHas('notes', ['note' => $note]);
        $newNote = \App\Note::where('note', $note)->first();
        $newNote->forceDelete();
    }

    public function test_client_page_updates_syndication()
    {
        $this->browse(function ($browser) {
            $browser->visit(route('micropub-client'))
                    ->assertDontSee('jonnybarnes on Twitter')
                    ->clickLink('Refresh Syndication Targets')
                    ->pause(5000)
                    ->assertSee('jonnybarnes on Twitter');
        });
    }
}

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class MicropubClientTest extends DuskTestCase
{
    /**
     * Test the client is shown for an unauthorised request.
     *
     * @return void
     */
    public function test_client_page_see_authenticated()
    {
        $this->browse(function ($browser) {
            $browser->visit(route('micropub-client'))
                    ->assertSee('You are authenticated');
        });
    }

    public function test_client_page_creates_new_note()
    {
        $faker = \Faker\Factory::create();
        $note = 'Fake note from #LaravelDusk: ' . $faker->text;
        $this->browse(function ($browser) use ($note) {
            $browser->visit(route('micropub-client'))
                    ->type('content', $note)
                    ->press('Submit');
        });
        $this->assertDatabaseHas('notes', ['note' => $note]);
        $newNote = \App\Note::where('note', $note)->first();
        $newNote->forceDelete();
    }
}

Remove test associated with removed functionality


<?php
/**
 * Which method in which MVC set will be executed
 * for each defined action in this array.
 */
$actions = array(
    'index' => \Ragnaroq\App\Runner::mvcAction('home', 'index'),
    'welcome' => \Ragnaroq\App\Runner::mvcAction('example', 'greet'),
);

/**
 * Which of the previously defined actions will
 * be executed in each route.
 */
$routes = array(
    'GET' => array(
        'homepage' => $actions['index'],
        'example' => $actions['welcome'],
    ),
    'POST' => array(

    ),
    'DELETE' => array(

    ),
    'PUT' => array(

    ),
    'OPTIONS' => array(

    ),
);

return $routes;

<?php
/**
 * Which method in which MVC set will be executed
 * for each defined action in this array.
 */
$actions = array(
    'index' => \Ragnaroq\App\Runner::mvcAction('home', 'index'),
    'welcome' => \Ragnaroq\App\Runner::mvcAction('example', 'greet'),
    'authorize' => \Ragnaroq\App\Runner::mvcAction('oauth2', 'authorizeCallback'),
);

/**
 * Which of the previously defined actions will
 * be executed in each route.
 */
$routes = array(
    'GET' => array(
        'homepage' => $actions['index'],
        'example' => $actions['welcome'],
        'authorize_callback' => $actions['authorize'],
    ),
    'POST' => array(

    ),
    'DELETE' => array(

    ),
    'PUT' => array(

    ),
    'OPTIONS' => array(

    ),
);

return $routes;

Add route for OAuth2 callback

Add route for OAuth2 callback


<?php

namespace Yajra\Auditable;

/**
 * Class AuditableObserver
 *
 * @package Yajra\Auditable
 */
class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param \Yajra\Auditable\AuditableTrait $model
     */
    public function creating($model)
    {
        if (! $model->created_by) {
            $model->created_by = $this->getAuthenticatedUserId();
        }

        if (! $model->updated_by) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : 0;
    }

    /**
     * Model's updating event hook.
     *
     * @param \Yajra\Auditable\AuditableTrait $model
     */
    public function updating($model)
    {
        if (! $model->updated_by) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }
}

<?php

namespace Yajra\Auditable;

/**
 * Class AuditableObserver
 *
 * @package Yajra\Auditable
 */
class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param \Yajra\Auditable\AuditableTrait $model
     */
    public function creating($model)
    {
        if (! $model->created_by) {
            $model->created_by = $this->getAuthenticatedUserId();
        }

        if (! $model->updated_by) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : 0;
    }

    /**
     * Model's updating event hook.
     *
     * @param \Yajra\Auditable\AuditableTrait $model
     */
    public function updating($model)
    {
        if (! $model->isDirty('updated_by')) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }
}

Fix setting of updated_by value column when updating.


<?php

use Illuminate\Database\Seeder;
use Bdgt\Resources\User;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i = 0; $i < 30; $i++) {
            User::create([
                'id' => null,
                'username' => $faker->userName(),
                'email' => $faker->email(),
                'password' => $faker->md5()
            ]);
        }
    }
}

<?php

use Illuminate\Database\Seeder;
use Bdgt\Resources\User;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        User::create([
            'id' => null,
            'username' => "admin",
            'email' => "admin@example.com",
            'password' => Hash::make("admin")
        ]);

        for ($i = 0; $i < 29; $i++) {
            User::create([
                'id' => null,
                'username' => $faker->userName(),
                'email' => $faker->email(),
                'password' => $faker->md5()
            ]);
        }
    }
}

Add dummy user with known credentials, some of the seed objects will be randomly assigned to it


<?php

return [
    'hostname' => '',
    'database' => '',
    'username' => '',
    'password' => '',
];

<?php

return [
    'development'   => 'mysql://username:password@hostname/database',
    'test'          => 'mysql://username:password@hostname/database',
    'acceptance'    => 'mysql://username:password@hostname/database',
    'production'    => 'mysql://username:password@hostname/database'
];

Update for use with PHP-Activerecord

Update for use with PHP-Activerecord


<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

Fix contrat-status issues - Date : 21/11/2016


<?php

namespace spec\FergusInLondon\Events;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class RegistrySpec extends ObjectBehavior
{
    function it_is_initializable()
    {
		$this->shouldHaveType('FergusInLondon\Events\Registry');
    }

	function can_accept_handler()
	{

	}

	function trigger_should_execute_callable()
	{

	}

	function trigger_should_pass_paramters_to_handler()
	{

	}

	function can_clear_all_handlers()
	{

	}

	function can_clear_individual_handlers()
	{

	}
}

<?php

namespace spec\FergusInLondon\Events;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class RegistrySpec extends ObjectBehavior
{
    function it_is_initializable()
    {
		$this->shouldHaveType('FergusInLondon\Events\Registry');
    }

	function it_can_accept_handler($handler)
	{
		$this->callOnWrappedObject('associateRegistry', [$registry, 'eve_0']);

	}

	function it_should_execute_callable_upon_trigger($handler)	{
		$handler->beADoubleOf('FergusInLondon\Events\Handler');
	}

	function it_should_pass_parameters_to_handler($handler)
	{

	}

	function it_should_execute_correct_handlers($eventAHandler, $eventBHandler)
	{

	}

	function it_can_clear_all_handlers($eventAHandler, $eventBHandler)
	{

	}

	function it_can_clear_individual_handlers($eventAHandler, $eventBHandler)
	{

	}
}

Introduce testing for Handler object

Introduce testing for Handler object


<?php
namespace Psalm\Report;

use LSS\Array2XML;
use Psalm\Internal\Analyzer\DataFlowNodeData;
use Psalm\Internal\Analyzer\IssueData;
use Psalm\Report;

use function array_map;

class XmlReport extends Report
{
    public function create(): string
    {
        $xml = Array2XML::createXML(
            'report',
            [
                'item' => array_map(
                    function (IssueData $issue_data): array {
                        $issue_data = (array) $issue_data;
                        unset($issue_data['dupe_key']);

                        if (null !== $issue_data['taint_trace']) {
                            $issue_data['taint_trace'] = array_map(
                                function ($trace): array {
                                    return (array) $trace;
                                },
                                $issue_data['taint_trace']
                            );
                        }

                        if (null !== $issue_data['other_references']) {
                            $issue_data['other_references'] = array_map(
                                function (DataFlowNodeData $reference): array {
                                    return (array) $reference;
                                },
                                $issue_data['other_references']
                            );
                        }

                        return $issue_data;
                    },
                    $this->issues_data
                )
            ]
        );

        return $xml->saveXML();
    }
}

<?php
namespace Psalm\Report;

use LSS\Array2XML;
use Psalm\Internal\Analyzer\DataFlowNodeData;
use Psalm\Internal\Analyzer\IssueData;
use Psalm\Report;

use function array_map;
use function get_object_vars;

class XmlReport extends Report
{
    public function create(): string
    {
        $xml = Array2XML::createXML(
            'report',
            [
                'item' => array_map(
                    function (IssueData $issue_data): array {
                        $issue_data = get_object_vars($issue_data);
                        unset($issue_data['dupe_key']);

                        if (null !== $issue_data['taint_trace']) {
                            $issue_data['taint_trace'] = array_map(
                                function ($trace): array {
                                    return (array) $trace;
                                },
                                $issue_data['taint_trace']
                            );
                        }

                        if (null !== $issue_data['other_references']) {
                            $issue_data['other_references'] = array_map(
                                function (DataFlowNodeData $reference): array {
                                    return (array) $reference;
                                },
                                $issue_data['other_references']
                            );
                        }

                        return $issue_data;
                    },
                    $this->issues_data
                )
            ]
        );

        return $xml->saveXML();
    }
}

Replace array cast with get_object_vars() which Psalm understands


<?php

namespace Lmc\Steward\Test;

use Nette\Utils\Strings;

/**
 * Listener to take screenshot on each error or failure
 */
class ErrorScreenshotListener extends \PHPUnit_Framework_BaseTestListener
{
    public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
        $this->takeScreenshot($test, $e, $time);
    }

    public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time)
    {
        $this->takeScreenshot($test, $e, $time);
    }

    /**
     * Take screenshot and save it
     * @param PHPUnit_Framework_Test|LmcTestCase $test
     * @param Exception $e
     * @param $time
     */
    private function takeScreenshot(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }
        $test->log('Taking screenshot because: ' . $e->getMessage());
        if (!$test->wd instanceof \RemoteWebDriver) {
            $test->log("No webdriver, no screenshot.");
        }
        $test->wd->takeScreenshot(
            __DIR__ . '/../../logs/'
            . Strings::webalize(get_class($test))
            . '-'
            . Strings::webalize($test->getName())
            . '-'
            . time()
            . '.png'
        );
    }
}

<?php

namespace Lmc\Steward\Test;

use Nette\Utils\Strings;

/**
 * Listener to take screenshot on each error or failure
 */
class ErrorScreenshotListener extends \PHPUnit_Framework_BaseTestListener
{
    public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
        $this->takeScreenshot($test, $e, $time);
    }

    public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time)
    {
        $this->takeScreenshot($test, $e, $time);
    }

    /**
     * Take screenshot and save it
     * @param PHPUnit_Framework_Test|LmcTestCase $test
     * @param Exception $e
     * @param $time
     */
    private function takeScreenshot(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
        if (!$test instanceof AbstractTestCase) {
            throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase');
        }
        $test->log('Taking screenshot because: ' . $e->getMessage());
        if (!$test->wd instanceof \RemoteWebDriver) {
            $test->log("No webdriver, no screenshot.");
        }

        $test->wd->takeScreenshot(
            __DIR__ . '/../../logs/'
            . Strings::webalize(get_class($test))
            . '-'
            . Strings::webalize($test->getName())
            . '-'
            . date('Y-m-d-H-i-s')
            . '.png'
        );
    }
}

Use time inestad of unix timestamp in screenshot file name


<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property integer $frequency
 * @property string $name
 */
class Tags extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tags';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'frequency', 'name'], 'required'],
            [['id', 'frequency'], 'integer'],
            [['name'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'frequency' => 'Frequency',
            'name' => 'Name',
        ];
    }
}

<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property integer $frequency
 * @property string $name
 */
class Tags extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tags';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['frequency', 'name'], 'required'], //id removed, new tags are not saved when it is required
            [['id', 'frequency'], 'integer'],
            [['name'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'frequency' => 'Frequency',
            'name' => 'Name',
        ];
    }
}

Remove id from required attributes, now new tags are saved


<?php

final class PhabricatorRobotsController extends PhabricatorController {

  public function shouldRequireLogin() {
    return false;
  }

  public function processRequest() {
    $out = array();

    // Prevent indexing of '/diffusion/', since the content is not generally
    // useful to index, web spiders get stuck scraping the history of every
    // file, and much of the content is Ajaxed in anyway so spiders won't even
    // see it. These pages are also relatively expensive to generate.

    // Note that this still allows commits (at '/rPxxxxx') to be indexed.
    // They're probably not hugely useful, but suffer fewer of the problems
    // Diffusion suffers and are hard to omit with 'robots.txt'.

    $out[] = 'User-Agent: *';
    $out[] = 'Disallow: /diffusion/';

    // Add a small crawl delay (number of seconds between requests) for spiders
    // which respect it. The intent here is to prevent spiders from affecting
    // performance for users. The possible cost is slower indexing, but that
    // seems like a reasonable tradeoff, since most Phabricator installs are
    // probably not hugely concerned about cutting-edge SEO.
    $out[] = 'Crawl-delay: 1';

    $content = implode("\n", $out)."\n";

    return id(new AphrontPlainTextResponse())
      ->setContent($content)
      ->setCacheDurationInSeconds(phutil_units('2 hours in seconds'));
  }
}

<?php

final class PhabricatorRobotsController extends PhabricatorController {

  public function shouldRequireLogin() {
    return false;
  }

  public function processRequest() {
    $out = array();

    // Prevent indexing of '/diffusion/', since the content is not generally
    // useful to index, web spiders get stuck scraping the history of every
    // file, and much of the content is Ajaxed in anyway so spiders won't even
    // see it. These pages are also relatively expensive to generate.

    // Note that this still allows commits (at '/rPxxxxx') to be indexed.
    // They're probably not hugely useful, but suffer fewer of the problems
    // Diffusion suffers and are hard to omit with 'robots.txt'.

    $out[] = 'User-Agent: *';
    $out[] = 'Disallow: /diffusion/';
    $out[] = 'Disallow: /multimeter/';

    // Add a small crawl delay (number of seconds between requests) for spiders
    // which respect it. The intent here is to prevent spiders from affecting
    // performance for users. The possible cost is slower indexing, but that
    // seems like a reasonable tradeoff, since most Phabricator installs are
    // probably not hugely concerned about cutting-edge SEO.
    $out[] = 'Crawl-delay: 1';

    $content = implode("\n", $out)."\n";

    return id(new AphrontPlainTextResponse())
      ->setContent($content)
      ->setCacheDurationInSeconds(phutil_units('2 hours in seconds'));
  }
}

Add /multimeter/ to robots.txt exclusion

We don't need search engines indexing /multimeter, it's unwanted load
and not at all useful. (It's also filling up the logs, currently)

Bug: T109247
Change-Id: I8d991f52b59219501982366738dfaab4ff6e7b43


<?php

namespace Oro\Bundle\ConfigBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\Config\Definition\Processor;

class ConfigPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $processor = new Processor();
        $settings  = array();

        foreach ($container->getExtensions() as $name => $extension) {
            if (!$config = $extension->getConfiguration(array(), $container)) {
                continue;
            }

            $config = $processor->processConfiguration(
                $config,
                $container->getExtensionConfig($name)
            );

            if (isset($config['settings'])) {
                $settings[$name] = $config['settings'];
            }
        }

        $taggedServices = $container->findTaggedServiceIds('oro_config.manager');

        foreach ($taggedServices as $id => $attributes) {
            $container
                ->getDefinition($id)
                ->addArgument($settings);
        }
    }
}

<?php

namespace Oro\Bundle\ConfigBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\Config\Definition\Processor;

class ConfigPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $processor = new Processor();
        $settings  = array();

        foreach ($container->getExtensions() as $name => $extension) {
            if (strpos($name, 'oro_') !== false) {
                if (!$config = $extension->getConfiguration(array(), $container)) {
                    continue;
                }

                $config = $processor->processConfiguration(
                    $config,
                    $container->getExtensionConfig($name)
                );

                if (isset($config['settings'])) {
                    $settings[$name] = $config['settings'];
                }
            }
        }

        $taggedServices = $container->findTaggedServiceIds('oro_config.manager');

        foreach ($taggedServices as $id => $attributes) {
            $container
                ->getDefinition($id)
                ->addArgument($settings);
        }
    }
}

Revert "BAP-2304: OroConfig work only for tree named by prefix "oro_""

This reverts commit dcd96f4de80928ed77db380de20bc0d02a45ed17.


<?php

return function (CM_Config_Node $config) {

    $awsBucket = '<%= @aws_bucket %>';
    $awsRegion = '<%= @aws_region %>';
    $awsKey = '<%= @aws_key %>';
    $awsSecret = '<%= @aws_secret %>';

    $config->services['s3export-filesystem-original'] = array(
        'class'  => 'CM_File_Filesystem_Factory',
        'method' => array(
            'name'      => 'createFilesystem',
            'arguments' => array(
                'CM_File_Filesystem_Adapter_AwsS3',
                array(
                    'bucket' => $awsBucket,
                    'region' => $awsRegion,
                    'key'    => $awsKey,
                    'secret' => $awsSecret,
                ),
            ),
        ));

    $config->services['s3export-backup-manager'] = [
        'class'     => 'S3Export_BackupManager',
        'arguments' => [
            [
                'key'    => $awsKey,
                'secret' => $awsSecret,
            ]
        ]
    ];
};

<?php

return function (CM_Config_Node $config) {

    $awsBucket = '<%= @aws_bucket %>';
    $awsRegion = '<%= @aws_region %>';
    $awsKey = '<%= @aws_key %>';
    $awsSecret = '<%= @aws_secret %>';

    $config->services['s3export-filesystem-original'] = array(
        'class'  => 'CM_File_Filesystem_Factory',
        'method' => array(
            'name'      => 'createFilesystem',
            'arguments' => array(
                'CM_File_Filesystem_Adapter_AwsS3',
                array(
                    'bucket' => $awsBucket,
                    'region' => $awsRegion,
                    'key'    => $awsKey,
                    'secret' => $awsSecret,
                ),
            ),
        ));

    $config->services['s3export-backup-manager'] = [
        'class'     => 'S3Export_BackupManager',
        'arguments' => [
            [
                'bucket' => $awsBucket,
                'key'    => $awsKey,
                'secret' => $awsSecret,
            ]
        ]
    ];
};

Add missing bucket for local fs

Add missing bucket for local fs


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Login Logo
    |--------------------------------------------------------------------------
    |
    | Replace the default login logo with clients logo or name will give your
    | custom built theme an extra touch.
    |
    | Define the width of your custom login logo in pixels.
    |
    */

    'image_path' => '/assets/images/logo.png',
    'image_width' =>  80,

    /*
    |--------------------------------------------------------------------------
    | Login Error Message
    |--------------------------------------------------------------------------
    |
    | It is good practice to replace the login error message for security
    | reasons. We don't wanna give unwanted guests any feedback except that
    | he/she can't login without the right credentials.
    |
    */

    'error_message' => 'Whoops! Looks like you missed something there. Have another go.',

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Login Logo
    |--------------------------------------------------------------------------
    |
    | Replace the default login logo with clients logo or name will give your
    | custom built theme an extra touch.
    |
    | Define the width of your custom login logo in pixels.
    |
    */

    'image' => [
        'path' => '/assets/images/logo.png',

        'width' => 200,
    ],

    /*
    |--------------------------------------------------------------------------
    | Login Error Message
    |--------------------------------------------------------------------------
    |
    | It is good practice to replace the login error message for security
    | reasons. We don't wanna give unwanted guests any feedback except that
    | he/she can't login without the right credentials.
    |
    */

    'error_message' => 'Whoops! Looks like you missed something there. Have another go.',

];

Make image_path and image_width into an array


<?php

require_once '../vendor/restler.php';

use Luracast\Restler\Restler;

$r = new Restler();
$r->addAPIClass('Highway');
$r->handle();

<?php

require_once '../vendor/restler.php';

use Luracast\Restler\Restler;

$r = new Restler();  // Pass "true" to this to put Restler into production mode
$r->addAPIClass('Highway');
$r->addAPIClass('Resources'); //this creates resources.json at API Root
$r->handle();

Add comments and resources for explorer

Add comments and resources for explorer


<?php

namespace OpenConext\EngineBlock\Logger\Formatter;

use EngineBlock_Exception;
use Monolog\Formatter\FormatterInterface;
use OpenConext\EngineBlock\Logger\Message\AdditionalInfo;

final class AdditionalInfoFormatter implements FormatterInterface
{
    /**
     * @var FormatterInterface
     */
    private $formatter;

    public function __construct(FormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    public function format(array $record)
    {
        return $this->formatter->format($this->addAdditionalInfoForEngineBlockExceptions($record));
    }

    public function formatBatch(array $records)
    {
        $self = $this;
        array_walk($records, function (&$value) use ($self) {
            $value = $self->addAdditionalInfoForEngineBlockExceptions($value);
        });

        return $this->formatter->formatBatch($records);
    }

    /**
     * @param array $record
     * @return array
     */
    private function addAdditionalInfoForEngineBlockExceptions(array $record)
    {
        if (!isset($record['context']['exception'])) {
            return $record;
        }

        $exception = $record['context']['exception'];
        if (!$exception instanceof EngineBlock_Exception) {
            return $record;
        }

        $record['context']['exception'] = AdditionalInfo::createFromException($exception)->toArray();

        return $record;
    }
}

<?php

namespace OpenConext\EngineBlock\Logger\Formatter;

use EngineBlock_Exception;
use Monolog\Formatter\FormatterInterface;
use OpenConext\EngineBlock\Logger\Message\AdditionalInfo;

final class AdditionalInfoFormatter implements FormatterInterface
{
    /**
     * @var FormatterInterface
     */
    private $formatter;

    public function __construct(FormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    public function format(array $record)
    {
        return $this->formatter->format($this->addAdditionalInfoForEngineBlockExceptions($record));
    }

    public function formatBatch(array $records)
    {
        foreach ($records as &$value) {
            $value = $this->addAdditionalInfoForEngineBlockExceptions($value);
        };

        return $this->formatter->formatBatch($records);
    }

    /**
     * @param array $record
     * @return array
     */
    private function addAdditionalInfoForEngineBlockExceptions(array $record)
    {
        if (!isset($record['context']['exception'])) {
            return $record;
        }

        $exception = $record['context']['exception'];
        if (!$exception instanceof EngineBlock_Exception) {
            return $record;
        }

        $record['context']['exception'] = AdditionalInfo::createFromException($exception)->toArray();

        return $record;
    }
}

Revert array_walk to foreach for php 5.3 compat


<?php

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

namespace Sculpin\Bundle\MarkdownBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Configuration.
 *
 * @author Beau Simensen <beau@dflydev.com>
 */
class Configuration implements ConfigurationInterface
{
    /**
    * {@inheritdoc}
    */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder;

        $rootNode = $treeBuilder->root('sculpin_markdown');

        $rootNode
            ->children()
                ->scalarNode('parser_class')->defaultValue('Sculpin\Bundle\MarkdownBundle\PhpMarkdownExtraParser')->end()
                ->arrayNode('extensions')
                    ->defaultValue(array('md', 'mdown', 'markdown'))
                    ->prototype('scalar')->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

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

namespace Sculpin\Bundle\MarkdownBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Configuration.
 *
 * @author Beau Simensen <beau@dflydev.com>
 */
class Configuration implements ConfigurationInterface
{
    /**
    * {@inheritdoc}
    */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder;

        $rootNode = $treeBuilder->root('sculpin_markdown');

        $rootNode
            ->children()
                ->scalarNode('parser_class')->defaultValue('Sculpin\Bundle\MarkdownBundle\PhpMarkdownExtraParser')->end()
                ->arrayNode('extensions')
                    ->defaultValue(array('md', 'mdown', 'mkdn', 'markdown'))
                    ->prototype('scalar')->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Add mkdn extension to markdown extension list

mkdn is an acceptable extension as per
https://github.com/github/markup/tree/master#markups


<?php
/**
 * @package plugins.bpmEventNotificationIntegration
 * @subpackage lib.events
 */
class kBpmEventNotificationIntegrationFlowManager implements kBatchJobStatusEventConsumer
{
	/* (non-PHPdoc)
	 * @see kBatchJobStatusEventConsumer::updatedJob()
	 */
	public function updatedJob(BatchJob $dbBatchJob)
	{
		$data = $dbBatchJob->getData();
		/* @var $data kIntegrationJobData */

		$triggerData = $data->getTriggerData();
		/* @var $triggerData kBpmEventNotificationIntegrationJobTriggerData */

		$template = EventNotificationTemplatePeer::retrieveByPK($triggerData->getTemplateId());
		/* @var $template BusinessProcessNotificationTemplate */

		$template->setCaseId($dbBatchJob, $triggerData->getCaseId());
	}

	/* (non-PHPdoc)
	 * @see kBatchJobStatusEventConsumer::shouldConsumeJobStatusEvent()
	 */
	public function shouldConsumeJobStatusEvent(BatchJob $dbBatchJob)
	{
		if(		$dbBatchJob->getJobType() == IntegrationPlugin::getBatchJobTypeCoreValue(IntegrationBatchJobType::INTEGRATION)
			&&	$dbBatchJob->getStatus() == KalturaBatchJobStatus::BATCHJOB_STATUS_DONT_PROCESS
			&&	$dbBatchJob->getData()->getTriggerType() == BpmEventNotificationIntegrationPlugin::getIntegrationTriggerCoreValue(BpmEventNotificationIntegrationTrigger::BPM_EVENT_NOTIFICATION)
		)
		{
			return true;
		}

		return false;
	}

}

<?php
/**
 * @package plugins.bpmEventNotificationIntegration
 * @subpackage lib.events
 */
class kBpmEventNotificationIntegrationFlowManager implements kBatchJobStatusEventConsumer
{
	/* (non-PHPdoc)
	 * @see kBatchJobStatusEventConsumer::updatedJob()
	 */
	public function updatedJob(BatchJob $dbBatchJob)
	{
		$data = $dbBatchJob->getData();
		/* @var $data kIntegrationJobData */

		$triggerData = $data->getTriggerData();
		/* @var $triggerData kBpmEventNotificationIntegrationJobTriggerData */

		$template = EventNotificationTemplatePeer::retrieveByPK($triggerData->getTemplateId());
		/* @var $template BusinessProcessNotificationTemplate */

		$template->setCaseId($dbBatchJob, $triggerData->getCaseId());
	}

	/* (non-PHPdoc)
	 * @see kBatchJobStatusEventConsumer::shouldConsumeJobStatusEvent()
	 */
	public function shouldConsumeJobStatusEvent(BatchJob $dbBatchJob)
	{
		if(		$dbBatchJob->getJobType() == IntegrationPlugin::getBatchJobTypeCoreValue(IntegrationBatchJobType::INTEGRATION)
			&&	$dbBatchJob->getStatus() == BatchJob::BATCHJOB_STATUS_DONT_PROCESS
			&&	$dbBatchJob->getData()->getTriggerType() == BpmEventNotificationIntegrationPlugin::getIntegrationTriggerCoreValue(BpmEventNotificationIntegrationTrigger::BPM_EVENT_NOTIFICATION)
		)
		{
			return true;
		}

		return false;
	}

}

Use core enums for event

Use core enums for event


<?php

namespace Backend\Modules\Users\Actions;

use Backend\Core\Engine\Base\Action as BackendBaseAction;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Core\Engine\User as BackendUser;
use Backend\Modules\Users\Engine\Model as BackendUsersModel;

/**
 * This is the undo-delete-action, it will restore a deleted user
 */
class UndoDelete extends BackendBaseAction
{
    public function execute(): void
    {
        $email = $this->getRequest()->query->get('email', '');

        // does the user exist
        if ($email !== '') {
            parent::execute();

            // delete item
            if (BackendUsersModel::undoDelete($email)) {
                // get user
                $user = new BackendUser(null, $email);

                // item was deleted, so redirect
                $this->redirect(
                    BackendModel::createUrlForAction('edit') . '&id=' . $user->getUserId(
                    ) . '&report=restored&var=' . $user->getSetting('nickname') . '&highlight=row-' . $user->getUserId()
                );
            } else {
                // invalid user
                $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing');
            }
        } else {
            $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing');
        }
    }
}

<?php

namespace Backend\Modules\Users\Actions;

use Backend\Core\Engine\Base\Action as BackendBaseAction;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Core\Engine\User as BackendUser;
use Backend\Modules\Users\Engine\Model as BackendUsersModel;

/**
 * This is the undo-delete-action, it will restore a deleted user
 */
class UndoDelete extends BackendBaseAction
{
    public function execute(): void
    {
        $this->checkToken();

        $email = $this->getRequest()->query->get('email', '');

        // does the user exist
        if ($email !== '') {
            parent::execute();

            // delete item
            if (BackendUsersModel::undoDelete($email)) {
                // get user
                $user = new BackendUser(null, $email);

                // item was deleted, so redirect
                $this->redirect(
                    BackendModel::createUrlForAction('edit') . '&id=' . $user->getUserId(
                    ) . '&report=restored&var=' . $user->getSetting('nickname') . '&highlight=row-' . $user->getUserId()
                );
            } else {
                // invalid user
                $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing');
            }
        } else {
            $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing');
        }
    }
}

Check csrf token before restoring a deleted user


<!doctype html>
<html lang="fr">
    <head>
        <title>Anis & Flo, Octobre 2016</title>
    </head>

    <body></body>
</html>

Add title to the page

Add title to the page


<?php
namespace Auth;

class SQLPendingUser extends PendingUser
{
    private $hash;
    private $time;
    private $blob;
    private $table;

    public function __construct($data, $table = false)
    {
        $this->hash = $data['hash'];
        $this->time = new \DateTime($data['time']);
        $this->blob = json_decode($data['data']);
        $this->table = $table;
    }

    public function __get($propName)
    {
        if(is_array($this->blob->{$propName}))
        {
            return $this->blob->{$propName}[0];
        }
        return $this->blob->{$propName};
    }

    public function __set($propName, $value)
    {
    }

    public function getHash()
    {
        return $this->hash;
    }

    public function getRegistrationTime()
    {
        return $this->time;
    }

    public function getPassword()
    {
        if(is_array($this->blob->password))
        {
            return $this->blob->password[0];
        }
        return $this->blob->password;
    }

    public function offsetGet($offset)
    {
        return $this->blob->$offset;
    }

    public function delete()
    {
        $this->table->delete(new \Data\Filter("hash eq '{$this->hash}'"));
    }
}

<?php
namespace Auth;

class SQLPendingUser extends PendingUser
{
    private $hash;
    private $time;
    private $blob;
    private $table;

    public function __construct($data, $table = false)
    {
        $this->hash = $data['hash'];
        $this->time = new \DateTime($data['time']);
        $this->blob = json_decode($data['data']);
        $this->table = $table;
    }

    public function __get($propName)
    {
        if(is_array($this->blob->{$propName}))
        {
            return $this->blob->{$propName}[0];
        }
        return $this->blob->{$propName};
    }

    public function __set($propName, $value)
    {
    }

    public function __isset($propName)
    {
       return isset($this->block->{$propName});
    }

    public function getHash()
    {
        return $this->hash;
    }

    public function getRegistrationTime()
    {
        return $this->time;
    }

    public function getPassword()
    {
        if(is_array($this->blob->password))
        {
            return $this->blob->password[0];
        }
        return $this->blob->password;
    }

    public function offsetGet($offset)
    {
        return $this->blob->$offset;
    }

    public function delete()
    {
        $this->table->delete(new \Data\Filter("hash eq '{$this->hash}'"));
    }
}

Add isset check to SQL Pending user

Add isset check to SQL Pending user


<?php

namespace Imjoehaines\Flowder\Persister;

use PDO;

interface PersisterInterface
{
    /**
     * @param PDO $db
     */
    public function __construct(PDO $db);

    /**
     * Persist an array of data
     *
     * @param string $table
     * @param array $data
     * @return bool
     */
    public function persist($table, array $data);
}

<?php

namespace Imjoehaines\Flowder\Persister;

use PDO;

interface PersisterInterface
{
    /**
     * Persist an array of data
     *
     * @param string $table
     * @param array $data
     * @return bool
     */
    public function persist($table, array $data);
}

Remove constructor from persister interface


<?php

namespace Jenssegers\Agent;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->app->singleton('agent', function ($app) {
            return new Agent($app['request']->server->all());
        });

        $this->app->alias('agent', Agent::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['agent', Agent::class];
    }
}

<?php

namespace Jenssegers\Agent;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->app->singleton('agent', function ($app) {
            return new Agent($app['request']->server());
        });

        $this->app->alias('agent', Agent::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['agent', Agent::class];
    }
}

Use server() of Laravel Request

Use server() of Laravel Request


<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            $regex = implode('|', $quoted_paths);
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            usort($quoted_paths, function ($a, $b) { return strlen($b) - strlen($a); });
            $regex = implode('|', $quoted_paths);
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

Sort repository regex paths by longest first


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    const ANTI_SPAM_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'label'       => false,
            'attr'        => array(
                'class' => 'title_field',
            ),
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'darvin_utils_anti_spam';
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    const ANTI_SPAM_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'label'       => false,
            'attr'        => array(
                'class' => 'title_field',
            ),
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\TextType';
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'darvin_utils_anti_spam';
    }
}

Remove backslash escaping where it is not needed.


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

/**
 * @property int $count
 * @property int $name
 */
class Count extends Model
{
    public $incrementing = false;
    public $timestamps = false;

    protected $primaryKey = 'name';
    protected $table = 'osu_counts';

    public static function currentRankStart(string $mode): int
    {
        return static::firstOrCreate(['name' => "pp_rank_column_{$mode}"], ['count' => 0]);
    }

    public static function totalUsers()
    {
        return static::firstOrCreate(['name' => 'usercount'], ['count' => 0]);
    }

    public static function lastMailUserNotificationIdSent()
    {
        return static::firstOrCreate(['name' => 'last_mail_user_notification_id_sent'], ['count' => 0]);
    }
}

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

declare(strict_types=1);

namespace App\Models;

/**
 * @property int $count
 * @property int $name
 */
class Count extends Model
{
    public $incrementing = false;
    public $timestamps = false;

    protected $primaryKey = 'name';
    protected $table = 'osu_counts';

    public static function currentRankStart(string $mode): static
    {
        return static::firstOrCreate(['name' => "pp_rank_column_{$mode}"], ['count' => 0]);
    }

    public static function totalUsers(): static
    {
        return static::firstOrCreate(['name' => 'usercount'], ['count' => 0]);
    }

    public static function lastMailUserNotificationIdSent(): static
    {
        return static::firstOrCreate(['name' => 'last_mail_user_notification_id_sent'], ['count' => 0]);
    }
}

Fix return type and set strict

Fix return type and set strict


<?php
namespace LazyRecord\Schema;
use LazyRecord\Schema\DeclareSchema;

use SQLBuilder\Universal\Query\CreateIndexQuery;

class MixinDeclareSchema extends DeclareSchema
{
    protected $parentSchema;

    public function __construct($parentSchema, array $options = array()) {
        $this->parentSchema = $parentSchema;
        parent::__construct($options);
    }

    public function getParentSchema() {
        return $this->parentSchema;
    }

    /**
     * Build schema
     */
    public function build(array $options = array())
    {
        $this->schema($options);
        // we don't need primary field (id) for mixin schema
    }

    /* is_a can not work on an abstract class */
    public function schema() { }

    public function postSchema() { }

    /**
     * compatible methods for BaseModel to mixin
     */
    public static function beforeCreate($args) { return $args; }
    public static function beforeUpdate($args) { return $args; }

    public static function afterCreate($args) {}
    public static function afterUpdate($args) {}

    public function index($name, array $columns = null)
    {
        if (isset($this->indexes[$name])) {
            return $this->indexes[$name];
        }
        $query = $this->indexes[$name] = new CreateIndexQuery($name);
        if ($columns) {
            if (empty($columns)) {
                throw new InvalidArgumentException("index columns must not be empty.");
            }
            $query->on($this->parentSchema->getTable(), $columns);
        }
        return $query;
    }

}

<?php
namespace LazyRecord\Schema;
use LazyRecord\Schema\DeclareSchema;

use SQLBuilder\Universal\Query\CreateIndexQuery;

class MixinDeclareSchema extends DeclareSchema
{
    protected $parentSchema;

    public function __construct($parentSchema, array $options = array()) {
        $this->parentSchema = $parentSchema;
        parent::__construct($options);
    }

    public function getParentSchema() {
        return $this->parentSchema;
    }

    /**
     * Build schema
     */
    public function build(array $options = array())
    {
        $this->schema($options);
        // we don't need primary field (id) for mixin schema
    }

    /* is_a can not work on an abstract class */
    public function schema() { }

    public function postSchema() { }

    /**
     * compatible methods for BaseModel to mixin
     */
    public static function beforeCreate($args) { return $args; }
    public static function beforeUpdate($args) { return $args; }

    public static function afterCreate($args) {}
    public static function afterUpdate($args) {}

    public function index($name, $columns = null, $using = null)
    {
        return $this->parentSchema->index($name, $columns, $using);
    }

}

Fix mixin schema index method

Fix mixin schema index method


<?php

namespace Ams\Composer\GitHooks;

class GitHooks
{
    const SAMPLE = '.sample';

    static $hookFilename = [
        'applypatch-msg',
        'pre-applypatch',
        'post-applypatch',
        'pre-commit',
        'prepare-commit-msg',
        'commit-msg',
        'post-commit',
        'pre-rebase',
        'post-checkout',
        'post-merge',
        'pre-push',
        'pre-receive',
        'update',
        'post-receive',
        'post-update',
        'pre-auto-gc',
        'post-rewrite',
    ];
}

<?php

namespace Ams\Composer\GitHooks;

class GitHooks
{
    const SAMPLE = '.sample';

    public static $hookFilename = [
        'applypatch-msg',
        'pre-applypatch',
        'post-applypatch',
        'pre-commit',
        'prepare-commit-msg',
        'commit-msg',
        'post-commit',
        'pre-rebase',
        'post-checkout',
        'post-merge',
        'pre-push',
        'pre-receive',
        'update',
        'post-receive',
        'post-update',
        'pre-auto-gc',
        'post-rewrite',
    ];
}

Set static property visibility to public


<?php namespace NZTim\Queue\Commands;

use Illuminate\Console\Command;
use NZTim\Queue\QueueManager;

class QueuemgrListCommand extends Command
{
    protected $signature = 'queuemgr:list {days=7}';

    protected $description = 'Lists recent jobs within the specified number of days';

    /** @var QueueManager */
    protected $queueManager;

    public function __construct(QueueManager $queueManager)
    {
        parent::__construct();
        $this->queueManager = $queueManager;
    }

    public function handle()
    {
        $days = $this->argument('days');
        $entries = $this->queueManager->recent($days);
        foreach($entries as $entry) {
            $status = is_null($entry->deleted_at) ? "Incomplete" : "Complete";
            $status .= " ({$entry->attempts})";
            if ($entry->attempts == 0) {
                $status = "Failed!";
            }
            $class = get_class($entry->getJob());
            $this->info("{$entry->created_at->format('Y-m-d@H:i')} | ID:{$entry->getId()} | {$class} | {$status}");
        }
    }
}

<?php namespace NZTim\Queue\Commands;

use Illuminate\Console\Command;
use NZTim\Queue\QueueManager;

class QueuemgrListCommand extends Command
{
    protected $signature = 'queuemgr:list {days=7}';

    protected $description = 'Lists recent jobs within the specified number of days';

    /** @var QueueManager */
    protected $queueManager;

    public function __construct(QueueManager $queueManager)
    {
        parent::__construct();
        $this->queueManager = $queueManager;
    }

    public function handle()
    {
        $days = $this->argument('days');
        $entries = $this->queueManager->recent($days);
        foreach($entries as $entry) {
            $message = $entry->created_at->format('Y-m-d @ H:i') . ' | ';
            $message .= "ID:{$entry->getId()} | ";
            $message .= get_class($entry->getJob()) . ' | ';
            $status = "Complete";
            $method = "info";
            if (is_null($entry->deleted_at)) {
                $status = "Incomplete";
                $method = "error";
            }
            $status .= " ({$entry->attempts})";
            if ($entry->attempts == 0) {
                $status = "Failed!";
                $method = 'error';
            }
            $message .= $status;
            $this->$method($message);
        }
    }
}

Improve list command to display colours

Improve list command to display colours


<?php

namespace VotingApp\Services;

use MessageBroker as MessageBrokerConnection;

class MessageBroker
{
    /**
     * Serialize and send payload to the Message Broker using a
     * given routing key.
     *
     * @param array $payload
     * @param string $routingKey
     */
    public function publishRaw($payload, $routingKey)
    {
        // Don't send messages locally.
        if (app()->environment('local', 'testing')) {
            return;
        }

        // Configure the message broker connection
        $credentials = config('services.message_broker.credentials');
        $config = config('services.message_broker.config');
        $config['routingKey'] = $routingKey;
        $broker = new MessageBrokerConnection($credentials, $config);

        $serializedPayload = serialize($payload);
        $broker->publishMessage($serializedPayload);
    }

    /**
     * Append expected configuration variables to the payload, and
     * then send to the Message Broker.
     *
     * @param string $activity
     * @param array $payload
     * @param string $routingKey
     */
    public function publish($activity, $payload, $routingKey)
    {
        // Set common configuration values:
        $payload['application_id'] = env('MESSAGE_BROKER_APPLICATION_ID');
        $payload['mc_opt_in_path_id'] = env('MC_OPT_IN_PATH');
        $payload['mailchimp_list_id'] = env('MAILCHIMP_LIST_ID');

        // Add activity type and timestamp
        $payload['activity'] = $activity;
        $payload['activity_timestamp'] = time();

        $this->publishRaw($payload, $routingKey);
    }
}

<?php

namespace VotingApp\Services;

use MessageBroker as MessageBrokerConnection;

class MessageBroker
{
    /**
     * Serialize and send payload to the Message Broker using a
     * given routing key.
     *
     * @param array $payload
     * @param string $routingKey
     */
    public function publishRaw($payload, $routingKey)
    {
        // Don't send messages locally.
        if (app()->environment('local', 'testing')) {
            return;
        }

        // Configure the message broker connection
        $credentials = config('services.message_broker.credentials');
        $config = config('services.message_broker.config');
        $broker = new MessageBrokerConnection($credentials, $config);

        $serializedPayload = serialize($payload);
        $broker->publish($serializedPayload, $routingKey);
    }

    /**
     * Append expected configuration variables to the payload, and
     * then send to the Message Broker.
     *
     * @param string $activity
     * @param array $payload
     * @param string $routingKey
     */
    public function publish($activity, $payload, $routingKey)
    {
        // Set common configuration values:
        $payload['application_id'] = env('MESSAGE_BROKER_APPLICATION_ID');
        $payload['mc_opt_in_path_id'] = env('MC_OPT_IN_PATH');
        $payload['mailchimp_list_id'] = env('MAILCHIMP_LIST_ID');

        // Add activity type and timestamp
        $payload['activity'] = $activity;
        $payload['activity_timestamp'] = time();

        $this->publishRaw($payload, $routingKey);
    }
}

Use newer Message Broker publish method.


<?php

/*
 * This file is part of Gitamin.
 *
 * Copyright (C) 2015-2016 The Gitamin Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gitamin\Composers;

use Illuminate\Contracts\View\View;

class AppComposer
{
    public function compose(View $view)
    {
        $app = [
            'theme'    => 'default',
            'request'  => [
                'basepath' => '',
            ],
        ];
        //$owner = 'Gitamin';
        //$view->withOwner($owner);
        $view->withApp($app);
        $view->withGitaminVersion(GITAMIN_VERSION);
    }
}

<?php

/*
 * This file is part of Gitamin.
 *
 * Copyright (C) 2015-2016 The Gitamin Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gitamin\Composers;

use Illuminate\Contracts\View\View;

class AppComposer
{
    public function compose(View $view)
    {
        $view->withGitaminVersion(GITAMIN_VERSION);
    }
}

Remove no longer needed code

Remove no longer needed code


<?php

namespace App\Observers;

use App\Events\MatchWasFinished;
use App\Models\Match;
use Illuminate\Support\Facades\Log;

class MatchObserver
{
    public function updating(Match $model)
    {
        $dirtyStatus = array_get($model->getDirty(), 'status');
        $resultType = array_get($model->getOriginal(), 'resultType');

        if (Match::RESULT_TYPE_UNKNOWN === $resultType
            && Match::STATUS_FINISHED === $dirtyStatus
        ) {
            event(new MatchWasFinished($model));
        }
    }
}

<?php

namespace App\Observers;

use App\Events\MatchWasFinished;
use App\Models\Match;
use Illuminate\Support\Facades\Log;

class MatchObserver
{
    public function updating(Match $model)
    {
        $dirtyStatus = array_get($model->getDirty(), 'status');
        $resultType = array_get($model->getOriginal(), 'resultType');

        // original score values
        $originalHomeScore = array_get($model->getOriginal(), 'homeScore');
        $originalAwayScore = array_get($model->getOriginal(), 'awayScore');

        // dirty score values
        $dirtyHomeScore = array_get($model->getDirty(), 'homeScore');
        $dirtyAwayScore = array_get($model->getDirty(), 'awayScore');

        if ((Match::RESULT_TYPE_UNKNOWN === $resultType && Match::STATUS_FINISHED === $dirtyStatus)
            || ($originalHomeScore !== $dirtyHomeScore || $originalAwayScore !== $dirtyAwayScore)
        ) {
            event(new MatchWasFinished($model));
        }
    }
}

Update match result on score properties changes


<?php

// {% if autodeploy_dynamic_deploy_repo_names %}

function ansibleExec(repo) {
  echo shell_exec('/usr/local/bin/ansible-playbook /data/deployment/'.repo.'.yml -i /data/deployment/hosts');
}

// {% endif %}

if($_SERVER['REQUEST_METHOD'] === 'POST') {

//   {% if autodeploy_dynamic_deploy_repo_names %}

  $data = file_get_contents('php://input');
  $post = json_decode($data, TRUE);
  $repo = $post['repository']['slug'];

  switch($repo) {
  // {% for repo in autodeploy_dynamic_deploy_repo_names %}

    case '{{ repo }}':
      ansibleExec('{{ repo }}');
      break;

  // {% endfor%}

  }

//   {% else %}

  echo shell_exec('/usr/local/bin/ansible-playbook /data/deployment/deploy.yml -i /data/deployment/hosts');

//   {% endif %}

}

?>

<?php

// {% if autodeploy_dynamic_deploy_repo_names %}

function ansibleExec(repo) {
  echo shell_exec('/usr/local/bin/ansible-playbook /data/deployment/'.repo.'.yml -i /data/deployment/hosts');
}

// {% endif %}

if($_SERVER['REQUEST_METHOD'] === 'POST') {

//   {% if autodeploy_dynamic_deploy_repo_names %}

  $data = file_get_contents('php://input');
  $post = json_decode($data, TRUE);
  $repo = $post['repository']['slug'];

  switch($repo) {
  // {% for repo in autodeploy_dynamic_deploy_repo_names %}

    case '{{ repo }}':
      ansibleExec('{{ repo }}');
      break;

  // {% endfor%}

  }

//   {% else %}
  # Set PYTHONUNBUFFERED environment variable, so that the output from ansible isn't buffered
  putenv("PYTHONUNBUFFERED=1");
  echo shell_exec('/usr/local/bin/ansible-playbook /data/deployment/deploy.yml -i /data/deployment/hosts');

//   {% endif %}

}

?>

Make the output from ansible unbuffered

Make the output from ansible unbuffered

via the PYTHONUNBUFFERED environment variable


<?php

final class PhabricatorHomeProfileMenuItem
  extends PhabricatorProfileMenuItem {

  const MENUITEMKEY = 'home.dashboard';

  public function getMenuItemTypeName() {
    return pht('Home');
  }

  private function getDefaultName() {
    return pht('Home');
  }

  public function canMakeDefault(
    PhabricatorProfileMenuItemConfiguration $config) {
    return true;
  }

  public function getDisplayName(
    PhabricatorProfileMenuItemConfiguration $config) {
    $name = $config->getMenuItemProperty('name');

    if (strlen($name)) {
      return $name;
    }

    return $this->getDefaultName();
  }

  public function newPageContent() {
    $viewer = $this->getViewer();

    return id(new PHUIHomeView())
      ->setViewer($viewer);
  }

  public function buildEditEngineFields(
    PhabricatorProfileMenuItemConfiguration $config) {
    return array(
      id(new PhabricatorTextEditField())
        ->setKey('name')
        ->setLabel(pht('Name'))
        ->setPlaceholder($this->getDefaultName())
        ->setValue($config->getMenuItemProperty('name')),
    );
  }

  protected function newNavigationMenuItems(
    PhabricatorProfileMenuItemConfiguration $config) {
    $viewer = $this->getViewer();

    $name = $this->getDisplayName($config);
    $icon = 'fa-home';
    $href = $this->getItemViewURI($config);

    $item = $this->newItem()
      ->setHref($href)
      ->setName($name)
      ->setIcon($icon);

    return array(
      $item,
    );
  }

}

<?php

final class PhabricatorHomeProfileMenuItem
  extends PhabricatorProfileMenuItem {

  const MENUITEMKEY = 'home.dashboard';

  public function getMenuItemTypeName() {
    return pht('Built-in Homepage');
  }

  private function getDefaultName() {
    return pht('Home');
  }

  public function canMakeDefault(
    PhabricatorProfileMenuItemConfiguration $config) {
    return true;
  }

  public function getDisplayName(
    PhabricatorProfileMenuItemConfiguration $config) {
    $name = $config->getMenuItemProperty('name');

    if (strlen($name)) {
      return $name;
    }

    return $this->getDefaultName();
  }

  public function newPageContent() {
    $viewer = $this->getViewer();

    return id(new PHUIHomeView())
      ->setViewer($viewer);
  }

  public function buildEditEngineFields(
    PhabricatorProfileMenuItemConfiguration $config) {
    return array(
      id(new PhabricatorTextEditField())
        ->setKey('name')
        ->setLabel(pht('Name'))
        ->setPlaceholder($this->getDefaultName())
        ->setValue($config->getMenuItemProperty('name')),
    );
  }

  protected function newNavigationMenuItems(
    PhabricatorProfileMenuItemConfiguration $config) {
    $viewer = $this->getViewer();

    $name = $this->getDisplayName($config);
    $icon = 'fa-home';
    $href = $this->getItemViewURI($config);

    $item = $this->newItem()
      ->setHref($href)
      ->setName($name)
      ->setIcon($icon);

    return array(
      $item,
    );
  }

}

Add better description to built-in Home

Add better description to built-in Home

Summary: Ref T12174. This could be a little more verbose.

Test Plan: Review Global Menu Items

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin

Maniphest Tasks: T12174

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


<?php

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

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\Stopwatch\Stopwatch;
use Twig\Extension\ProfilerExtension as BaseProfilerExtension;
use Twig\Profiler\Profile;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class ProfilerExtension extends BaseProfilerExtension
{
    private $stopwatch;
    private $events;

    public function __construct(Profile $profile, Stopwatch $stopwatch = null)
    {
        parent::__construct($profile);

        $this->stopwatch = $stopwatch;
        $this->events = new \SplObjectStorage();
    }

    public function enter(Profile $profile): void
    {
        if ($this->stopwatch && $profile->isTemplate()) {
            $this->events[$profile] = $this->stopwatch->start($profile->getName(), 'template');
        }

        parent::enter($profile);
    }

    public function leave(Profile $profile): void
    {
        parent::leave($profile);

        if ($this->stopwatch && $profile->isTemplate()) {
            $this->events[$profile]->stop();
            unset($this->events[$profile]);
        }
    }
}

<?php

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

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Stopwatch\StopwatchEvent;
use Twig\Extension\ProfilerExtension as BaseProfilerExtension;
use Twig\Profiler\Profile;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class ProfilerExtension extends BaseProfilerExtension
{
    private $stopwatch;

    /**
     * @var \SplObjectStorage<Profile, StopwatchEvent>
     */
    private $events;

    public function __construct(Profile $profile, Stopwatch $stopwatch = null)
    {
        parent::__construct($profile);

        $this->stopwatch = $stopwatch;
        $this->events = new \SplObjectStorage();
    }

    public function enter(Profile $profile): void
    {
        if ($this->stopwatch && $profile->isTemplate()) {
            $this->events[$profile] = $this->stopwatch->start($profile->getName(), 'template');
        }

        parent::enter($profile);
    }

    public function leave(Profile $profile): void
    {
        parent::leave($profile);

        if ($this->stopwatch && $profile->isTemplate()) {
            $this->events[$profile]->stop();
            unset($this->events[$profile]);
        }
    }
}

Add generic types to traversable implementations


<?php

namespace QueryTranslator\Values;

/**
 * Token sequence holds an array of tokens extracted from the query string.
 *
 * @see \QueryTranslator\Tokenizing::tokenize()
 */
class TokenSequence
{
    /**
     * An array of tokens extracted from the input string.
     *
     * @var \QueryTranslator\Values\Token[]
     */
    public $tokens;

    /**
     * Source query string, unmodified.
     *
     * @var string
     */
    public $source;

    /**
     * @param \QueryTranslator\Values\Token[] $tokens[]
     * @param string $source
     */
    public function __construct(array $tokens, $source)
    {
        $this->tokens = $tokens;
        $this->source = $source;
    }
}

<?php

namespace QueryTranslator\Values;

/**
 * Token sequence holds an array of tokens extracted from the query string.
 *
 * @see \QueryTranslator\Tokenizing::tokenize()
 */
class TokenSequence
{
    /**
     * An array of tokens extracted from the input string.
     *
     * @var \QueryTranslator\Values\Token[]
     */
    public $tokens;

    /**
     * Source query string, unmodified.
     *
     * @var string
     */
    public $source;

    /**
     * @param \QueryTranslator\Values\Token[] $tokens
     * @param string $source
     */
    public function __construct(array $tokens, $source)
    {
        $this->tokens = $tokens;
        $this->source = $source;
    }
}

Fix param name in docblock

Fix param name in docblock


<?php

class ZendDbTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiateDbAdapter()
    {
        $adapter = \Zend_Db::factory(
            'Pdo_Sqlite',
            array(
                'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
            )
        );
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }

    public function testZendDbFactoryWithZendConfig()
    {
        $config = new Zend_Config(
            array(
                'database' => array(
                    'adapter' => 'Pdo_Sqlite',
                    'params'  => array(
                        'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
                    )
                )
            )
        );

        $adapter = Zend_Db::factory($config->database);
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }
}

<?php

class ZendDbTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiateDbAdapter()
    {
        $adapter = \Zend_Db::factory(
            'Pdo_Sqlite',
            array(
                'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
            )
        );
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }

    public function testZendDbFactoryWithZendConfig()
    {
        $config = new Zend_Config(
            array(
                'database' => array(
                    'adapter' => 'Pdo_Sqlite',
                    'params'  => array(
                        'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
                    )
                )
            )
        );

        $adapter = Zend_Db::factory($config->database);
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }

    public function testZendDbAdapterForcingConnection()
    {
        $adapter = \Zend_Db::factory(
            'Pdo_Sqlite',
            array(
                'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
            )
        );
        $connection = $adapter->getConnection();
        $this->assertInstanceOf('PDO', $connection);
    }
}

Add Zend_Db Test - force connection using adapter


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Promotion\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
    /**
     * @param mixed $promotionId
     *
     * @return QueryBuilder
     */
    public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;

    /**
     * @param int $codeLength
     *
     * @return int
     */
    public function countByCodeLength(int $codeLength): int;

    /**
     * @param string $code
     * @param string $promotionCode
     *
     * @return PromotionCouponInterface|null
     */
    public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Promotion\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
    /**
     * @param mixed $promotionId
     *
     * @return QueryBuilder
     */
    public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;

    /**
     * @param int $codeLength
     *
     * @return int
     */
    public function countByCodeLength(int $codeLength): int;

    /**
     * @param string $code
     * @param string $promotionCode
     *
     * @return PromotionCouponInterface|null
     */
    public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;

    /**
     * @param string $promotionCode
     *
     * @return iterable
     */
    public function findByPromotionCode(string $promotionCode): iterable;
}

[API][Promotion] Index coupons only for requested promotion


<?php
class Simple_Random_Image{

    private $imageObject;

    public function __construct(){
        $this->imageObject = null;
        $this->random_image_from_library();
    }

    private function random_image_from_library(){
        $args = array(
            'numberposts'       => 1,
            'orderby'           => 'rand',
            'post_type'         => 'attachment',
            'post_mime_type'    =>'image',
            'post_status'       => null,
            'post_parent'       => null
        );

        $attachments = get_posts( $args );
        if( $attachments ){
            $this->imageObject = $attachments[0];
        }
    }
}

<?php
class Simple_Random_Image{

    private $dataObject;
    private $image;

    public function __construct(){
        $this->initialize();
        $this->generate();
    }

    private function initialize(){
        $this->dataObject = null;
        $this->image = array();

        $this->image["url"] = "";
        $this->image["alt"] = "";
        $this->image["title"] = "";
        $this->image["height"] = 0;
        $this->image["width"] = 0;
    }

    public function generate(){
        $args = array(
            'numberposts'       => 1,
            'orderby'           => 'rand',
            'post_type'         => 'attachment',
            'post_mime_type'    => 'image',
            'post_status'       => null,
            'post_parent'       => null
        );

        $attachments = get_posts( $args );
        if( $attachments ){
            $this->dataObject = $attachments[0];
        }
        echo "<pre>";
        var_dump($this->dataObject);
        echo "</pre>";
    }

    public function get( $size = "medium", $value = "all" ){
        if( $value === "all" ){
            return $this->image;
        }
    }
}

Rename the method to generate a random object from the library and add some methods to handle the image


<?php
/**
 * WidgetController.php
 * avanzu-admin
 * Date: 16.03.14
 */

namespace Avanzu\AdminThemeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WidgetController extends Controller
{
    public function defaultBoxAction() {
    }

    public function solidBoxAction() {}

    public function tiledBoxAction() {}

    public function smallBoxAction() {}
}

<?php
/**
 * WidgetController.php
 * avanzu-admin
 * Date: 16.03.14
 */

namespace Avanzu\AdminThemeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WidgetController extends Controller
{
    public function defaultBoxAction() {}

    public function solidBoxAction() {}

    public function tiledBoxAction() {}

    public function smallBoxAction() {}
}

Use same format for functions

Use same format for functions


<?php
namespace Http;

class WebErrorHandler
{
    public function __invoke($request, $response, $exception)
    {
        if($exception->getCode() === \Http\Rest\ACCESS_DENIED)
        {
            return $response->withStatus(401);
        }
        return $response
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write($exception->__toString());
   }
}

<?php
namespace Http;

class WebErrorHandler
{
    public function __invoke($request, $response, $exception)
    {
        if($exception->getCode() === \Http\Rest\ACCESS_DENIED)
        {
            $response->getBody()->write('You are not authorized to view this page. The most common cause of this is that you are not logged in to the website. Please log in then try again');
            return $response->withStatus(401);
        }
        return $response
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write($exception->__toString());
   }
}

Update generic error handler to include not logged in message


<?php

/**
 * Class VersionedReadingMode
 */
class VersionedReadingMode
{
    /**
     * @var String
     */
    private static $originalReadingMode;

    /**
     * Set the reading mode to 'Stage' so that all data objects are displayed for lists whether or not they have
     * been published
     */
    public static function setStageReadingMode()
    {
        self::$originalReadingMode = Versioned::current_stage();
        Versioned::reading_stage('Stage');
    }

    /**
     * Set the reading mode to 'Live'
     */
    public static function setLiveReadingMode()
    {
        self::$originalReadingMode = Versioned::current_stage();
        Versioned::reading_stage('Live');
    }

    /**
     * Restore the reading mode to what's been set originally in the CMS
     */
    public static function restoreOriginalReadingMode()
    {
        if (isset(self::$originalReadingMode) && in_array(self::$originalReadingMode, ['Stage', 'Live'])) {
            Versioned::reading_stage(self::$originalReadingMode);
        }
    }
}

<?php

/**
 * Class VersionedReadingMode
 */
class VersionedReadingMode
{
    /**
     * @var String
     */
    private static $originalReadingMode;

    /**
     * Set the reading mode to 'Stage' so that all data objects are displayed for lists whether or not they have
     * been published
     */
    public static function setStageReadingMode()
    {
        self::$originalReadingMode = Versioned::current_stage();
        Versioned::reading_stage('Stage');
    }

    /**
     * Set the reading mode to 'Live'
     */
    public static function setLiveReadingMode()
    {
        self::$originalReadingMode = Versioned::current_stage();
        Versioned::reading_stage('Live');
    }

    /**
     * Restore the reading mode to what's been set originally in the CMS
     */
    public static function restoreOriginalReadingMode()
    {
        if (
            isset(self::$originalReadingMode) &&
            in_array(self::$originalReadingMode, array('Stage', 'Live'))
        ) {
            Versioned::reading_stage(self::$originalReadingMode);
        }
    }
}

Use array instead of PHP 5.4. [] syntax

Use array instead of PHP 5.4. [] syntax


<?php

namespace Enqueue\Symfony\Client;

use Enqueue\Client\SpoolProducer;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class FlushSpoolProducerListener implements EventSubscriberInterface
{
    /**
     * @var SpoolProducer
     */
    private $producer;

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

    public function flushMessages()
    {
        $this->producer->flush();
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        $events = [];

        if (class_exists(KernelEvents::class)) {
            $events[KernelEvents::TERMINATE] = 'flushMessages';
        }

        if (class_exists(ConsoleEvents::class)) {
            $events[ConsoleEvents::TERMINATE] = 'flushMessages';
        }

        return $events;
    }
}

<?php

namespace Enqueue\Symfony\Client;

use Enqueue\Client\SpoolProducer;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class FlushSpoolProducerListener implements EventSubscriberInterface
{
    /**
     * @var SpoolProducer
     */
    private $producer;

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

    public function flushMessages()
    {
        $this->producer->flush();
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents(): array
    {
        $events = [];

        if (class_exists(KernelEvents::class)) {
            $events[KernelEvents::TERMINATE] = 'flushMessages';
        }

        if (class_exists(ConsoleEvents::class)) {
            $events[ConsoleEvents::TERMINATE] = 'flushMessages';
        }

        return $events;
    }
}

Fix types for Symfony 5.4

Fix types for Symfony 5.4


<?php

namespace App\Exceptions;

use App\Exceptions\SolverException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof ValidationException) {
            return response()->json([
                'message' => trans('error.validation'),
                'errors' => $exception->errors(),
            ], 422);
        }

        if ($exception instanceof SolverException) {
            return response()->json([
                'message' => trans('error.solution'),
            ], 422);
        }

        if ($exception instanceof InvalidSignatureException) {
            return response()->json([
                'message' => trans('error.signature'),
            ], 500);
        }

        return parent::render($request, $exception);
    }
}

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (ValidationException $e, $request) {
            return response()->json([
                'message' => trans('error.validation'),
                'errors' => $e->errors(),
            ], 422);
        });

        $this->renderable(function (InvalidSignatureException $e, $request) {
            return response()->json([
                'message' => trans('error.signature'),
            ], 500);
        });

        return parent::render($request, $exception);
    }
}

Use exception renderable instead of uses of instanceof