<?php

namespace Laravel\Passport\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;

class DenyAuthorizationController
{
    use RetrievesAuthRequestFromSession;

    /**
     * The response factory implementation.
     *
     * @var ResponseFactory
     */
    protected $response;

    /**
     * Create a new controller instance.
     *
     * @param  ResponseFactory  $response
     * @return void
     */
    public function __construct(ResponseFactory $response)
    {
        $this->response = $response;
    }

    /**
     * Deny the authorization request.
     *
     * @param  Request  $request
     * @return Response
     */
    public function deny(Request $request)
    {
        $redirect = $this->getAuthRequestFromSession($request)
                    ->getClient()->getRedirectUri();

        return $this->response->redirectTo(
            $redirect.'?error=access_denied&state='.$request->input('state')
        );
    }
}

<?php

namespace Laravel\Passport\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;

class DenyAuthorizationController
{
    use RetrievesAuthRequestFromSession;

    /**
     * The response factory implementation.
     *
     * @var ResponseFactory
     */
    protected $response;

    /**
     * Create a new controller instance.
     *
     * @param  ResponseFactory  $response
     * @return void
     */
    public function __construct(ResponseFactory $response)
    {
        $this->response = $response;
    }

    /**
     * Deny the authorization request.
     *
     * @param  Request  $request
     * @return Response
     */
    public function deny(Request $request)
    {
        $authRequest = $this->getAuthRequestFromSession($request);

        $authRequest->getClient()->getRedirectUri();
        $separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : '?';

        return $this->response->redirectTo(
            $redirect.$separator.'error=access_denied&state='.$request->input('state')
        );
    }
}

Fix implicit flow athorization denied redirect


<?php

namespace JonoM\FocusPoint\Extensions;

use JonoM\FocusPoint\Dev\FocusPointMigrationTask;
use JonoM\FocusPoint\FieldType\DBFocusPoint;
use SilverStripe\Assets\Image;
use SilverStripe\Assets\Storage\DBFile;

/**
 * FocusPoint Image extension.
 * Extends Image to allow automatic cropping from a selected focus point.
 *
 * @extends DataExtension
 * @property DBFocusPoint $FocusPoint
 * @property Image|DBFile|FocusPointImageExtension $owner
 */
class FocusPointImageExtension extends FocusPointExtension
{
    /**
     * Describes the focus point coordinates on the image.
     */
    private static $db = [
        'FocusPoint' => DBFocusPoint::class,
    ];

    public function requireDefaultRecords()
    {
        $autoMigrate = FocusPointMigrationTask::create();
        $autoMigrate->up();
    }

    public function onBeforeWrite()
    {
        // Ensure that we saved the cached image width / height whenever we change the file hash
        if (
            (
                $this->owner->isChanged('FileHash')
                || empty($this->owner->FocusPoint->getField('Width'))
                || empty($this->owner->FocusPoint->getField('Height'))
            ) && $this->owner->exists()
        ) {
            $this->owner->FocusPoint->Width = $this->owner->getWidth();
            $this->owner->FocusPoint->Height = $this->owner->getHeight();
        }
    }
}

<?php

namespace JonoM\FocusPoint\Extensions;

use JonoM\FocusPoint\Dev\FocusPointMigrationTask;
use JonoM\FocusPoint\FieldType\DBFocusPoint;
use SilverStripe\Assets\Image;
use SilverStripe\Assets\Storage\DBFile;

/**
 * FocusPoint Image extension.
 * Extends Image to allow automatic cropping from a selected focus point.
 *
 * @extends DataExtension
 * @property DBFocusPoint $FocusPoint
 * @property Image|DBFile|FocusPointImageExtension $owner
 */
class FocusPointImageExtension extends FocusPointExtension
{
    /**
     * Describes the focus point coordinates on the image.
     */
    private static $db = [
        'FocusPoint' => DBFocusPoint::class,
    ];

    public function requireDefaultRecords()
    {
        $autoMigrate = FocusPointMigrationTask::create();
        $autoMigrate->up();
    }

    public function onBeforeWrite()
    {
        // Ensure that we saved the cached image width / height whenever we change the file hash
        // This code ignores forceChange, since we only need to know if the underlying file is modified
        $changes = $this->owner->getChangedFields(['FileHash']);
        $fileHashChanged = isset($changes['FileHash']) && $changes['FileHash']['before'] !== $changes['FileHash']['after'];
        if (
            (
                $fileHashChanged
                || empty($this->owner->FocusPoint->getField('Width'))
                || empty($this->owner->FocusPoint->getField('Height'))
            ) && $this->owner->exists()
        ) {
            $this->owner->FocusPoint->Width = $this->owner->getWidth();
            $this->owner->FocusPoint->Height = $this->owner->getHeight();
        }
    }
}

Fix performance issue with publishing images


<?php namespace Klaravel\Ntrust\Traits;

use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;

trait NtrustPermissionTrait
{
    /**
     * Many-to-Many relations with role model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Config::get('ntrust.profiles.' . self::$roleProfile . '.role'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_role_table'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.role_foreign_key'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_foreign_key')
            );
    }

    /**
     * Trait boot method
     *
     * @return void
     */
    protected static function bootNtrustPermissionTrait()
    {
        /**
         * Attach event listener to remove the many-to-many records when trying to delete
         *  Will NOT delete any records if the permission model uses soft deletes.
         */
        static::deleted(function($permission)
        {
            if(Cache::getStore() instanceof TaggableStore) {
                Cache::tags(Config::get('ntrust.profiles.' . self::$roleProfile . '.permission'))
                    ->flush();

                $permission->roles()->sync([]);
            }
        });
    }
}

<?php namespace Klaravel\Ntrust\Traits;

use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;

trait NtrustPermissionTrait
{
    /**
     * Many-to-Many relations with role model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Config::get('ntrust.profiles.' . self::$roleProfile . '.role'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_role_table'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_foreign_key'),
            Config::get('ntrust.profiles.' . self::$roleProfile . '.role_foreign_key')
            );
    }

    /**
     * Trait boot method
     *
     * @return void
     */
    protected static function bootNtrustPermissionTrait()
    {
        /**
         * Attach event listener to remove the many-to-many records when trying to delete
         *  Will NOT delete any records if the permission model uses soft deletes.
         */
        static::deleted(function($permission)
        {
            if(Cache::getStore() instanceof TaggableStore) {
                Cache::tags(Config::get('ntrust.profiles.' . self::$roleProfile . '.permission'))
                    ->flush();

                $permission->roles()->sync([]);
            }
        });
    }
}

Fix roles relation of Permission

Fix roles relation of Permission


<?php

namespace Michaeljennings\Carpenter\Tests\Store;

use Michaeljennings\Carpenter\Store\Laravel4\Eloquent;
use Michaeljennings\Carpenter\Tests\TestCase;

class Laravel4StoreTest extends TestCase
{
    public function testCountReturnsTotalResults()
    {
        $store = $this->makeStore();
        $model = new ExampleEloquentModel();

        $store->model($model);
        $this->assertEquals(0, $store->count());
    }

    /**
     * @expectedException \Michaeljennings\Carpenter\Exceptions\ModelNotSetException
     */
    public function testExceptionIsThrownIfCountIsCalledBeforeModelIsSet()
    {
        $store = $this->makeStore();

        $store->count();
    }

    public function makeStore()
    {
        return new Eloquent();
    }
}

<?php

namespace Michaeljennings\Carpenter\Tests\Store;

use Michaeljennings\Carpenter\Store\Laravel4\Eloquent;
use Michaeljennings\Carpenter\Tests\TestCase;
use Mockery as m;

class Laravel4StoreTest extends TestCase
{
    public function testCountReturnsTotalResults()
    {
        $store = $this->makeStore();
        $model = new ExampleEloquentModel();

        $store->model($model);
        $this->assertEquals(0, $store->count());
    }

    /**
     * @expectedException \Michaeljennings\Carpenter\Exceptions\ModelNotSetException
     */
    public function testExceptionIsThrownIfCountIsCalledBeforeModelIsSet()
    {
        $store = $this->makeStore();

        $store->count();
    }

    public function makeStore()
    {
        $app = [
            'paginator' => m::mock('Paginator', [
                'make' => m::mock('Paginator', [
                    'links' => '',
                    'getCurrentPage' => 1,
                    'setPageName' => true,
                ]),
                'setPageName' => null,
            ]),
        ];

        return new Eloquent($app);
    }
}

Fix laravel 4 store unit test

Fix laravel 4 store unit test


<?php get_header(); ?>

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

	<?php
		$args=array(
		'taxonomy' => 'gradyear',
		'post_type' => 'illustrator',
		'term' => '2011',
		'posts_per_page' => -1,
		'orderby' => 'rand',
		);
	?>

	<?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
  <?php query_posts( $args );?>
	<?php while (have_posts()) : the_post(); ?>

                   <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
                       <?php the_post_thumbnail('thumbnail', array('alt' => 'Thumbnail of '.get_the_title().'', 'title' => ''.get_the_title().'' )); ?>

       <?php endwhile; ?>

<?php endif; ?>

<?php if (  $wp_query->max_num_pages > 1 ) : ?>

<?php previous_posts_link('« View Previous') ?>

<?php next_posts_link('View More »') ?>

<?php endif; ?>

<?php get_footer(); ?>

<?php get_header(); ?>

	<?php
		$args=array(
		'taxonomy' => 'gradyear',
		'post_type' => 'illustrator',
		'term' => '2011',
		'posts_per_page' => -1,
		'orderby' => 'rand',
		);
	?>

	<?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
  <?php query_posts( $args );?>
	<?php while (have_posts()) : the_post(); ?>

                   <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
                       <?php the_post_thumbnail('thumbnail', array('alt' => 'Thumbnail of '.get_the_title().'', 'title' => ''.get_the_title().'' )); ?>

       <?php endwhile; ?>

<?php get_footer(); ?>

Index to show all illustrators without an existing post in database


<html>
	<head>
		<title>WebEL</title>
		<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

		<script type="text/javascript" src="gl-matrix-2.1.0.js"></script>
		<script type="text/javascript" src="webgl-utils.js"></script>
		<script type="text/javascript" src="jquery-2.1.3.js"></script>

		<script type="text/javascript" src="ajaxblob.js"></script>

		<script type="text/javascript" src="Camera.js"></script>
		<script type="text/javascript" src="DDS.js"></script>
		<script type="text/javascript" src="GameWindow.js"></script>
		<script type="text/javascript" src="KeyHandler.js"></script>
		<script type="text/javascript" src="Stack.js"></script>
		<script type="text/javascript" src="Shaders.js"></script>
		<script type="text/javascript" src="TextureCache.js"></script>
		<script type="text/javascript" src="drawscene.js"></script>
	</head>

	<body onload="webGLStart();">
		<canvas id="webel-canvas" style="border: none;" width="500" height="500"></canvas>
	</body>
</html>

<html>
	<head>
		<title>WebEL</title>
		<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

		<script type="text/javascript" src="gl-matrix.js"></script>
		<script type="text/javascript" src="webgl-utils.js"></script>
		<script type="text/javascript" src="jquery-2.1.3.js"></script>

		<script type="text/javascript" src="ajaxblob.js"></script>

		<script type="text/javascript" src="Camera.js"></script>
		<script type="text/javascript" src="DDS.js"></script>
		<script type="text/javascript" src="GameWindow.js"></script>
		<script type="text/javascript" src="KeyHandler.js"></script>
		<script type="text/javascript" src="Stack.js"></script>
		<script type="text/javascript" src="Shaders.js"></script>
		<script type="text/javascript" src="TextureCache.js"></script>
		<script type="text/javascript" src="drawscene.js"></script>
	</head>

	<body onload="webGLStart();">
		<canvas id="webel-canvas" style="border: none;" width="500" height="500"></canvas>
	</body>
</html>

Use git version of gl-matrix, since it has some functions we could use


<?php

namespace Mollie\Api;

use Mollie\Api\Exceptions\IncompatiblePlatform;

class CompatibilityChecker
{
    /**
     * @var string
     */
    public const MIN_PHP_VERSION = "7.0";

    /**
     * @throws IncompatiblePlatform
     * @return void
     */
    public function checkCompatibility()
    {
        if (! $this->satisfiesPhpVersion()) {
            throw new IncompatiblePlatform(
                "The client requires PHP version >= " . self::MIN_PHP_VERSION . ", you have " . PHP_VERSION . ".",
                IncompatiblePlatform::INCOMPATIBLE_PHP_VERSION
            );
        }

        if (! $this->satisfiesJsonExtension()) {
            throw new IncompatiblePlatform(
                "PHP extension json is not enabled. Please make sure to enable 'json' in your PHP configuration.",
                IncompatiblePlatform::INCOMPATIBLE_JSON_EXTENSION
            );
        }
    }

    /**
     * @return bool
     * @codeCoverageIgnore
     */
    public function satisfiesPhpVersion()
    {
        return (bool)version_compare(PHP_VERSION, self::MIN_PHP_VERSION, ">=");
    }

    /**
     * @return bool
     * @codeCoverageIgnore
     */
    public function satisfiesJsonExtension()
    {
        // Check by extension_loaded
        if (function_exists('extension_loaded') && extension_loaded('json')) {
            return true;
        } elseif (function_exists('json_encode')) {
            return true;
        }

        return false;
    }
}

<?php

namespace Mollie\Api;

use Mollie\Api\Exceptions\IncompatiblePlatform;

class CompatibilityChecker
{
    /**
     * @var string
     */
    public const MIN_PHP_VERSION = "7.2";

    /**
     * @throws IncompatiblePlatform
     * @return void
     */
    public function checkCompatibility()
    {
        if (! $this->satisfiesPhpVersion()) {
            throw new IncompatiblePlatform(
                "The client requires PHP version >= " . self::MIN_PHP_VERSION . ", you have " . PHP_VERSION . ".",
                IncompatiblePlatform::INCOMPATIBLE_PHP_VERSION
            );
        }

        if (! $this->satisfiesJsonExtension()) {
            throw new IncompatiblePlatform(
                "PHP extension json is not enabled. Please make sure to enable 'json' in your PHP configuration.",
                IncompatiblePlatform::INCOMPATIBLE_JSON_EXTENSION
            );
        }
    }

    /**
     * @return bool
     * @codeCoverageIgnore
     */
    public function satisfiesPhpVersion()
    {
        return (bool)version_compare(PHP_VERSION, self::MIN_PHP_VERSION, ">=");
    }

    /**
     * @return bool
     * @codeCoverageIgnore
     */
    public function satisfiesJsonExtension()
    {
        // Check by extension_loaded
        if (function_exists('extension_loaded') && extension_loaded('json')) {
            return true;
        } elseif (function_exists('json_encode')) {
            return true;
        }

        return false;
    }
}

Fix PHP 7.2 Compatibility Check

Fix PHP 7.2 Compatibility Check


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

namespace Momento;

/**
 * Handles events with either simple processing or delegating complex tasks to a
 * proper service or model.
 *
 * @author George D. Cooksey, III <texdc3@gmail.com>
 */
interface EventHandler
{
    /**
     * Handle an {@link Event}
     *
     * @param  Event $event the event to handle
     * @return EventResult
     */
    public function handle(Event $event);

    /**
     * List the handled event types
     *
     * @return array
     */
    public function listHandledEventTypes();
}

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

namespace Momento;

/**
 * Handles events with either simple processing or delegating complex tasks to a
 * proper service or model.
 *
 * @package Momento
 */
interface EventHandler
{
    /**
     * Process or delegate an {@link Event}
     *
     * @param  Event            $anEvent      the event to handle
     * @param  EventResult|null $aPriorResult optional result from a prior handler
     * @return EventResult
     */
    public function handle(Event $anEvent, EventResult $aPriorResult = null);

    /**
     * List the handled event types
     *
     * @return string[]
     */
    public function listHandledEventTypes();
}

Add optional prior handler to handle signature


<?php

namespace Serializer;

/**
 * Class SerializationContext
 *
 * @package Serializer
 * @author Tales Santos <tales.maxmilhas@gmail.com>
 */
class SerializationContext
{
    private $groups = ['Default'];
    private $serializeNull = true;

    public static function create(): SerializationContext
    {
        return new self;
    }

    /**
     * @param array $groups
     * @return SerializationContext
     */
    public function setGroups(array $groups): SerializationContext
    {
        $this->groups = $groups;
        return $this;
    }

    public function getGroups(): array
    {
        return $this->groups;
    }

    public function setSerializeNull(bool $enabled)
    {
        $this->serializeNull = $enabled;
        return $this;
    }

    public function shouldSerializeNull(): bool
    {
        return $this->serializeNull;
    }
}

<?php

namespace Serializer;

/**
 * Class SerializationContext
 *
 * @package Serializer
 * @author Tales Santos <tales.maxmilhas@gmail.com>
 */
class SerializationContext
{
    private $groups = ['Default'];
    private $serializeNull = false;

    public static function create(): SerializationContext
    {
        return new self;
    }

    /**
     * @param array $groups
     * @return SerializationContext
     */
    public function setGroups(array $groups): SerializationContext
    {
        $this->groups = $groups;
        return $this;
    }

    public function getGroups(): array
    {
        return $this->groups;
    }

    public function setSerializeNull(bool $enabled)
    {
        $this->serializeNull = $enabled;
        return $this;
    }

    public function shouldSerializeNull(): bool
    {
        return $this->serializeNull;
    }
}

Make serialize null values option to false


<?php
namespace IVIR3aM\GraphicEditor\Tests\Colors;

use IVIR3aM\GraphicEditor\ColorInterface;
use IVIR3aM\GraphicEditor\Colors\FlyweightFactory;
use PHPUnit\Framework\TestCase;

class FlyweightFactoryTest extends TestCase
{
    /**
     * @var FlyweightFactory
     */
    private $factory;

    public function setUp()
    {
        $this->factory = new FlyweightFactory();
    }

    public function testFactory()
    {
        $color = $this->factory->getColor(255, 512, 120);
        $this->assertInstanceOf(ColorInterface::class, $color);
        $this->assertSame($color, $this->factory->getColor(255, 255, 120));
        $this->assertSame($color->getRed(), 255);
        $this->assertSame($color->getGreen(), 255);
        $this->assertSame($color->getBlue(), 120);
    }
}

<?php
namespace IVIR3aM\GraphicEditor\Tests\Colors;

use IVIR3aM\GraphicEditor\ColorInterface;
use IVIR3aM\GraphicEditor\Colors\FlyweightFactory;
use PHPUnit\Framework\TestCase;

class FlyweightFactoryTest extends TestCase
{
    /**
     * @var FlyweightFactory
     */
    private $factory;

    public function setUp()
    {
        $this->factory = new FlyweightFactory();
    }

    public function testFactory()
    {
        $color = $this->factory->getColor(255, 512, 120);
        $this->assertTrue($color instanceof ColorInterface);
        $this->assertSame($color, $this->factory->getColor(255, 255, 120));
        $this->assertSame($color->getRed(), 255);
        $this->assertSame($color->getGreen(), 255);
        $this->assertSame($color->getBlue(), 120);
    }
}

Change assertInstanceOf to assertTrue for PHP5.4


<?php

namespace Phug\Test\Parser\TokenHandler;

use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\WhileTokenHandler;
use Phug\Test\AbstractParserTest;

/**
 * @coversDefaultClass Phug\Parser\TokenHandler\WhileTokenHandler
 */
class WhileTokenHandlerTest extends AbstractParserTest
{
    /**
     * @covers ::<public>
     */
    public function testHandleToken()
    {
        $this->assertNodes("while \$i < 3\n  p=\$i", [
            '[DocumentNode]',
            '  [WhileNode]',
            '    [ElementNode]',
            '      [ExpressionNode]',
        ]);
    }

    /**
     * @covers                   ::<public>
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage You can only pass while tokens to this token handler
     */
    public function testHandleTokenTokenException()
    {
        $lexer = new Lexer();
        $state = new State($lexer->lex(''));
        $handler = new WhileTokenHandler();
        $handler->handleToken(new TagToken(), $state);
    }
}

<?php

namespace Phug\Test\Parser\TokenHandler;

use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\WhileTokenHandler;
use Phug\Test\AbstractParserTest;

/**
 * @coversDefaultClass Phug\Parser\TokenHandler\WhileTokenHandler
 */
class WhileTokenHandlerTest extends AbstractParserTest
{
    /**
     * @covers ::<public>
     */
    public function testHandleToken()
    {
        $this->assertNodes("while \$i < 3\n  p=\$i", [
            '[DocumentNode]',
            '  [WhileNode]',
            '    [ElementNode]',
            '      [ExpressionNode]',
        ]);
        $this->assertNodes(
            "- var x = 1;\n".
            "ul\n".
            "  while x < 10\n".
            "    - x++;\n".
            "    li= x\n"
        , [
            '[DocumentNode]',
            '  [CodeNode]',
            '    [TextNode]',
            '  [ElementNode]',
            '    [WhileNode]',
            '      [CodeNode]',
            '        [TextNode]',
            '      [ElementNode]',
            '        [ExpressionNode]',
        ]);
    }

    /**
     * @covers                   ::<public>
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage You can only pass while tokens to this token handler
     */
    public function testHandleTokenTokenException()
    {
        $lexer = new Lexer();
        $state = new State($lexer->lex(''));
        $handler = new WhileTokenHandler();
        $handler->handleToken(new TagToken(), $state);
    }
}

Add complex while test that match the pugjs case


<?php use_helper('I18N') ?>

<form action="<?php echo url_for('@sf_guard_signin') ?>" method="post">

      <?php echo $form ?>

          <input type="submit" value="<?php echo __('Signin', null, 'sf_guard') ?>" />

          <?php $routes = $sf_context->getRouting()->getRoutes() ?>
          <?php if (isset($routes['sf_guard_forgot_password'])): ?>
            <a href="<?php echo url_for('@sf_guard_forgot_password') ?>"><?php echo __('Forgot your password?', null, 'sf_guard') ?>
          <?php endif; ?>

          <?php if (isset($routes['sf_guard_register'])): ?>
              <a href="<?php echo url_for('@sf_guard_register') ?>"><?php echo __('Want to register?', null, 'sf_guard') ?>
          <?php endif; ?>

</form>

<?php use_helper('I18N') ?>

<form action="<?php echo url_for('@sf_guard_signin') ?>" method="post">

      <?php echo $form ?>

          <input type="submit" value="<?php echo __('Signin', null, 'sf_guard') ?>" />

          <?php if ($sf_context->getRouting()->hasRouteName('sf_guard_forgot_password')): ?>
            <a href="<?php echo url_for('@sf_guard_forgot_password') ?>"><?php echo __('Forgot your password?', null, 'sf_guard') ?>
          <?php endif; ?>

          <?php if ($sf_context->getRouting()->hasRouteName('sf_guard_register')): ?>
              <a href="<?php echo url_for('@sf_guard_register') ?>"><?php echo __('Want to register?', null, 'sf_guard') ?>
          <?php endif; ?>

</form>

Remove usage of getRoutes in a view

[plugin][sfDoctrineGuardPlugin][1.4] Remove usage of getRoutes in a view


<?php

namespace Pix\SortableBehaviorBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SortableAdminController extends CRUDController
{
    /**
     * Move element
     *
     * @param integer $id
     * @param string $position
     */
    public function moveAction($id, $position)
    {
        $object = $this->admin->getObject($id);

        $position_service = $this->get('pix_sortable_behavior.position');
        $last_position = $position_service->getLastPosition(get_class($object));
        $position = $position_service->getPosition($object, $position, $last_position);

        $object->setPosition($position);
        $this->admin->update($object);

        if ($this->isXmlHttpRequest()) {
            return $this->renderJson(array(
                'result' => 'ok',
                'objectId' => $this->admin->getNormalizedIdentifier($object)
            ));
        }
        $this->get('session')->setFlash('sonata_flash_info', 'Position mise à jour');

        return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
    }

}

<?php

namespace Pix\SortableBehaviorBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SortableAdminController extends CRUDController
{
    /**
     * Move element
     *
     * @param integer $id
     * @param string $position
     */
    public function moveAction($id, $position)
    {
        $object = $this->admin->getObject($id);

        $position_service = $this->get('pix_sortable_behavior.position');
        $last_position = $position_service->getLastPosition(get_class($object));
        $position = $position_service->getPosition($object, $position, $last_position);

        $object->setPosition($position);
        $this->admin->update($object);

        if ($this->isXmlHttpRequest()) {
            return $this->renderJson(array(
                'result' => 'ok',
                'objectId' => $this->admin->getNormalizedIdentifier($object)
            ));
        }
        $this->get('session')->getFlashBag()->set('sonata_flash_info', 'Position mise à jour');

        return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
    }

}

Fix flash message for Symfony >= 2.1

Fix flash message for Symfony >= 2.1


Connexion

    <form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">

        Email<input name="email" id="email" type="text" required />

        Mot de Passe<input id="password" type="password" required />

        <input type="submit" value="Se Connecter" class="submit" />

    </form>

      <a href="<?php echo Config::get('config.base'); ?>/user/register" class="password-lost">Mot de passe oublié
      <a href="<?php echo Config::get('config.base'); ?>/user/lostpassword" class="register">Pas encore inscrit ?

Connexion

    <form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">

        Email<input name="email" id="email" type="text" required />

        Mot de Passe<input name="password" id="password" type="password" required />

        <input type="submit" value="Se Connecter" class="submit" />

    </form>

      <a href="<?php echo Config::get('config.base'); ?>/user/register" class="password-lost">Mot de passe oublié
      <a href="<?php echo Config::get('config.base'); ?>/user/lostpassword" class="register">Pas encore inscrit ?

Fix missing name on password field

Fix missing name on password field


<?php

use Mdd\QueryBuilder\Queries;
use Mdd\QueryBuilder\Conditions;
use Mdd\QueryBuilder\Types;
use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper;

class SelectTest extends PHPUnit_Framework_TestCase
{
    protected
        $escaper;

    protected function setUp()
    {
        $this->escaper = new SimpleEscaper();
    }

    public function testSelect()
    {
        $query = (new Queries\Select())->setEscaper($this->escaper);

        $query
            ->select(array('id', 'name'))
            ->from('poney')
            ->where(new Conditions\Equal('name', new Types\String('burger')))
        ;

        $this->assertSame("SELECT id, name FROM poney WHERE name = 'burger'", $query->toString($this->escaper));
    }
}

<?php

use Mdd\QueryBuilder\Queries;
use Mdd\QueryBuilder\Conditions;
use Mdd\QueryBuilder\Types;
use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper;

class SelectTest extends PHPUnit_Framework_TestCase
{
    protected
        $escaper;

    protected function setUp()
    {
        $this->escaper = new SimpleEscaper();
    }

    public function testSelect()
    {
        $query = (new Queries\Select())->setEscaper($this->escaper);

        $query
            ->select(array('id', 'name'))
            ->from('poney')
            ->where(new Conditions\Equal('name', new Types\String('burger')))
        ;

        $this->assertSame("SELECT id, name FROM poney WHERE name = 'burger'", $query->toString($this->escaper));
    }

    public function testSelectMultipleWhere()
    {
        $query = (new Queries\Select())->setEscaper($this->escaper);

        $query
            ->select(array('id', 'name'))
            ->from('poney')
            ->where(new Conditions\Equal('name', new Types\String('burger')))
            ->where(new Conditions\Equal('rank', new Types\Int(42)))
        ;

        $this->assertSame("SELECT id, name FROM poney WHERE name = 'burger' AND rank = 42", $query->toString($this->escaper));
    }

    public function testSelectMultipleSelect()
    {
        $query = (new Queries\Select())->setEscaper($this->escaper);

        $query
            ->select(array('id', 'name'))
            ->select('rank')
            ->select(array('taste', 'price'))
            ->select('rank')
            ->from('poney')
            ->where(new Conditions\Equal('name', new Types\String('burger')))
        ;

        $this->assertSame("SELECT id, name, rank, taste, price FROM poney WHERE name = 'burger'", $query->toString($this->escaper));
    }
}

Add tests for select query

Add tests for select query


<?php

$staq_path = substr( __DIR__, 0, strrpos( __DIR__, '/Staq/' ) + 5 );
require_once( $staq_path . '/util/tests.php' );
include_once( $staq_path . '/include.php' );

// CONTEXT
$path = \Staq\util\string_basename( __DIR__, 4 );
$app = new \Staq\Application( $path );
$app->run( );

// TEST COLLECTION
$case = new \Staq\util\Test_Case( 'Extends project without configuration', [
	'Extensions' => function( ) use ( $app, $path ) {
		return ( $app->get_extensions( ) == [ $path, 'Staq/view', 'Staq/ground' ] );
	}
] );

// RESULT
echo $case->to_html( );
return $case;

<?php

$staq_path = substr( __DIR__, 0, strrpos( __DIR__, '/Staq/' ) + 5 );
require_once( $staq_path . '/util/tests.php' );
include_once( $staq_path . '/include.php' );

// CONTEXT
$path = \Staq\util\string_basename( __DIR__, 4 );
$app = new \Staq\Application( $path );
$app->run( );

// TEST COLLECTION
$case = new \Staq\util\Test_Case( 'With the starter disabled', [
	'Extensions' => function( ) use ( $app, $path ) {
		return ( $app->get_extensions( ) == [ $path, 'Staq/view', 'Staq/ground' ] );
	}
] );

// RESULT
echo $case->to_html( );
return $case;

Change the name of the test to disabled an extension


<?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
    define('PHPUnit2_MAIN_METHOD', 'Zend_HttpClient_AllTests::main');
}

require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';

require_once 'Zend/Http/ResponseTest.php';
require_once 'Zend/Http/ClientTest.php';

class Zend_Http_AllTests
{
    public static function main()
    {
        PHPUnit2_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit2_Framework_TestSuite('Zend Framework - Zend_HttpClient');

        $suite->addTestSuite('Zend_Http_ClientTest');
		$suite->addTestSuite('Zend_Http_ResponseTest');

        return $suite;
    }
}

if (PHPUnit2_MAIN_METHOD == 'Zend_Http_AllTests::main') {
    Zend_HttpClient_AllTests::main();
}

<?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
    define('PHPUnit2_MAIN_METHOD', 'Zend_HttpClient_AllTests::main');
}

require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';

require_once 'Zend/Http/ResponseTest.php';
require_once 'Zend/Http/ClientTest.php';

class Zend_Http_AllTests
{
    public static function main()
    {
        PHPUnit2_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit2_Framework_TestSuite('Zend Framework - Zend_HttpClient');

        $suite->addTestSuite('Zend_Http_ClientTest');
		$suite->addTestSuite('Zend_Http_Client_ResponseTest');

        return $suite;
    }
}

if (PHPUnit2_MAIN_METHOD == 'Zend_Http_AllTests::main') {
    Zend_HttpClient_AllTests::main();
}

Fix test case class name.

Fix test case class name.

git-svn-id: b6e219894c353fb1d215c78b2075057d8daadfba@1040 44c647ce-9c0f-0410-b52a-842ac1e357ba


<?php

namespace Tests\Integration;

use Dotenv\Dotenv;
use ElasticEmail\Client;
use ElasticEmail\Email\Send;
use Tests\TestCase;

class SendTest extends TestCase
{
    /** @test */
    public function send_an_email()
    {
        $dotenv = Dotenv::createImmutable(__DIR__ . '../../');
        $dotenv->load();

        $apiKey = getenv('ELASTIC_EMAIL_API_KEY');
        $from = getenv('INTEGRATION_TEST_EMAIL_FROM');
        $to = getenv('INTEGRATION_TEST_EMAIL_TO');

        $client = new Client($apiKey);

        $send = new Send($client);

        $response = $send->handle([
            'to' => $to,
            'from' => $from,
            'subject' => $this->subject(__FUNCTION__),
        ]);

        $this->assertTrue($response->wasSuccessful());
        $this->assertEquals(200, $response->getStatusCode());
    }
}

<?php

namespace Tests\Integration\Email;

use Dotenv\Dotenv;
use ElasticEmail\Client;
use ElasticEmail\Email\Send;
use Tests\Integration\IntegrationTestCase;

class SendTest extends IntegrationTestCase
{
    /** @test */
    public function send_an_email()
    {
        $this->loadEnv();
        $client = new Client($_ENV['ELASTIC_EMAIL_API_KEY']);
        $send = new Send($client);

        $subject = "elasticemail-php: Integration test ensuring email send.";
        $response = $send->handle([
            'to' => $_ENV['INTEGRATION_TEST_EMAIL_TO'],
            'from' => $_ENV['INTEGRATION_TEST_EMAIL_FROM'],
            'subject' => $subject,
        ]);

        $this->assertTrue($response->wasSuccessful());
        $this->assertEquals(200, $response->getStatusCode());
    }
}

Refactor to load to/from from .env values.


<?php
require dirname(__DIR__) . '/vendor/autoload.php';

use WebSocket\Client;
use Pheanstalk\Pheanstalk;

// Wait time in seconds when there are no clients connected
define('WAIT_TIME',1);

$pheanstalk = new Pheanstalk('127.0.0.1');

$wsClient = new Client("ws://localhost:10800");

// Publish the job/message to the websocket server
function publishMessage($client, $message) {
    $client->send($message);

    $result = $client->receive();

    $client->close();
    return $result == "OK";
}

// will read messages from beanstalkd queue and block
// when no messages are available
while (true) {
    global $pheanstalk;

    $job = $pheanstalk
         ->watch('cfm')
         ->ignore('default')
         ->reserve();

    print_r($job);

    echo "Reserved job: {$job->getId()}";
    $data = $job->getData();

    // if the message is succefull published to clients
    // it will be deleted, else we wait before trying again
    if ( publishMessage($data) ) {
        $pheanstalk->delete($job);
        echo "deleted job: {$job->getId()}";
    } else {
        $pheanstalk->release($job);
        echo "released job: {$job->getId()}";
        sleep(WAIT_TIME);
    }
}

<?php
require dirname(__DIR__) . '/vendor/autoload.php';

use WebSocket\Client;
use Pheanstalk\Pheanstalk;

// Wait time in seconds when there are no clients connected
define('WAIT_TIME',1);

$pheanstalk = new Pheanstalk('127.0.0.1');

$wsClient = new Client("ws://localhost:10800");

// Publish the job/message to the websocket server
function publishMessage($client, $message) {
    $client->send($message);

    $result = $client->receive();

    $client->close();
    return $result == "OK";
}

// will read messages from beanstalkd queue and block
// when no messages are available
while (true) {
    global $pheanstalk;

    $job = $pheanstalk
         ->watch('cfm')
         ->ignore('default')
         ->reserve();

    print_r($job);

    echo "Reserved job: {$job->getId()}";
    $data = $job->getData();

    // if the message is succefull published to clients
    // it will be deleted, else we wait before trying again
    if ( publishMessage($wsClient, $data) ) {
        $pheanstalk->delete($job);
        echo "deleted job: {$job->getId()}";
    } else {
        $pheanstalk->release($job);
        echo "released job: {$job->getId()}";
        sleep(WAIT_TIME);
    }
}

Fix missing parameter in publishMessage function


<?php
// -- include/functions/utilities.php
// ---------------------------------------------------------------------------------------------

/**
 * string get_permalink_by_slug( string $slug [, string $post_type = 'post'] )
 * Retrieves the permalink of the post with the given slug and post type.
 *
 * @param   string  $slug       The post slug.
 * @param   string  $post_type  The post type (shocking, I know).
 *
 * @return  string              The generated permalink.
 * ------------------------------------------------------------------------------------------ */
function get_permalink_by_slug( $slug, $post_type = 'post' )
{
  if ( empty( $slug ) )
    return;

  global $wpdb;
  $sql = $wpdb->prepare(
    'SELECT `ID` FROM `%1$s` WHERE `post_type`="%2$s" AND `post_name`="%3$s" AND `post_status`="publish";',
    $wpdb->posts,
    $post_type,
    $slug
  );

  $ID = $wpdb->get_var( $sql );
  if ( !empty( $ID ) )
    return get_permalink( $ID );
}

<?php
// -- include/functions/utilities.php
// ---------------------------------------------------------------------------------------------

/**
 * string get_permalink_by_slug( string $slug [, string $post_type = 'post'] )
 * Retrieves the permalink of the post with the given slug and post type.
 *
 * @param   string  $slug       The post slug.
 * @param   string  $post_type  The post type (shocking, I know).
 *
 * @return  string              The generated permalink.
 * ------------------------------------------------------------------------------------------ */
function get_permalink_by_slug( $slug, $post_type = 'post' )
{
  if ( empty( $slug ) )
    return;

  global $wpdb;
  $sql = $wpdb->prepare(
    "SELECT `ID` FROM {$wpdb->posts} WHERE `post_type`='%s' AND `post_name`='%s' AND `post_status`='publish';",
    $post_type,
    $slug
  );

  $ID = $wpdb->get_var( $sql );
  if ( !empty( $ID ) )
    return get_permalink( $ID );
}

Add support for prepare statement hardening


<!DOCTYPE html>

<meta charset="UTF-8">
<title>PHP-login</title>

<?php
// if you need users's information, just put them into the $_SESSION variable and output them here

echo $phplogin_lang['You are logged in as'] . $_SESSION['user_name'] ."
\n";
//echo $login->user_gravatar_image_url;
echo $phplogin_lang['Profile picture'] .'
'. $login->user_gravatar_image_tag;

?>

	<?php echo $phplogin_lang['Logout']; ?>
	<?php echo $phplogin_lang['Edit user data']; ?>

<?php
// include html header and display php-login message/error
include('header.php');

// if you need users's information, just put them into the $_SESSION variable and output them here

echo $phplogin_lang['You are logged in as'] . $_SESSION['user_name'] ."
\n";
//echo $login->user_gravatar_image_url;
echo $phplogin_lang['Profile picture'] .'
'. $login->user_gravatar_image_tag;

?>

	<?php echo $phplogin_lang['Logout']; ?>
	<?php echo $phplogin_lang['Edit user data']; ?>

<?php
// include html footer
include('footer.php');

Update logged-in.php: Basis CSS code inside views and adding header/footer files


<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Connect to MySQL
include("dbconnect.php");

// Prepare the SQL statement
$sensor = $_GET["serial"];
$celsius = $_GET["temperature"];
$humidity = $_GET["humidity"];

$SQL = "INSERT INTO `dht22` (sensor,celsius,humidity) VALUES ($sensor,$celsius,$humidity)";
// Execute SQL statement
mysqli_query($link, $SQL);
?>

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Connect to MySQL
include("dbconnect.php");

// Prepare the SQL statement
$sensor = $_GET["serial"];
$celsius = $_GET["temperature"];
$humidity = $_GET["humidity"];
$pressure = $_GET["pressure"];
echo "Sensor: " . $sensor . PHP_EOL;
echo "Temperature: " . $celsius . PHP_EOL;
echo "Humidity: " . $humidity . PHP_EOL;
echo "Pressure: " . $pressure . PHP_EOL;
$SQL = "INSERT INTO `dht22` (sensor,celsius,humidity,pressure) VALUES ('$sensor','$celsius','$humidity','$pressure')";

// Execute SQL statement
mysqli_query($link, $SQL);
?>

Add pressure measurement, improve syntax of INSERT statement.


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

use GeneaLabs\LaravelGovernor\Providers\LaravelGovernorService;
use Illuminate\Console\Command;

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

    public function handle()
    {
        if ($this->option('assets')) {
            $this->call('casts:publish', ['--assets' => true]);
        }

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

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

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

use GeneaLabs\LaravelGovernor\Providers\Service as LaravelGovernorService;
use Illuminate\Console\Command;

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

    public function handle()
    {
        if ($this->option('assets')) {
            $this->call('casts:publish', ['--assets' => true]);
        }

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

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

Fix service provider class name

Fix service provider class name


<a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?>

<?php
foreach ($context as $e) {
    //Start building an array of row classes
    $classes = array('event');

    if ($e->isAllDay()) {
        $classes[] = 'all-day';
    }

    if ($e->isInProgress()) {
        $classes[] = 'in-progress';
    }

    if ($e->isOnGoing()) {
        $classes[] = 'ongoing';
    }

    ?>
    <li class="<?php echo implode(' ', $classes); ?>">
        <?php echo $savvy->render($e, 'EventInstance/Date.tpl.php') ?> :
        <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?>

    <?php
}
?>

Add a link to the day

Add a link to the day


<?php

namespace UMFlint\Html\Traits;

trait Checkable
{
    /**
     * Helper to check an input.
     *
     * @author Donald Wilcox <dowilcox@umflint.edu>
     * @return $this
     */
    public function check()
    {
        $this->set('checked', 'checked');

        return $this;
    }

    /**
     * Helper to uncheck an input.
     *
     * @author Donald Wilcox <dowilcox@umflint.edu>
     * @return $this
     */
    public function uncheck()
    {
        $this->remove('checked');

        return $this;
    }
}

<?php

namespace UMFlint\Html\Traits;

trait Checkable
{
    /**
     * Helper to check an input.
     *
     * @author Donald Wilcox <dowilcox@umflint.edu>
     * @param bool $check
     * @return $this
     */
    public function check($check = true)
    {
        if ($check) {
            $this->set('checked', 'checked');
        }else {
            $this->uncheck();
        }

        return $this;
    }

    /**
     * Helper to uncheck an input.
     *
     * @author Donald Wilcox <dowilcox@umflint.edu>
     * @return $this
     */
    public function uncheck()
    {
        $this->remove('checked');

        return $this;
    }
}

Set check based on passed value.

Set check based on passed value.


<?php
namespace bmtmgr;

require_once dirname(__DIR__) . '/src/common.php';

if (isset($_GET['autocomplete']) && $_GET['autocomplete'] == 'json') {
	render_json(array_map(function($c) {
		return [
			'id' => $c->id,
			'name' => $c->name,
			'text' => '(' . $c->id . ') ' . $c->name,
		];
	}, user\User::get_all()));
	exit();
}

$u = user\check_current();
$u->require_perm('admin');

render('club_list', [
	'user' => $u,
	'breadcrumbs' => [
		['name' => 'Clubs', 'path' => 'club/']
	],
	'clubs' => user\User\get_all(),
]);

<?php
namespace bmtmgr;

require_once dirname(__DIR__) . '/src/common.php';

if (isset($_GET['autocomplete']) && $_GET['autocomplete'] == 'json') {
	render_json(array_map(function($c) {
		return [
			'id' => $c->id,
			'name' => $c->name,
			'text' => '(' . $c->id . ') ' . $c->name,
		];
	}, user\User::get_all()));
	exit();
}

$u = user\check_current();
$u->require_perm('admin');

render('club_list', [
	'user' => $u,
	'breadcrumbs' => [
		['name' => 'Clubs', 'path' => 'club/']
	],
	'clubs' => user\User::get_all(),
]);

Correct method call for model class

Correct method call for model class


<?php namespace willvincent\Rateable;

use Config;
use Illuminate\Database\Eloquent\Model;

class Rating extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $fillable = ['rating'];

    /**
     * @return mixed
     */
    public function rateable()
    {
        return $this->morphTo();
    }

    /**
     * Rating belongs to a user.
     *
     * @return User
     */
    public function user()
    {
        return $this->belongsTo(Config::get('auth.providers.users.model'));
    }
}

<?php namespace willvincent\Rateable;

use Config;
use Illuminate\Database\Eloquent\Model;

class Rating extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $fillable = ['rating'];

    /**
     * @return mixed
     */
    public function rateable()
    {
        return $this->morphTo();
    }

    /**
     * Rating belongs to a user.
     *
     * @return User
     */
    public function user()
    {
        $userClassName = Config::get('auth.model');
        if (is_null($userClassName)) {
            $userClassName = Config::get('auth.providers.users.model');
        }

        return $this->belongsTo($userClassName);
    }
}

Fix user relation while maintaining older verions

There is another approach which is using `app()->version()` however I didn't want to go throw strings manipulation to figure it out!


<?php

/**
 * Subclass for representing a row from the 'profile_property' table.
 *
 *
 *
 * @package lib.model
 */
class ProfileProperty extends BaseProfileProperty
{
  /**
  * to string
  *
  * @return string
  */
  public function __toString()
  {
    return $this->getLabel();
  }

  /**
   * @param int $counter
   * @param string $language
   *
   * @return string
   */
  public function getLabelForExport($counter, $language = '')
  {
    $label = $this->getName();
    $label = $this->getIsRequired() ? "*" . $label : $label;
    if ($this->getHasLanguage()) {
      $label = $this->getIsSingleton() ? $label . "_" . $language : $label . "[$counter]_" . $language;
    } else {
      $label = $this->getIsSingleton() ? $label : $label . "[$counter]";
    }
    return $label;

  } //__toString
}

<?php

/**
 * Subclass for representing a row from the 'profile_property' table.
 *
 *
 *
 * @package lib.model
 */
class ProfileProperty extends BaseProfileProperty
{
  /**
  * to string
  *
  * @return string
  */
  public function __toString()
  {
    return $this->getLabel();
  }

  /**
   * @param int $counter
   * @param string $language
   *
   * @return string
   */
  public function getLabelForExport($counter, $language = '')
  {
    $label = $this->getLabel();
    $label = $this->getIsRequired() ? "*" . $label : $label;
    if ($this->getHasLanguage()) {
      $label = $this->getIsSingleton() ? $label . "_" . $language : $label . "[$counter]_" . $language;
    } else {
      $label = $this->getIsSingleton() ? $label : $label . "[$counter]";
    }
    return $label;

  } //__toString
}

Use the (English) label instead of the name for export


<?php

namespace Prelude;

const anyPass = __NAMESPACE__.'\anyPass';

function anyPass(array $preds)
{
    return function ($value) use ($preds) {
        return array_reduce($preds, function ($carry, callable $pred) use ($value) {
            return true === $carry
                ? $carry
                : $pred($value);
        }, false);
    };
}

<?php

namespace Prelude;

const anyPass = __NAMESPACE__.'\anyPass';

function anyPass(array $preds)
{
    return function ($value) use ($preds) {
        return array_reduce($preds, function ($carry, callable $pred) use ($value) {
            return equals($carry, true)
                ? $carry
                : $pred($value);
        }, false);
    };
}

Replace === by equals fn

Replace === by equals fn


<?php
namespace phorkie;

class Repository_Setup
{
    protected $repo;

    public function __construct(Repository $repo)
    {
        $this->repo = $repo;
    }

    /**
     * Should be called right after a repository has been created,
     * either by "git init" or "git clone".
     * Takes care of removing hook example files and creating
     * the git daemon export file
     *
     * @return void
     */
    public function afterInit()
    {
        foreach (glob($this->repo->gitDir . '/hooks/*') as $hookfile) {
            unlink($hookfile);
        }
        touch($this->repo->gitDir . '/git-daemon-export-ok');

        $vc = $this->repo->getVc();

        file_put_contents(
            $this->repo->gitDir . '/hooks/post-update',
            <<<CDE
#!/bin/sh
# Hook script to prepare a packed repository for use over dumb transports.

exec git update-server-info

CDE
        );
        chmod($this->repo->gitDir . '/hooks/post-update', 0755);

        //keep track of owner
        $vc->getCommand('config')
            ->addArgument('user.name')
            ->addArgument($_SESSION['name'])
            ->execute();
        $vc->getCommand('config')
            ->addArgument('user.email')
            ->addArgument($_SESSION['email'])
            ->execute();
    }

}

?>

<?php
namespace phorkie;

class Repository_Setup
{
    protected $repo;

    public function __construct(Repository $repo)
    {
        $this->repo = $repo;
    }

    /**
     * Should be called right after a repository has been created,
     * either by "git init" or "git clone".
     * Takes care of removing hook example files and creating
     * the git daemon export file
     *
     * @return void
     */
    public function afterInit()
    {
        foreach (glob($this->repo->gitDir . '/hooks/*') as $hookfile) {
            unlink($hookfile);
        }
        touch($this->repo->gitDir . '/git-daemon-export-ok');

        $vc = $this->repo->getVc();

        file_put_contents(
            $this->repo->gitDir . '/hooks/post-update',
            <<<CDE
#!/bin/sh
# Hook script to prepare a packed repository for use over dumb transports.

exec git update-server-info

CDE
        );
        chmod($this->repo->gitDir . '/hooks/post-update', 0755);

        //keep track of owner
        $vc->getCommand('config')
            ->addArgument('owner.name')
            ->addArgument($_SESSION['name'])
            ->execute();
        $vc->getCommand('config')
            ->addArgument('owner.email')
            ->addArgument($_SESSION['email'])
            ->execute();
    }

}

?>

Revert "Fixed bad owner/user config, causing pastes to fail with 'Please tell me who you are'"

This reverts commit b0396671c6aad090e6b9b5bc9d6b6886b9f0d4e3.

The owner.* configuration is custom-made by phorkie.
If we use user.*, anonymous commits automatically get the user.* settings
which we do not want.

Resolves: https://github.com/cweiske/phorkie/issues/27


<?php
class A01_Frontend_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function setProfileInfo(FunctionalTester $I)
    {
        $I->wantTo('Set a user profile.');

        $I->amOnPage('/');
        $I->see('Dashboard');

        $I->amOnPage('/profile');
        $I->see('Profile');
        $I->see('Super Administrator');

        $I->click('Edit Profile');

        $I->submitForm('.form', [
            'timezone' => 'US/Central',
            'locale' => 'fr_FR.UTF-8',
        ]);

        $I->seeCurrentUrlEquals('/profile');
        $I->see('Central Time');
        $I->see('Français');
    }
}

<?php
class A01_Frontend_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function setProfileInfo(FunctionalTester $I)
    {
        $I->wantTo('Set a user profile.');

        $I->amOnPage('/');
        $I->see('Dashboard');

        $I->amOnPage('/profile');
        $I->see('Profile');
        $I->see('Super Administrator');

        $I->click('Edit');

        $I->submitForm('.form', [
            'timezone' => 'US/Central',
            'locale' => 'fr_FR.UTF-8',
        ]);

        $I->seeCurrentUrlEquals('/profile');
        $I->see('Central Time');
        $I->see('Français');
    }
}

Update language on unit test.

Update language on unit test.


<?php

namespace Jaybizzle;

class Seasons
{
    /**
     * Seasons.
     *
     * @var array
     */
    public $seasons = array(
        'Winter',
        'Spring',
        'Summer',
        'Autumn',
    );

    /**
     * Parse input date and return numeric month.
     *
     * @param  string
     *
     * @return int
     */
    public function getMonth($date)
    {
        if (is_null($date)) {
            return date('n');
        } else {
            return date('n', strtotime($date));
        }
    }

    /**
     * Parse date, return season.
     *
     * @param  string
     *
     * @return string
     */
    public function get($date = null)
    {
        return $this->seasons[(int) (($this->getMonth($date) % 12) / 3)];
    }
}

<?php

namespace Jaybizzle;

class Seasons
{
    /**
     * Seasons.
     *
     * @var array
     */
    public $seasons = array(
        'Winter',
        'Spring',
        'Summer',
        'Autumn',
    );

    /**
     * Parse input date and return numeric month.
     *
     * @param  string
     * @return int
     */
    public function getMonth($date)
    {
        if(is_null($date)) {
            return date('n');
        } else {
            if($parsed_date = strtotime($date)) {
                return date('n', strtotime($date));
            }

            throw new \Exception('Input date must be parsable by strtotime().');
        }
    }

    /**
     * Parse date, return season.
     *
     * @param  string
     *
     * @return string
     */
    public function get($date = null)
    {
        return $this->seasons[(int) (($this->getMonth($date) % 12) / 3)];
    }
}

Throw exception if input date is not parsable


<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
  <meta charset="<?php bloginfo('charset'); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width">
  <meta name="theme-color" content="#464646">

  <meta name="author" content="">
  <meta name="description" content="">

  <?php wp_head(); ?>

  <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body>

    <header id="masthead" class="site-header" role="banner">
        <nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
            <?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
        </nav>
    </header>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
  <meta charset="<?php bloginfo('charset'); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width">
  <meta name="theme-color" content="#464646">

  <meta name="author" content="">
  <meta name="description" content="">

  <?php wp_head(); ?>

  <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body <?php body_class(); ?>>

    <header id="masthead" class="site-header" role="banner">
        <nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">
            <?php wp_nav_menu(['theme_location' => 'primary-menu', 'menu_class' => 'nav-menu']); ?>
        </nav>
    </header>

Include the <?php body_class(); ?>

Include the <?php body_class(); ?>

We should always include the body class on the body, because a lot of well known and popular plugins use this in their functions.


<?php

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

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

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

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

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

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

<?php

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

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

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

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

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

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

Enable preventing remote access to debug environment on production server


<?php namespace Orchestra\Foundation\Providers;

use Illuminate\Support\AggregateServiceProvider;

class ConsoleSupportServiceProvider extends AggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        'Orchestra\Auth\CommandServiceProvider',
        'Orchestra\Extension\CommandServiceProvider',
        'Orchestra\Memory\CommandServiceProvider',
        'Orchestra\Optimize\OptimizeServiceProvider',
        'Orchestra\View\CommandServiceProvider',
    ];

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

<?php namespace Orchestra\Foundation\Providers;

use Illuminate\Support\AggregateServiceProvider;

class ConsoleSupportServiceProvider extends AggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        'Orchestra\Auth\CommandServiceProvider',
        'Orchestra\Extension\CommandServiceProvider',
        'Orchestra\Memory\CommandServiceProvider',
        'Orchestra\Optimize\OptimizeServiceProvider',
        'Orchestra\Publisher\CommandServiceProvider',
        'Orchestra\View\CommandServiceProvider',
    ];

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

Add publisher command service provider.

Add publisher command service provider.

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


<?php

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

class CreateVillagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('laravolt.indonesia.table_prefix') . 'villages', function(Blueprint $table)
        {
            $table->char('id', 10);
            $table->char('district_id', 7);
            $table->string('name', 255);
            $table->primary('id');
            $table->foreign('district_id')->references('id')->on(config('laravolt.indonesia.table_prefix') . 'districts');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop(config('laravolt.indonesia.table_prefix') . 'villages');
    }
}

<?php

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

class CreateVillagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('laravolt.indonesia.table_prefix') . 'villages', function(Blueprint $table)
        {
            $table->char('id', 10);
            $table->char('district_id', 7);
            $table->string('name', 255);
            $table->primary('id');
            $table->foreign('district_id')->references('id')->on(config('laravolt.indonesia.table_prefix') . 'districts');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop(config('laravolt.indonesia.table_prefix') . 'villages');
    }
}

Solve schema not found on migrate

Solve schema not found on migrate

[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Schema' not found


<?php
/**
 * Resque test case class. Contains setup and teardown methods.
 *
 * @package		Resque/Tests
 * @author		Chris Boulton <chris@bigcommerce.com>
 * @license		http://www.opensource.org/licenses/mit-license.php
 */
class Resque_Tests_TestCase extends PHPUnit_Framework_TestCase
{
	protected $resque;
	protected $redis;

	public function setUp()
	{
		$config = file_get_contents(REDIS_CONF);
		preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches);
		$this->redis = new RedisApi('localhost', $matches[1]);
		$this->redis->prefix(REDIS_NAMESPACE);
		$this->redis->select(REDIS_DATABASE);

		// Flush redis
		$this->redis->flushAll();
	}
}

<?php
/**
 * Resque test case class. Contains setup and teardown methods.
 *
 * @package		Resque/Tests
 * @author		Chris Boulton <chris@bigcommerce.com>
 * @license		http://www.opensource.org/licenses/mit-license.php
 */
class Resque_Tests_TestCase extends PHPUnit_Framework_TestCase
{
	protected $resque;
	protected $redis;

	public function setUp()
	{
		$config = file_get_contents(REDIS_CONF);
		preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches);
		$this->redis = new RedisApi('localhost', $matches[1]);
		$this->redis->select(REDIS_DATABASE);

		// Flush redis
		$this->redis->flushAll();
	}
}

Fix tests after removal of prefix

Fix tests after removal of prefix


<?php

namespace App\Http\Controllers\Lead;

class LeadDeleteController
{

}

<?php

namespace App\Http\Controllers\Lead;

use Illuminate\Http\Request;
use App\Models\Lead;

class LeadDeleteController
{
    public function delete(Request $request, int $id)
    {
        $lead = Lead::find($id);
        $lead->delete();
        return redirect('/lead');
    }
}

Fix missing delete lead code

Fix missing delete lead code


<?php
Yii::app()->clientScript->registerCoreScript('jquery');
Yii::app()->clientScript->registerCSSFile('/css/theatre_calendar.css', 'all');
$patient = $operation->event->episode->patient; ?>

Patient: <?php echo $patient->first_name . ' ' . $patient->last_name . ' (' . $patient->hos_num . ')'; ?>

Cancel operation

<?php
echo CHtml::form(array('booking/cancelOperation'));
echo CHtml::hiddenField('operation_id', $operation->id);

echo CHtml::label('Cancellation Reason: ', 'cancellation_reason');
echo CHtml::dropDownList('cancellation_reason', '',
	CancellationReason::getReasonsByListNumber(1)
); ?>

<button type="submit" value="submit" class="shinybutton highlighted">Cancel operation</button>

<?php
echo CHtml::endForm(); ?>

<?php
Yii::app()->clientScript->registerCoreScript('jquery');
Yii::app()->clientScript->registerCSSFile('/css/theatre_calendar.css', 'all');
$patient = $operation->event->episode->patient; ?>

Patient: <?php echo $patient->first_name . ' ' . $patient->last_name . ' (' . $patient->hos_num . ')'; ?>

Cancel operation

<?php
echo CHtml::form(array('booking/cancelOperation'), 'post', array('id' => 'cancelForm'));
echo CHtml::hiddenField('operation_id', $operation->id); ?>

<?php
echo CHtml::label('Cancellation Reason: ', 'cancellation_reason');
echo CHtml::dropDownList('cancellation_reason', '',
	CancellationReason::getReasonsByListNumber(1),
	array('empty'=>'Select a reason')
); ?>

<button type="submit" value="submit" class="shinybutton highlighted">Cancel operation</button>

<?php
echo CHtml::endForm(); ?>

Add ajax validation to cancel operation so that reason is required


<?php
$post_id = get_the_ID();
$type = get_post_meta( $post_id, 'issue_category_type', true );
?>

<article <?php post_class(); ?>>

<?php the_title( sprintf( 'Report Issue: ') ); ?>

      <?php the_content(); ?>
      <?php if ($type == 'iframe'): ?>
        <iframe src="<?php echo get_post_meta( $post_id, 'iframe', true ); ?>" style="border:none;height:1500px;width:100%">
      <?php elseif($type == 'form'): ?>
        <?php gravity_form( get_post_meta( $post_id, 'form', true ), false, false ); ?>
      <?php else: ?>

      <?php endif ?>

<?php
$post_id = get_the_ID();
$type = get_post_meta( $post_id, 'issue_category_type', true );
?>

<article <?php post_class(); ?>>

<?php the_title( sprintf( _x( 'Report Issue: ', 'post prefix', 'wp-issue' )) ); ?>

      <?php the_content(); ?>
      <?php if ($type == 'iframe'): ?>
        <iframe src="<?php echo get_post_meta( $post_id, 'iframe', true ); ?>" style="border:none;height:1500px;width:100%">
      <?php elseif($type == 'form'): ?>
        <?php gravity_form( get_post_meta( $post_id, 'form', true ), false, false ); ?>
      <?php else: ?>

      <?php endif ?>

Allow Report Issue to label to be customized (changed to Service Request)


<?php

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

Route::get('/users', 'UserController@index');
Route::get('/users/{id}', 'UserController@show');
Route::get('/users/{id}/checkins', 'UserController@checkins');

Route::get('/places', 'PlaceController@index');
Route::get('/places/{id}', 'PlaceController@show');
Route::get('/places/{id}/checkins', 'PlaceController@getCheckins');
Route::get('/places/{id}/image', 'PlaceController@uploadImage');

<?php

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

Route::get('/users', 'UserController@index');
Route::get('/users/{id}', 'UserController@show');
Route::get('/users/{id}/checkins', 'UserController@getCheckins');

Route::get('/places', 'PlaceController@index');
Route::get('/places/{id}', 'PlaceController@show');
Route::get('/places/{id}/checkins', 'PlaceController@getCheckins');
Route::get('/places/{id}/image', 'PlaceController@uploadImage');

Update route file to use a method that exists


<?php

namespace Igniter\Flame\Setting;

use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;

class SettingServiceProvider extends ServiceProvider
{
    protected $defer = TRUE;

    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        $this->registerManager();

        $this->registerStores();

        $this->app->singleton(SaveSetting::class);
    }

    protected function registerManager()
    {
        $this->app->singleton('setting.manager', function ($app) {
            return new SettingManager($app);
        });
    }

    protected function registerStores()
    {
        $this->app->singleton('system.setting', function ($app) {
            return $app['setting.manager']->driver();
        });

        $this->app->singleton('system.parameter', function ($app) {
            return $app['setting.manager']->driver('prefs');
        });
    }
}

<?php

namespace Igniter\Flame\Setting;

use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;

class SettingServiceProvider extends ServiceProvider
{
    protected $defer = TRUE;

    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        $this->registerManager();

        $this->registerStores();

        $this->app->singleton(SaveSetting::class);
    }

    protected function registerManager()
    {
        $this->app->singleton('setting.manager', function ($app) {
            return new SettingManager($app);
        });
    }

    protected function registerStores()
    {
        $this->app->singleton('system.setting', function ($app) {
            return $app['setting.manager']->driver();
        });

        $this->app->singleton('system.parameter', function ($app) {
            return $app['setting.manager']->driver('prefs');
        });
    }

    public function provides()
    {
        return ['setting.manager', 'system.setting', 'system.parameter', SaveSetting::class];
    }
}

Fix system.setting does not exist

Fix system.setting does not exist

Signed-off-by: SamPoyigi <f16bed56189e249fe4ca8ed10a1ecae60e8ceac0@sampoyigi.com>


<?php

// create a custom menu option for the theme
function custom_menu() {
  register_nav_menu('header-menu',__( 'Header Menu'));
}
add_action( 'init', 'custom_menu');
?>

<?php

// create a custom menu option for the theme
function custom_menu() {
  register_nav_menu('header-menu',__( 'Header Menu'));
}
add_action( 'init', 'custom_menu');

// Custom header image
$args = array(
  'default-image' => '',
  'uploads'       => true,
);
add_theme_support('custom-header', $args );
?>

Remove header image default args

Remove header image default args


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set the fullBaseUrl to allow URLs to be generated in shell tasks.
// This is useful when sending email from shells.
//Configure::write('App.fullBaseUrl', php_uname('n'));

// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

try {
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set the fullBaseUrl to allow URLs to be generated in shell tasks.
// This is useful when sending email from shells.
//Configure::write('App.fullBaseUrl', php_uname('n'));

// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

try {
    Plugin::load('Migrations');
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

Add Migrations Plugin to bootrap_cli.php

Ref: https://github.com/cakephp/app/issues/452
Note: 2 PRs cause quick via GH.

While I like it to be optional, should it be outside the try block instead?


<?php
/**
 * the home page
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 */

get_header(); ?>

Anonymous friends
trusted face-to-face.

Create secure social networks using shared QR codes. Share them with whomever you trust, face-to-face.

				Download App

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Update download link and remove market image, for now.


<?php

namespace CloudCreativity\LaravelJsonApi\Eloquent;

use CloudCreativity\JsonApi\Contracts\Store\RelationshipAdapterInterface;
use Neomerx\JsonApi\Contracts\Encoder\Parameters\EncodingParametersInterface;

class MorphHasMany implements RelationshipAdapterInterface
{

    /**
     * @var HasMany[]
     */
    private $adapters;

    /**
     * MorphToManyAdapter constructor.
     *
     * @param HasMany[] ...$adapters
     */
    public function __construct(HasMany ...$adapters)
    {
        $this->adapters = $adapters;
    }

    /**
     * @inheritDoc
     */
    public function queryRelated($record, EncodingParametersInterface $parameters)
    {
        $all = collect();

        foreach ($this->adapters as $adapter) {
            $all = $all->merge($adapter->queryRelated($record, $parameters));
        }

        return $all;
    }

    /**
     * @inheritDoc
     */
    public function queryRelationship($record, EncodingParametersInterface $parameters)
    {
        $all = collect();

        foreach ($this->adapters as $adapter) {
            $all = $all->merge($adapter->queryRelationship($record, $parameters));
        }

        return $all;
    }

}

<?php

namespace CloudCreativity\LaravelJsonApi\Eloquent;

use CloudCreativity\JsonApi\Contracts\Store\RelationshipAdapterInterface;
use Neomerx\JsonApi\Contracts\Encoder\Parameters\EncodingParametersInterface;

class MorphHasMany implements RelationshipAdapterInterface
{

    /**
     * @var HasMany[]
     */
    private $adapters;

    /**
     * MorphToManyAdapter constructor.
     *
     * @param HasMany[] ...$adapters
     */
    public function __construct(HasMany ...$adapters)
    {
        $this->adapters = $adapters;
    }

    /**
     * Set the relationship name.
     *
     * @param $name
     * @return $this
     */
    public function withRelationshipName($name)
    {
        foreach ($this->adapters as $adapter) {
            if (method_exists($adapter, 'withRelationshipName')) {
                $adapter->withRelationshipName($name);
            }
        }

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function queryRelated($record, EncodingParametersInterface $parameters)
    {
        $all = collect();

        foreach ($this->adapters as $adapter) {
            $all = $all->merge($adapter->queryRelated($record, $parameters));
        }

        return $all;
    }

    /**
     * @inheritDoc
     */
    public function queryRelationship($record, EncodingParametersInterface $parameters)
    {
        $all = collect();

        foreach ($this->adapters as $adapter) {
            $all = $all->merge($adapter->queryRelationship($record, $parameters));
        }

        return $all;
    }

}

[Feature-WIP] Add a minor change to the morph has many relation


<?php

/*
 * Plugin Name: Hide Menu
 * Plugin URI: http://pothi.info
 * Author: Pothi Kalimuthu
 * Author URI: http://pothi.info
 * Description: Hides unneccessary menu item/s
 * Version: 1.0
 * License: Apache 2.0
 */

function tiny_remove_menus() {
    // Hide Ewww image optimizer settings that are found in two places
    $page = remove_submenu_page( 'options-general.php', 'ewww-image-optimizer/ewww-image-optimizer.php' );
    $page = remove_submenu_page( 'tools.php', 'ewww-image-optimizer-aux-images' );
}
add_action( 'admin_menu', 'tiny_remove_menus', 999 );

<?php

/*
 * Plugin Name: Hide Menu
 * Plugin URI: http://pothi.info
 * Author: Pothi Kalimuthu
 * Author URI: http://pothi.info
 * Description: Hides unneccessary menu item/s
 * Version: 1.0
 * License: Apache 2.0
 */

function tiny_remove_menus() {
    // Hide Ewww image optimizer settings that are found in four places
    $page = remove_submenu_page( 'options-general.php', 'ewww-image-optimizer/ewww-image-optimizer.php' );
    $page = remove_submenu_page( 'tools.php', 'ewww-image-optimizer-aux-images' );
    $page = remove_submenu_page( 'themes.php', 'ewww-image-optimizer-theme-images' );
    $page = remove_submenu_page( 'upload.php', 'ewww-image-optimizer-bulk' );
}
add_action( 'admin_menu', 'tiny_remove_menus', 999 );

Hide two more settings menu from ewww image optimizer


<?php

namespace Michaeljennings\Snapshot\Listeners;

use League\Event\EventInterface;
use Maknz\Slack\Client;
use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException;

class SendToSlack extends Listener
{
    /**
     * Check if slack is enabled, if so send the snapshot to the relevant
     * channel.
     *
     * @param EventInterface $event
     * @throws EndPointNotSetException
     */
    public function handle(EventInterface $event)
    {
        if ($this->config['slack']['enabled']) {
            if (empty($this->config['slack']['endpoint'])) {
                throw new EndPointNotSetException("You must set the endpoint for your slack channel.");
            }

            $client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']);

            $client->send($this->getMessage($event->getSnapshot()));
        }
    }

    /**
     * Get the slack message for the snapshot. If you wish to use markdown
     * then set the allow_markdown config option to true.
     *
     * @param mixed $snapshot
     * @return string
     */
    protected function getMessage($snapshot)
    {
        return 'A new snapshot has been captured. #' . $snapshot->getId();
    }
}

<?php

namespace Michaeljennings\Snapshot\Listeners;

use League\Event\EventInterface;
use Maknz\Slack\Client;
use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException;

class SendToSlack extends Listener
{
    /**
     * Check if slack is enabled, if so send the snapshot to the relevant
     * channel.
     *
     * @param EventInterface $event
     * @throws EndPointNotSetException
     */
    public function handle(EventInterface $event)
    {
        if ($this->config['slack']['enabled']) {
            if (empty($this->config['slack']['endpoint'])) {
                throw new EndPointNotSetException("You must set the endpoint for your slack channel.");
            }

            $client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']);

            $client->send($this->getMessage($event->getSnapshot()));
        }
    }

    /**
     * Get the slack message for the snapshot. If you wish to use markdown
     * then set the allow_markdown config option to true.
     *
     * @param mixed $snapshot
     * @return string
     */
    protected function getMessage($snapshot)
    {
        return '#' . $snapshot->getId() . ' A new snapshot has been captured';
    }
}

Update the default send to slack message


<?php

namespace Expressly\Event;

use Buzz\Message\Response;
use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

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

    public function setResponse(Response $response)
    {
        $this->response = $response;

        return $this;
    }

    public function isSuccessful()
    {
        if (!$this->response instanceof Response) {
            return false;
        }

        return $this->response->isSuccessful();
    }

    public function getContent()
    {
        if (!$this->response instanceof Response) {
            return null;
        }

        $content = $this->response->getContent();
        if (is_array($content)) {
            return $content;
        }

        $json = json_decode($content, true);

        return (json_last_error() == JSON_ERROR_NONE) ? $json : $content;
    }
}

<?php

namespace Expressly\Event;

use Buzz\Message\Response;
use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

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

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }

    public function isSuccessful()
    {
        if (!$this->response instanceof Response) {
            return false;
        }

        return $this->response->isSuccessful();
    }

    public function getContent()
    {
        if (!$this->response instanceof Response) {
            return null;
        }

        $content = $this->response->getContent();
        if (is_array($content)) {
            return $content;
        }

        $json = json_decode($content, true);

        return (json_last_error() == JSON_ERROR_NONE) ? $json : $content;
    }
}

Remove typecast on setting Response

Remove typecast on setting Response


<?php

/**
 * This file is part of the Tarantool Client package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Tarantool\Client\Packer;

final class PacketLength
{
    public const SIZE_BYTES = 5;

    private function __construct()
    {
    }

    public static function pack(int $length) : string
    {
        return \pack('CN', 0xce, $length);
    }

    public static function unpack(string $data) : int
    {
        if (false === $data = @\unpack('C/N', $data)) {
            throw new \RuntimeException('Unable to unpack packet length.');
        }

        return $data[1];
    }
}

<?php

/**
 * This file is part of the Tarantool Client package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Tarantool\Client\Packer;

final class PacketLength
{
    public const SIZE_BYTES = 5;

    private function __construct()
    {
    }

    public static function pack(int $length) : string
    {
        return \pack('CN', 0xce, $length);
    }

    public static function unpack(string $data) : int
    {
        if (!isset($data[4]) || "\xce" !== $data[0]) {
            throw new \RuntimeException('Unable to unpack packet length.');
        }

        return \ord($data[1]) << 24
            | \ord($data[2]) << 16
            | \ord($data[3]) << 8
            | \ord($data[4]);
    }
}

Optimize unpacking the packet length

Optimize unpacking the packet length


<?php

/**
 * Input receiver for SMTP server piping
 * In your application file: list($message, $additionalData) = require('$path_to_smp/includes/message-pipe.php');
 * Usage for Exim4 filter file: pipe "php $path_to_bin/your_application.php $sender_address"
 * Raw mail body given on STDIN
 */

if ($argc < 2) {
    die("Sender address required as the first parameter\n");
}
$senderAddress = $argv[1];

$rawMessage = file_get_contents('php://stdin');
if ($rawMessage === false) {
    die("Can't read standard input to get message body\n");
}
if (count($rawMessage) < 1) {
    die("Message body (read from standard input) is empty\n");
}

$rawClearedMessage = substr($rawMessage, strpos($rawMessage, "\n") + 1);
$message = \Feedbee\Smp\Mail\Message::fromString($rawClearedMessage);

return [$message, ['sender_address' => $senderAddress]];

<?php

/**
 * Input receiver for SMTP server piping
 * In your application file: list($message, $additionalData) = require('$path_to_smp/includes/message-pipe.php');
 * Usage for Exim4 filter file: pipe "php $path_to_bin/your_application.php $sender_address"
 * Raw mail body given on STDIN
 */

if ($argc < 2) {
    die("Sender address required as the first parameter\n");
}
$senderAddress = $argv[1];

$rawMessage = file_get_contents('php://stdin');
if ($rawMessage === false) {
    die("Can't read standard input to get message body\n");
}
if (strlen($rawMessage) < 1) {
    die("Message body (read from standard input) is empty\n");
}

$rawClearedMessage = substr($rawMessage, strpos($rawMessage, "\n") + 1);
$message = \Feedbee\Smp\Mail\Message::fromString($rawClearedMessage);

return [$message, ['sender_address' => $senderAddress]];

Fix count -> strlen bug

Fix count -> strlen bug


<?php
/**
 * Validate class existence.
 *
 * @package HylianShield
 * @subpackage Validator
 * @copyright 2013 Jan-Marten "Joh Man X" de Boer
 */

namespace HylianShield\Validator\CoreClass;

/**
 * Exists.
 */
class Exists extends \HylianShield\Validator
{
    /**
     * The type.
     *
     * @var string $type
     */
    protected $type = 'class_exists';

    /**
     * The validator.
     *
     * @var callable $validator
     */
    protected $validator = 'class_exists';
}

<?php
/**
 * Validate class existence.
 *
 * @package HylianShield
 * @subpackage Validator
 * @copyright 2013 Jan-Marten "Joh Man X" de Boer
 */

namespace HylianShield\Validator\CoreClass;

use \InvalidArgumentException;
use \HylianShield\Validator\Boolean;

/**
 * Exists.
 */
class Exists extends \HylianShield\Validator
{
    /**
     * The type.
     *
     * @var string $type
     */
    protected $type = 'class_exists';

    /**
     * Create a validator that checks if a class exists.
     *
     * @param boolean $useAutoloader whether to use the autoloader
     * @throws \InvalidArgumentException when the supplied argument is not a boolean
     */
    public function __construct($useAutoloader = true)
    {
        $boolean = new Boolean;
        if (!$boolean($useAutoloader)) {
            throw new InvalidArgumentException(
                'Supplied argument is not a boolean: ' . gettype($useAutoloader)
                . ') ' . var_export($useAutoloader, true)
            );
        }

        // Add a wrapper around class exists, so we can tell when to use the autoloader.
        $this->validator = function ($class) use ($useAutoloader) {
            return class_exists($class, $useAutoloader);
        };
    }
}

Use the autoloader by default

Use the autoloader by default


<?php

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

class CreatePostsTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('posts', function (Blueprint $table)
		{
			$table->increments('id');
			$table->string('title');
			$table->string('summary')->nullable();
			$table->integer('minutes_read')->nullable();
			$table->longText('content');
			$table->timestamps();

			$table->integer('author_id')->unsigned()->index();
			$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
		});
	}

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

<?php

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

class CreatePostsTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('posts', function (Blueprint $table)
		{
			$table->increments('id');
			$table->string('title');
			$table->mediumText('summary')->nullable();
			$table->integer('minutes_read')->nullable();
			$table->longText('content');
			$table->timestamps();

			$table->integer('author_id')->unsigned()->index();
			$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
		});
	}

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

Use medium text to store posts summary.

Use medium text to store posts summary.


<?php

namespace OParl\Website\Api\Controllers;

use function Swagger\scan;

/**
 * @SWG\Swagger(
 *     schemes={"https"},
 *     host="dev.oparl.org",
 *     basePath="/api/",
 *     @SWG\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @SWG\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     ),
 *     produces={ "application/json" }
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function swaggerJson()
    {
        $swagger = scan(base_path('lib/Api/Controllers'));

        return response($swagger, 200, [
            'Content-Tyype'               => 'application/json',
            'Access-Control-Allow-Origin' => '*',
        ]);
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

<?php

namespace OParl\Website\Api\Controllers;

use function Swagger\scan;

/**
 * @SWG\Swagger(
 *     schemes={"https"},
 *     host="dev.oparl.org",
 *     basePath="/api/",
 *     @SWG\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @SWG\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     ),
 *     produces={ "application/json" }
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function swaggerJson()
    {
        $swagger = scan(base_path('lib/Api/Controllers'));

        return response($swagger, 200, [
            'Content-Type'               => 'application/json',
            'Access-Control-Allow-Origin' => '*',
        ]);
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

Fix typo in content type

Fix typo in content type


<?php

namespace PHPOrchestra\ModelBundle\EventListener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs;
use PHPOrchestra\ModelBundle\Model\StatusInterface;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class SavePublishedDocumentListener
 */
class SavePublishedDocumentListener
{
    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function preUpdate(LifecycleEventArgs $eventArgs)
    {
        $document = $eventArgs->getDocument();
        if ($document instanceof StatusableInterface) {
            $status = $document->getStatus();
            if (! empty($status)
                 && $status->isPublished()
                 && (!method_exists($document, 'isDeleted') || ! $document->isDeleted())
            ) {
                     $documentManager = $eventArgs->getDocumentManager();
                     $documentManager->getUnitOfWork()->detach($document);
            }
        }
    }
}

<?php

namespace PHPOrchestra\ModelBundle\EventListener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs;
use PHPOrchestra\ModelBundle\Model\StatusInterface;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class SavePublishedDocumentListener
 */
class SavePublishedDocumentListener
{
    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function preUpdate(LifecycleEventArgs $eventArgs)
    {
        $document = $eventArgs->getDocument();
        if ($document instanceof StatusableInterface) {
            $status = $document->getStatus();
            if (!empty($status)
                 && $status->isPublished()
                 && (!method_exists($document, 'isDeleted') || ! $document->isDeleted())
            ) {
                     $documentManager = $eventArgs->getDocumentManager();
                     $documentManager->getUnitOfWork()->detach($document);
            }
        }
    }
}

Add read only functionnality on published node


<?php __('plain'); ?>

<?php __('DATE \a\t TIME'); ?>

<?php __("DATE \a\\t TIME"); ?>

<?php __("DATE \\a\\t TIME"); ?>

<?php __("FIELD\tFIELD"); ?>

<?php __(
        "text "
        // test
        .'concatenated'.
        /* test*/ " with 'comments'"
    ); ?>

<?php __($avoid['me']); ?>

<?php __('Stop at the variable'.$var.'!'); ?>

<?php __ ( 'plain' ); ?>

<?php __('DATE \a\t TIME'); ?>

<?php __("DATE \a\\t TIME"); ?>

<?php __("DATE \\a\\t TIME"); ?>

<?php __("FIELD\tFIELD"); ?>

<?php __(
        "text "
        // test
        .'concatenated'.
        /* test*/ " with 'comments'"
    ); ?>

<?php __($avoid['me']); ?>

<?php __('Stop at the variable'.$var.'!'); ?>

Add space after function name

Add space after function name