<?php namespace Anomaly\UsersModule\Role;

use Anomaly\Streams\Platform\Entry\EntryCollection;
use Anomaly\UsersModule\Role\Contract\RoleInterface;

/**
 * Class RoleCollection
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class RoleCollection extends EntryCollection
{

    /**
     * Return all permissions.
     *
     * @return array
     */
    public function permissions()
    {
        return $this->map(
            function (RoleInterface $role) {
                return $role->getPermissions();
            }
        )->flatten()->all();
    }

    /**
     * Return if a role as access to a the permission.
     *
     * @param  string $permission
     * @return RoleCollection
     */
    public function hasPermission($permission)
    {
        return $this->filter(
            function (RoleInterface $role) use ($permission) {
                return $role->hasPermission($permission);
            }
        );
    }
}

<?php namespace Anomaly\UsersModule\Role;

use Anomaly\Streams\Platform\Entry\EntryCollection;
use Anomaly\UsersModule\Role\Contract\RoleInterface;

/**
 * Class RoleCollection
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class RoleCollection extends EntryCollection
{

    /**
     * Return all permissions.
     *
     * @return array
     */
    public function permissions()
    {
        return $this->map(
            function (RoleInterface $role) {
                return $role->getPermissions();
            }
        )->flatten()->all();
    }

    /**
     * Return if a role as access to a the permission.
     *
     * @param  string $permission
     * @return RoleCollection
     */
    public function hasPermission($permission)
    {
        return $this->filter(
            function (RoleInterface $role) use ($permission) {
                return $role->hasPermission($permission);
            }
        );
    }

    /**
     * Return if the role exists or not.
     *
     * @param $role
     * @return bool
     */
    public function hasRole($role)
    {
        return (bool)$this->first(
            function ($item) use ($role) {

                /* @var RoleInterface $item */
                return $item->getSlug() == $role;
            }
        );
    }
}

Add method to check for role by slug since they're not keyed that way anymore.


<?php

namespace Camspiers\StatisticalClassifier\Classifier;

use Camspiers\StatisticalClassifier\DataSource\DataArray;

class SVMTest extends \PHPUnit_Framework_TestCase
{
    public function testClassify()
    {
        $dataSource = new DataArray();
        $dataSource->addDocument('spam', 'Some spam');
        $dataSource->addDocument('ham', 'Some ham');

        $classifier = new SVM($dataSource);

        $this->assertEquals('spam', $classifier->classify('Some spam'));
        $this->assertEquals('ham', $classifier->classify('Some ham'));
    }
}

<?php

namespace Camspiers\StatisticalClassifier\Classifier;

use Camspiers\StatisticalClassifier\DataSource\DataArray;

/**
 * Class SVMTest
 * @package Camspiers\StatisticalClassifier\Classifier
 * @group svm
 */
class SVMTest extends \PHPUnit_Framework_TestCase
{
    public function testClassify()
    {
        $dataSource = new DataArray();
        $dataSource->addDocument('spam', 'Some spam');
        $dataSource->addDocument('ham', 'Some ham');

        $classifier = new SVM($dataSource);

        $this->assertEquals('spam', $classifier->classify('Some spam'));
        $this->assertEquals('ham', $classifier->classify('Some ham'));
    }
}

Add SVM test to group

UPDATE: Add SVM test to group


<?php
namespace PhpDDD\Notification;

use Exception;

/**
 * This class is for internal purpose only
 */
class Error
{

    /**
     * @var string
     */
    private $message;

    /**
     * @var Exception
     */
    private $cause;

    /**
     * @param string         $message
     * @param Exception|null $cause
     */
    public function __construct($message, Exception $cause = null)
    {
        if (!is_string($message)) {
            throw new InvalidArgumentException('The first parameter of Error must be a string.');
        }
        $this->message = $message;
        $this->cause   = $cause;
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }
}

<?php
namespace PhpDDD\Notification;

/**
 * This class is for internal purpose only
 */
class Error
{
    /**
     * @var string
     */
    private $message;

    /**
     * @param string         $message
     */
    public function __construct($message)
    {
        if (!is_string($message)) {
            throw new InvalidArgumentException('The first parameter of Error must be a string.');
        }
        $this->message = $message;
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }
}

Remove the $cause parameter as it is not used


<?php

namespace Silly\Input;

/**
 * Extending InputArgument because...
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class InputArgument extends \Symfony\Component\Console\Input\InputArgument
{
    private $description;

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription()
    {
        return $this->description ?: parent::getDescription();
    }
}

<?php

namespace Silly\Input;

/**
 * Extending InputArgument because...
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class InputArgument extends \Symfony\Component\Console\Input\InputArgument
{
    private $description;

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription(): string
    {
        return $this->description ?: parent::getDescription();
    }
}

Add return types preparing for upgrade of parent.


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for apply Mimic library function.
 *
 * @since 0.1.0
 */
class ApplyFuncTest extends PHPUnit_Framework_TestCase {

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testApplyExecutesClosure() {
		$this->assertTrue(F\apply(function() {return true; }));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_FileDoesNotExist() {
		$this->assertFalse(F\apply(
			F\wrap('file_exists', __DIR__ . '/nonexistantfile.doesnotexist')
		));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_DirectoryExists() {
		$this->assertTrue(F\apply(F\wrap('file_exists', __DIR__)));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_FileExists() {
		$this->assertTrue(F\apply(F\wrap('file_exists', __FILE__)));
	}
}

<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for apply Mimic library function.
 *
 * @since 0.1.0
 */
class ApplyFuncTest extends PHPUnit_Framework_TestCase {

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testApplyExecutesClosure() {
		$this->assertTrue(F\apply(function() {return true; }));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_FileDoesNotExist() {
		$this->assertFalse(F\apply(
			F\wrap('file_exists', __DIR__ . '/nonexistantfile.doesnotexist')
		));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testWrappedFileExistsFunction_DirectoryExists() {
		$this->assertTrue(F\apply(F\wrap('file_exists', __DIR__)));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testWrappedFileExistsFunction_FileExists() {
		$this->assertTrue(F\apply(F\wrap('file_exists', __FILE__)));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_DirectoryExists() {
		$this->assertTrue(F\apply('file_exists', __DIR__));
	}

	/**
	 * @covers ::Mimic\Functional\apply
	 */
	public function testFileExistsFunction_FileExists() {
		$this->assertTrue(F\apply('file_exists', __FILE__));
	}
}

Add additional tests for parameters that complete code coverage for apply function.


<?php

namespace MillerVein\Component\Form\DataTransformer;

use DateTime;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 *
 * @author Nick Fenzan <nickf@millervein.com>
 */
class TwentyFourToTwelveHourArray implements DataTransformerInterface{
    public function reverseTransform($value) {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new UnexpectedTypeException($value, 'array');
        }

        if($value['ampm'] == 'PM' && $value['hour']>0){
            $value['hour'] = $value['hour'] + 12;
        }
        unset($value['ampm']);
        return $value;
    }

    public function transform($value) {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new UnexpectedTypeException($value, 'array');
        }

        if($value['hour'] === 0){
            $value['hour'] = 12;
            $value['ampm'] = 'AM';
        }elseif($value['hour']<12){
            $value['ampm'] = 'AM';
        }else{
            $value['hour'] = $value['hour'] - 12;
            $value['ampm'] = 'PM';
        }

        return $value;
    }

}

<?php

namespace MillerVein\Component\Form\DataTransformer;

use DateTime;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 *
 * @author Nick Fenzan <nickf@millervein.com>
 */
class TwentyFourToTwelveHourArray implements DataTransformerInterface{
    public function reverseTransform($value) {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new UnexpectedTypeException($value, 'array');
        }

        if($value['ampm'] == 'AM'){
            if($value['hour'] == 12){
                $value['hour'] = 0;
            }
        }else{
            if($value['hour'] != 12){
                $value['hour'] = $value['hour'] + 12;
            }
        }
        unset($value['ampm']);
        return $value;
    }

    public function transform($value) {
        if (null === $value) {
            return null;
        }

        if (!is_array($value)) {
            throw new UnexpectedTypeException($value, 'array');
        }

        if($value['hour'] === 0){
            $value['hour'] = 12;
            $value['ampm'] = 'AM';
        }elseif($value['hour']<12){
            $value['ampm'] = 'AM';
        }else{
            $value['hour'] = $value['hour'] - 12;
            $value['ampm'] = 'PM';
        }

        return $value;
    }

}

Fix bug with clock roll over.

Fix bug with clock roll over.


<?php

namespace atk4\data\tests\smbo;

class SMBOTestCase extends \atk4\data\tests\SQLTestCase
{
    public function setUp()
    {
        parent::setUp();

        $s = new \atk4\data\tests\Structure(['connection' => $this->db->connection]);

        $x = clone $s;
        $x->table('account')->drop()
            ->id()
            ->field('name')
            ->create();

        $x = clone $s;
        $x->table('document')->drop()
            ->id()
            ->field('reference')
            ->field('contact_from_id')
            ->field('contact_to_id')
            ->field('doc_type')
            ->field('amount', ['type' => 'decimal(8,2)'])
            ->create();

        $x = clone $s;
        $x->table('payment')->drop()
            ->id()
            ->field('document_id', ['type' => 'integer'])
            ->field('account_id', ['type' => 'integer'])
            ->field('cheque_no')
            ->field('misc_payment', ['type' => 'enum("N","Y")'])
            ->field('transfer_document_id')
            ->create();
    }
}

<?php

namespace atk4\data\tests\smbo;

class SMBOTestCase extends \atk4\data\tests\SQLTestCase
{
    public function setUp()
    {
        parent::setUp();
        $queryClass = $this->getProtected($this->db->connection, 'query_class');
        $escapeChar = $this->getProtected(new $queryClass, 'escape_char');

        $s = new \atk4\data\tests\Structure(['connection' => $this->db->connection]);
        $s->setEscapeChar($escapeChar);

        $x = clone $s;
        $x->table('account')->drop()
            ->id()
            ->field('name')
            ->create();

        $x = clone $s;
        $x->table('document')->drop()
            ->id()
            ->field('reference')
            ->field('contact_from_id')
            ->field('contact_to_id')
            ->field('doc_type')
            ->field('amount', ['type' => 'decimal(8,2)'])
            ->create();

        $x = clone $s;
        $x->table('payment')->drop()
            ->id()
            ->field('document_id', ['type' => 'integer'])
            ->field('account_id', ['type' => 'integer'])
            ->field('cheque_no')
            //->field('misc_payment', ['type' => 'enum(\'N\',\'Y\')'])
            ->field('misc_payment', ['type' => 'varchar(2)'])
            ->field('transfer_document_id')
            ->create();
    }
}

Use a varchar instead of an enum. Enums are not supported in sqlite and on postgresql it requires extra work to use


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

namespace Flarum\Core\Notifications\Commands;

use Flarum\Core\Notifications\Notification;
use Flarum\Core\Exceptions\PermissionDeniedException;
use Flarum\Core\Support\DispatchesEvents;

class ReadNotificationHandler
{
    /**
     * @param ReadNotification $command
     * @return Notification
     * @throws \Flarum\Core\Exceptions\PermissionDeniedException
     */
    public function handle(ReadNotification $command)
    {
        $actor = $command->actor;

        if ($actor->isGuest()) {
            throw new PermissionDeniedException;
        }

        $notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId);

        $notification->read();
        $notification->save();

        return $notification;
    }
}

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

namespace Flarum\Core\Notifications\Commands;

use Flarum\Core\Notifications\Notification;
use Flarum\Core\Exceptions\PermissionDeniedException;
use Flarum\Core\Support\DispatchesEvents;

class ReadNotificationHandler
{
    /**
     * @param ReadNotification $command
     * @return Notification
     * @throws \Flarum\Core\Exceptions\PermissionDeniedException
     */
    public function handle(ReadNotification $command)
    {
        $actor = $command->actor;

        if ($actor->isGuest()) {
            throw new PermissionDeniedException;
        }

        $notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId);

        Notification::where([
            'user_id' => $actor->id,
            'type' => $notification->type,
            'subject_id' => $notification->subject_id
        ])
            ->update(['is_read' => true]);

        return $notification;
    }
}

Mark all notifications with the same subject as read


@if(Session::get('selected.business_id'))

{!! Icon::home() !!} {{ trans('app.nav.manager.business.dashboard') }}

@endif

	{{ trans('app.nav.manager.business.menu') }}

{{ trans('app.nav.manager.business.list') }}

{{ trans('app.nav.manager.business.register') }}

{!! Form::open(['method' => 'post', 'url' => '/manager/search/', 'class' => 'navbar-form navbar-left', 'role' => 'search']) !!}

  <input name="criteria" type="text" class="form-control" placeholder="...">

{!! Form::close() !!}

@if($business = Session::get('selected.business'))

id) }}">{!! Icon::home() !!} {{ $business->name }}

@endif

	{{ trans('app.nav.manager.business.menu') }}

{{ trans('app.nav.manager.business.list') }}

{{ trans('app.nav.manager.business.register') }}

{!! Form::open(['method' => 'post', 'url' => '/manager/search/', 'class' => 'navbar-form navbar-left', 'role' => 'search']) !!}

  <input name="criteria" type="text" class="form-control" placeholder="...">

{!! Form::close() !!}

Fix selected business retrieval from session


<?php
/**
 * Created by PhpStorm.
 * User: ylly
 * Date: 16/10/15
 * Time: 19:01
 */

namespace ESN\PermanenceBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ReportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('amountBefore', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3'
                )
            ))
            ->add('amountAfter', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3'
                )
            ))
            ->add('sellCard', 'integer', array(
                'attr' => array(
                    'class' => 'span3',
                    'min' => 1
                )
            ))
            ->add('availableCard', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3',
                    'min' => 1
                )
            ))
            ->add('comments', 'textarea')
            ;
    }

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

<?php
/**
 * Created by PhpStorm.
 * User: ylly
 * Date: 16/10/15
 * Time: 19:01
 */

namespace ESN\PermanenceBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ReportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('amountBefore', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3'
                )
            ))
            ->add('amountAfter', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3'
                )
            ))
            ->add('sellCard', 'integer', array(
                'attr' => array(
                    'class' => 'span3',
                    'min' => 0
                )
            ))
            ->add('availableCard', 'integer', array(
                'attr' => array(
                    'readonly' => true,
                    'class' => 'span3',
                    'min' => 1
                )
            ))
            ->add('comments', 'textarea')
            ;
    }

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

Remove min 1 from reporttype

Remove min 1 from reporttype


<?php

namespace AlexaPHP\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\ServiceProvider;

class AlexaServiceProvider extends ServiceProvider
{

	/**
	 * Register any other events for your application.
	 *
	 * @param  \Illuminate\Contracts\Events\Dispatcher $events
	 * @return void
	 */
	public function boot(DispatcherContract $events)
	{
		parent::boot($events);

		$this->publishes(
			[
				__DIR__ . '../config/alexaphp.php' => config_path('alexaphp.php'),
			]
		);
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		// pass
	}
}

<?php

namespace AlexaPHP\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\ServiceProvider;

class AlexaServiceProvider extends ServiceProvider
{

	/**
	 * Register any other events for your application.
	 *
	 * @param  \Illuminate\Contracts\Events\Dispatcher $events
	 * @return void
	 */
	public function boot(DispatcherContract $events)
	{
		parent::boot($events);

		$this->publishes(
			[
				__DIR__ . '/../config/alexaphp.php' => config_path('alexaphp.php'),
			]
		);
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		// pass
	}
}

Add missing slash to config directory

Add missing slash to config directory


<?php
/**
 * @title            Provider Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Payment / Gateway / Api
 * @version          1.0
 */

namespace PH7\Framework\Payment\Gateway\Api;

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

abstract class Provider
{
    protected $aParams = array();

    /**
     * @param string $sName
     * @param string $sValue
     *
     * @return object this
     */
    public function param($sName, $sValue)
    {
        $this->aParams[$sName] = $sValue;
        return $this;
    }

    /**
     * Generate Output.
     *
     * @return string HTML tags
     */
    public function generate()
    {
        $sHtml = ''; // Default Value

        foreach ($this->aParams as $sKey => $sVal)
            $sHtml .= "<input type=\"hidden\" name=\"$sKey\" value=\"$sVal\" />\n";

        return $sHtml;
    }
}

<?php
/**
 * @title            Provider Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Payment / Gateway / Api
 * @version          1.0
 */

namespace PH7\Framework\Payment\Gateway\Api;

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

abstract class Provider
{
    protected $aParams = array();

    /**
     * @param string $sName
     * @param string $sValue
     *
     * @return self
     */
    public function param($sName, $sValue)
    {
        $this->aParams[$sName] = $sValue;

        return $this;
    }

    /**
     * Generate Output.
     *
     * @return string HTML tags
     */
    public function generate()
    {
        $sHtml = ''; // Default Value

        foreach ($this->aParams as $sKey => $sVal)
            $sHtml .= "<input type=\"hidden\" name=\"$sKey\" value=\"$sVal\" />\n";

        return $sHtml;
    }
}

Fix wrong return phpdoc value

Fix wrong return phpdoc value


<?php

namespace LaravelFlare\Cms;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class CmsServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot(Router $router)
    {
        $router->middleware('checkslugexists', 'LaravelFlare\Cms\Http\Middleware\CheckSlugExists');

        $this->publishes([
            __DIR__.'/Database/Migrations' => base_path('database/migrations'),
        ]);

        // Routes
        if (!$this->app->routesAreCached()) {
            require __DIR__.'/Http/routes.php';
        }

        // Views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'flare');
        $this->publishes([
            __DIR__.'/../resources/views' => base_path('resources/views/vendor/flare'),
        ]);

        $this->registerBladeOperators();
    }

    /**
     * Register any package services.
     */
    public function register()
    {
        $this->registerServiceProviders();
    }

    /**
     * Register Service Providers.
     */
    protected function registerServiceProviders()
    {
    }

    /**
     * Register Blade Operators.
     */
    protected function registerBladeOperators()
    {
    }
}

<?php

namespace LaravelFlare\Cms;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class CmsServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot(Router $router)
    {
        $router->middleware('checkslugexists', 'LaravelFlare\Cms\Http\Middleware\CheckSlugExists');

        $this->publishes([
            __DIR__.'/Database/Migrations' => base_path('database/migrations'),
        ]);

        // Routes
        if (!$this->app->routesAreCached()) {
            require __DIR__.'/Http/routes.php';
        }

        // Views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'flare');
        $this->publishes([
            __DIR__.'/../resources/views' => base_path('resources/views/vendor/flare'),
        ]);
    }

    /**
     * Register any package services.
     */
    public function register()
    {
    }

    /**
     * Register Service Providers.
     */
    protected function registerServiceProviders()
    {
    }

    /**
     * Register Blade Operators.
     */
    protected function registerBladeOperators()
    {
    }
}

Remove unused method calls in ServiceProvider


<?php
// Database
// Name              : MySQL (PDO)
// Dependencies      : php;pdo_mysql
// Required          : server username database
// Optional          : password tablePrefix
/**
 * PDO MySQL database driver
 * @package Jivoo\Database\PdoMysql
 */
class PdoMysqlDatabase extends PdoDatabase {

  /**
   * Constructor.
   * @param array $options An associative array with options for at least
   * 'server', 'username', 'password' and 'database'. 'tablePrefix' is optional.
   * @throws DatabaseConnectionFailedException if connection fails
   */
  public function init($options = array()) {
    $this->setTypeAdapter(new MysqlTypeAdapter($this));
    if (isset($options['tablePrefix'])) {
      $this->tablePrefix = $options['tablePrefix'];
    }
    try {
      $this->pdo = new PDO(
        'mysql:host=' . $options['server'] . ';dbname=' . $options['database'],
        $options['username'], $options['password']);
    }
    catch (DatabaseQueryFailedException $exception) {
      throw new DatabaseConnectionFailedException($exception->getMessage());
    }
    catch (PDOException $exception) {
      throw new DatabaseConnectionFailedException($exception->getMessage());
    }
  }
}

<?php
// Database
// Name              : MySQL (PDO)
// Dependencies      : php;pdo_mysql
// Required          : server username database
// Optional          : password tablePrefix
/**
 * PDO MySQL database driver
 * @package Jivoo\Database\PdoMysql
 */
class PdoMysqlDatabase extends PdoDatabase {

  /**
   * Constructor.
   * @param array $options An associative array with options for at least
   * 'server', 'username', 'password' and 'database'. 'tablePrefix' is optional.
   * @throws DatabaseConnectionFailedException if connection fails
   */
  public function init($options = array()) {
    $this->setTypeAdapter(new MysqlTypeAdapter($this));
    if (isset($options['tablePrefix'])) {
      $this->tablePrefix = $options['tablePrefix'];
    }
    try {
      if (isset($options['password'])) {
        $this->pdo = new PDO(
          'mysql:host=' . $options['server'] . ';dbname=' . $options['database'],
          $options['username'], $options['password']);
      }
      else {
        $this->pdo = new PDO(
          'mysql:host=' . $options['server'] . ';dbname=' . $options['database'],
          $options['username']);
      }
    }
    catch (DatabaseQueryFailedException $exception) {
      throw new DatabaseConnectionFailedException($exception->getMessage());
    }
    catch (PDOException $exception) {
      throw new DatabaseConnectionFailedException($exception->getMessage());
    }
  }
}

Fix silent PDO construction failure when password not set


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Terramar\Packages\Application;

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

Symfony\Component\Debug\Debug::enable();

$app = new Application('dev', true);
$app->run();

<?php

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

$app = new Terramar\Packages\Application('prod', false);
$app->run();

Index page is much more production-centric


                <?php if (!dynamic_sidebar("Footer Left")) { ?>

<?php wp_list_bookmarks(); ?>

Meta

                        <?php wp_meta(); ?>

<a href="<?php bloginfo("rss_url"); ?>">RSS feed

Using NightSkyLine theme

                                Powered by WordPress

                <?php } ?>

                <?php if (!dynamic_sidebar("Footer Right")) { ?>

Search

                        <?php get_search_form(); ?>

                <?php } ?>

Fix default sidebar search label.

Fix default sidebar search label.


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

// Contains the text for default chunks to highlight that content can be inserted.
return array(
	'text' 		=>	'Default text.',
	'feature'	=>	'Click to feature a page here.',
	'linkset'	=>	'',
	'slideshow'	=>	'Click to insert a slideshow here.',
	'video'		=>	'Click here to add a video.',
);

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

// Contains the text for default chunks to highlight that content can be inserted.
return array(
	'text' 		=>	'
Default text.
',
	'feature'	=>	'Click to feature a page here.',
	'linkset'	=>	'',
	'slideshow'	=>	'Click to insert a slideshow here.',
	'video'		=>	'Click here to add a video.',
);

Fix editable text divs. Have probably broken headings and paras.


<?php

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

$app = new Looptribe\Paytoshi\Application();
$app->run();

<?php

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

$app = new Looptribe\Paytoshi\Application();
$app['debug'] = false;
$app->run();

Add convenience line for debug.

Add convenience line for debug.


<?php

use Illuminate\Database\Seeder;
use VotingApp\Models\User;

class UsersTableSeeder extends Seeder
{

    public function run()
    {
        $faker = Faker\Factory::create();

        User::truncate();

        User::create([
            'first_name' => 'Dave',
            'email' => 'dfurnes@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        User::create([
            'first_name' => 'Andrea',
            'email' => 'agaither@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        User::create([
            'first_name' => 'Naomi',
            'email' => 'nhirabayashi@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        if (app()->environment('local')) {
            foreach (range(1, 25) as $index) {
                User::create([
                    'first_name' => $faker->firstName,
                    'email' => $faker->unique()->safeEmail,
                    'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
                ]);
            }
            foreach (range(1, 25) as $index) {
                User::create([
                    'first_name' => $faker->firstName,
                    'phone' => $faker->unique()->phoneNumber,
                    'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
                ]);
            }
        }
    }
}

<?php

use Illuminate\Database\Seeder;
use VotingApp\Models\User;

class UsersTableSeeder extends Seeder
{

    public function run()
    {
        $faker = Faker\Factory::create();

        User::truncate();

        User::create([
            'first_name' => 'Dave',
            'email' => 'dfurnes@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        User::create([
            'first_name' => 'Andrea',
            'email' => 'agaither@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        User::create([
            'first_name' => 'Naomi',
            'email' => 'nhirabayashi@dosomething.org',
            'password' => 'tops3cret',
        ])->assignRole(1);

        foreach (range(1, 25) as $index) {
            User::create([
                'first_name' => $faker->firstName,
                'email' => $faker->unique()->safeEmail,
                'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
            ]);
        }

        foreach (range(1, 25) as $index) {
            User::create([
                'first_name' => $faker->firstName,
                'phone' => $faker->unique()->phoneNumber,
                'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
            ]);
        }
    }
}

Remove conditional on seeding users.

Remove conditional on seeding users.


<?php namespace Illuminate\Foundation\Providers;

use Illuminate\Foundation\Artisan;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Console\TailCommand;
use Illuminate\Foundation\Console\ChangesCommand;
use Illuminate\Foundation\Console\EnvironmentCommand;

class ArtisanServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->bindShared('artisan', function($app)
		{
			return new Artisan($app);
		});

		$this->app->bindShared('command.tail', function($app)
		{
			return new TailCommand;
		});

		$this->app->bindShared('command.changes', function($app)
		{
			return new ChangesCommand;
		});

		$this->app->bindShared('command.environment', function($app)
		{
			return new EnvironmentCommand;
		});

		$this->commands('command.tail', 'command.changes', 'command.environment');
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('artisan', 'command.changes', 'command.environment');
	}

}

<?php namespace Illuminate\Foundation\Providers;

use Illuminate\Foundation\Artisan;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Console\TailCommand;
use Illuminate\Foundation\Console\ChangesCommand;
use Illuminate\Foundation\Console\EnvironmentCommand;

class ArtisanServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		// This Artisan class is a lightweight wrapper for calling into the Artisan
		// command line. If a call to this class is executed we will boot up the
		// entire Artisan command line then pass the method into the main app.
		$this->app->bindShared('artisan', function($app)
		{
			return new Artisan($app);
		});

		$this->app->bindShared('command.tail', function($app)
		{
			return new TailCommand;
		});

		$this->app->bindShared('command.changes', function($app)
		{
			return new ChangesCommand;
		});

		$this->app->bindShared('command.environment', function($app)
		{
			return new EnvironmentCommand;
		});

		$this->commands('command.tail', 'command.changes', 'command.environment');
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('artisan', 'command.changes', 'command.environment');
	}

}

Add comment on Artisan class.

Add comment on Artisan class.


<?php

class Admin_FormAction_UserInvite_Create extends Admin_FormAction_Abstract {

    protected function _getRequiredFields() {
        return [];
    }

    protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        if (!$response->getViewer(true)->getRoles()->contains(Denkmal_Role::ADMIN)) {
            $response->addError($response->getRender()->getTranslation('Not Allowed'));
        }
    }

    protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        /** @var Denkmal_Params $params */
        $inviter = $response->getViewer(true);
        $email = $params->has('email') ? $params->getString('email') : null;
        $expires = $params->getDate('expires');
        $sendEmail = $params->getBoolean('sendEmail');

        $userInvite = Denkmal_Model_UserInvite::create($inviter, $email, $expires);

        if ($sendEmail) {
            $email = new Denkmal_Mail_UserInvite($userInvite);
            $email->send();
        }
    }
}

<?php

class Admin_FormAction_UserInvite_Create extends Admin_FormAction_Abstract {

    protected function _getRequiredFields() {
        return [];
    }

    protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        parent::_checkData($params, $response, $form);
        $email = $params->has('email') ? $params->getString('email') : null;
        $sendEmail = $params->getBoolean('sendEmail');

        if (null === $email && true === $sendEmail) {
            $response->addError($response->getRender()->getTranslation('Einladung kann nicht verschickt werden weil E-Mail fehlt.'), 'sendEmail');
        }
    }

    protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        /** @var Denkmal_Params $params */
        $inviter = $response->getViewer(true);
        $email = $params->has('email') ? $params->getString('email') : null;
        $expires = $params->getDate('expires');
        $sendEmail = $params->getBoolean('sendEmail');

        $userInvite = Denkmal_Model_UserInvite::create($inviter, $email, $expires);

        if ($sendEmail) {
            $email = new Denkmal_Mail_UserInvite($userInvite);
            $email->send();
        }
    }
}

Add form error for sendEmail but not email on invite form


<?php

namespace DigitLab\AdaptiveView;

use DigitLab\AdaptiveView\Browser\AgentBrowserAdapter;
use DigitLab\AdaptiveView\Browser\Browser;
use Illuminate\Support\ServiceProvider;

class AdaptiveViewServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->registerBrowser();

        $this->registerViewFinder();
    }

    public function registerBrowser()
    {
        $browser = $this->app['config']['view.browser'];
        if (!$browser) {
            $browser = AgentBrowserAdapter::class;
        }

        $this->app->bind(Browser::class, $browser);
    }

    public function registerViewFinder()
    {
        $this->app->bind('view.finder', function ($app) {
            $browser = $app->make(Browser::class);
            $paths = $app['config']['view.paths'];

            return new AdaptiveFileViewFinder($browser, $app['files'], $paths);
        });
    }
}

<?php

namespace DigitLab\AdaptiveView;

use DigitLab\AdaptiveView\Browser\AgentBrowserAdapter;
use DigitLab\AdaptiveView\Browser\Browser;
use Illuminate\Support\ServiceProvider;

class AdaptiveViewServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerBrowser();

        $this->registerViewFinder();
    }

    /**
     * Register the browser implementation.
     *
     * @return void
     */
    public function registerBrowser()
    {
        $browser = $this->app['config']['view.browser'];
        if (!$browser) {
            $browser = AgentBrowserAdapter::class;
        }

        $this->app->bind(Browser::class, $browser);
    }

    /**
     * Register the view finder implementation.
     *
     * @return void
     */
    public function registerViewFinder()
    {
        $this->app->bind('view.finder', function ($app) {
            $browser = $app->make(Browser::class);
            $paths = $app['config']['view.paths'];

            return new AdaptiveFileViewFinder($browser, $app['files'], $paths);
        });
    }
}

Add doc blocks to service provider.

Add doc blocks to service provider.


<?php
/**
 * Script to remove users with duplicate email accounts.
 *
 * to run:
 * drush --script-path=../scripts/ php-script remove-duplicate-emails.php
 */

$users = db_query('SELECT uid FROM users
  WHERE mail IN (SELECT mail FROM users GROUP BY mail HAVING COUNT(mail) > 1)
  AND uid NOT IN (SELECT MIN(uid) FROM users GROUP BY mail HAVING COUNT(mail) > 1)');

foreach ($users as $user) {
  $user = user_load($user->uid);

  if($user->access == 0) {
    print 'Deleting ' . $user->uid . ' (' . $user->mail . ')' . PHP_EOL;

    $northstar_id = $user->field_northstar_id[LANGUAGE_NONE][0]['value'];

    if ($northstar_id !== 'NONE') {
      print 'User ' . $user->uid . ' has a Northstar profile: ' . $northstar_id;
    }

    user_delete($user->uid);
  } else {
    print 'Ignoring duplicate ' . $user->uid . ' (' . $user->mail . ')' . PHP_EOL;
  }
}

<?php
/**
 * Script to remove users with duplicate email accounts.
 *
 * to run:
 * drush --script-path=../scripts/ php-script remove-duplicate-emails.php
 */

$dupes = array_keys(db_query('SELECT mail FROM users GROUP BY mail HAVING COUNT(mail) > 1')->fetchAllKeyed());
$removed = 0;

foreach ($dupes as $mail) {
  // Load all users with that duped email address, with the most recently accessed first.
  $users = db_query('SELECT uid FROM users WHERE mail = :mail ORDER BY access DESC', [':mail' => $mail]);
  $canonical_uid = 0;

  foreach ($users as $key => $user) {
    $user = user_load($user->uid);

    if ($key == 0) {
      print 'Keeping ' . $user->uid . ' for ' . $user->mail . '.' . PHP_EOL;
      $canonical_uid = $user->uid;
      continue;
    }

    // Set the new email for the deactivated user.
    $new_email = 'duplicate-' . $canonical_uid . '-' . $key . '@dosomething.invalid';
    print ' - Removing ' . $user->uid . ' (' . $user->mail . ' --> ' . $new_email . ')' . PHP_EOL;
    user_save($user, ['mail' => $new_email, 'status' => 0]);
    $removed++;

    // Finally, make a note if that user has a Northstar profile, so we can clean that up.
    $northstar_id = $user->field_northstar_id[LANGUAGE_NONE][0]['value'];
    if ($northstar_id !== 'NONE') {
      print '   ** User ' . $user->uid . ' has a Northstar profile: ' . $northstar_id;
    }
  }

  print PHP_EOL;
}

print '[✔] Renamed & deactivated ' . $removed . ' users.' . PHP_EOL;

Update script to safely de-activate, and keep latest active.


<?php namespace Barryvdh\TranslationManager;

use Illuminate\Translation\Translator as LaravelTranslator;
use Illuminate\Events\Dispatcher;

class Translator extends LaravelTranslator {

    /** @var  Dispatcher */
    protected $events;

    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @return string
     */
    public function get($key, array $replace = array(), $locale = null)
    {
        $result = parent::get($key, $replace, $locale);
        if($result === $key){
            $this->notifyMissingKey($key);
        }

        return $result;
    }

    public function setTranslationManager(Manager $manager)
    {
        $this->manager = $manager;
    }

    protected function notifyMissingKey($key)
    {
        list($namespace, $group, $item) = $this->parseKey($key);
        if($this->manager && $namespace === '*' && $group && $item ){
            $this->manager->missingKey($namespace, $group, $item);
        }
    }

}

<?php namespace Barryvdh\TranslationManager;

use Illuminate\Translation\Translator as LaravelTranslator;
use Illuminate\Events\Dispatcher;

class Translator extends LaravelTranslator {

    /** @var  Dispatcher */
    protected $events;

    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @return string
     */
    public function get($key, array $replace = array(), $locale = null, $fallback = true)
    {
        $result = parent::get($key, $replace, $locale);
        if($result === $key){
            $this->notifyMissingKey($key);

            // Reget with fallback if true
            if ($fallback) {
                $result = parent::get($key, $replace, $locale, $fallback);
            }
        }

        return $result;
    }

    public function setTranslationManager(Manager $manager)
    {
        $this->manager = $manager;
    }

    protected function notifyMissingKey($key)
    {
        list($namespace, $group, $item) = $this->parseKey($key);
        if($this->manager && $namespace === '*' && $group && $item ){
            $this->manager->missingKey($namespace, $group, $item);
        }
    }

}

Enable getting string with fallback, but still notifying missing key


<?php

namespace Coduo\PHPHumanizer\String;

class Truncate
{
    /**
     * @var string
     */
    private $text;

    /**
     * @var int
     */
    private $charactersCount;

    /**
     * @var string
     */
    private $append;

    /**
     * @param string $text
     * @param int $charactersCount
     * @param string $append
     */
    public function __construct($text, $charactersCount, $append = '')
    {
        $this->text = $text;
        $this->charactersCount = $charactersCount;
        $this->append = $append;
    }

    public function __toString()
    {
        if ($this->charactersCount < 0 || strlen($this->text) <= $this->charactersCount) {
            return $this->text;
        }

        $word = \IntlBreakIterator::createWordInstance(\Locale::getDefault());
        $word->setText($this->text);
        $word->following($this->charactersCount);

        return substr($this->text, 0, $word->current()) . $this->append;
    }
}

<?php

namespace Coduo\PHPHumanizer\String;

class Truncate
{
    /**
     * @var string
     */
    private $text;

    /**
     * @var int
     */
    private $charactersCount;

    /**
     * @var string
     */
    private $append;

    /**
     * @param string $text
     * @param int $charactersCount
     * @param string $append
     */
    public function __construct($text, $charactersCount, $append = '')
    {
        $this->text = $text;
        $this->charactersCount = $charactersCount;
        $this->append = $append;
    }

    public function __toString()
    {
        if ($this->charactersCount < 0 || strlen($this->text) <= $this->charactersCount) {
            return $this->text;
        }

        $length = $this->charactersCount;
        if (false !== ($breakpoint = mb_strpos($this->text, ' ', $this->charactersCount))) {
            $length = $breakpoint;
        }

        return rtrim(mb_substr($this->text, 0, $length)) . $this->append;
    }
}

Make truncate to be available at php 5.3 and 5.4


@section('title')
Melee - Cataclysm: Dark Days Ahead
@endsection
@section('content')

Melee

Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2

    Name
    Material
    V
    W
    Dmg
    H

@foreach($items as $item)

  {{ $item->symbol }}
  id)}}">{{ $item->name }}
  {{ $item->materials }}
  {{ $item->volume }}
  {{ $item->weight }}
  {{ $item->bashing+$item->cutting }}
  {{ $item->to_hit }}

@endforeach

@endsection

@section('title')
Melee - Cataclysm: Dark Days Ahead
@endsection
@section('content')

Melee

Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2

    Name
    Material
    V
    W
    M/A
    Dmg
    H

@foreach($items as $item)

  {{ $item->symbol }}
  id)}}">{{ $item->name }}
  {{ $item->materials }}
  {{ $item->volume }}
  {{ $item->weight }}
  {{ $item->movesPerAttack }}
  {{ $item->bashing+$item->cutting }}
  {{ $item->to_hit }}

@endforeach

@endsection

Add a new column: moves per attack.

Add a new column: moves per attack.


<?php

namespace A3020\Centry\User\Summary;

use A3020\Centry\Payload\PayloadAbstract;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\User\UserList;

final class Payload extends PayloadAbstract
{
    /** @var Connection */
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function jsonSerialize()
    {
        return [
            'total_users' => $this->getTotalUsers(),
            'last_login' => $this->getLastLoginDate(),
        ];
    }

    /**
     * @return int
     */
    private function getTotalUsers()
    {
        $ul = new UserList();
        $ul->ignorePermissions();
        return (int) $ul->getTotalResults();
    }

    /**
     * @return int timestamp
     */
    private function getLastLoginDate()
    {
        return $this->db->fetchColumn('
            SELECT uLastLogin FROM Users
            ORDER BY uLastLogin DESC LIMIT 0,1
        ');
    }
}

<?php

namespace A3020\Centry\User\Summary;

use A3020\Centry\Payload\PayloadAbstract;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\User\UserList;

final class Payload extends PayloadAbstract
{
    /** @var Connection */
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function jsonSerialize()
    {
        return [
            'total_users' => $this->getTotalUsers(),
            'last_login' => $this->getLastLoginDate(),
        ];
    }

    /**
     * @return int
     */
    private function getTotalUsers()
    {
        $ul = new UserList();
        if (method_exists($ul, 'ignorePermissions')) {
            // This method doesn't exist in v8.0
            $ul->ignorePermissions();
        }
        return (int) $ul->getTotalResults();
    }

    /**
     * @return int timestamp
     */
    private function getLastLoginDate()
    {
        return $this->db->fetchColumn('
            SELECT uLastLogin FROM Users
            ORDER BY uLastLogin DESC LIMIT 0,1
        ');
    }
}

Fix 'ignorePermissions' compatibility bug in 8.0


<?php
/**
 * WebHook event manager
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) 2014, Mohammad Abdoli Rad
 * @author    Mohammad Abdoli Rad <m.abdolirad@gmail.com>
 * @since     Version 0.1.0
 * @license   http://opensource.org/licenses/MIT MIT license
 */
namespace WebHookEventManager;

use WebHookEventManager\Service\GitHub\Request;

/**
 * Class WebHook
 *
 * @package WebHookEventManager
 */
class WebHook
{
    protected $service = null;
    protected $webHookService = null;

    /**
     * Get GitHub service
     *
     * @return Service\GitHub\WebHook
     */
    public function getGitHubService()
    {
        $request = new Request();

        if ($request->isValidOrigin()) {
            $data = $request->getContent();
        } else {
            $data = null;
        }

        $payload = new \WebHookEventManager\Service\GitHub\WebHook($data);

        return $payload;
    }
}

<?php
/**
 * WebHook event manager
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) 2014, Mohammad Abdoli Rad
 * @author    Mohammad Abdoli Rad <m.abdolirad@gmail.com>
 * @since     Version 0.1.0
 * @license   http://opensource.org/licenses/MIT MIT license
 */
namespace WebHookEventManager;

use WebHookEventManager\Service\GitHub\Request;

/**
 * Class WebHook
 *
 * @package WebHookEventManager
 */
class WebHook
{
    protected $service = null;
    protected $webHookService = null;

    /**
     * Get GitHub service
     *
     * @return Service\GitHub\WebHook
     */
    public function getGitHubService()
    {
        $request = new Request();

        if ($request->isValidOrigin()) {
            $data = $request->getContent();
        } else {
            $data = '{}';
        }

        $payload = new \WebHookEventManager\Service\GitHub\WebHook($data);

        return $payload;
    }
}

Change data with empty json string

Change data with empty json string


<?php

class ManipleRequirejs_Bootstrap extends Maniple_Application_Module_Bootstrap
{
    public function getResourcesConfig()
    {
        return require __DIR__ . '/configs/resources.config.php';
    }

    public function getViewConfig()
    {
        return array(
            'helperPaths' => array(
                'ManipleRequirejs_View_Helper_' => __DIR__ . '/library/ManipleRequirejs/View/Helper/',
            ),
        );
    }

    public function getAutoloaderConfig()
    {
        return array(
            'prefixes' => array(
                'ManipleRequirejs_' => __DIR__ . '/library/ManipleRequirejs/',
            ),
        );
    }
}

<?php

class ManipleRequirejs_Bootstrap extends Maniple_Application_Module_Bootstrap
{
    public function getResourcesConfig()
    {
        return require __DIR__ . '/configs/resources.config.php';
    }

    public function getViewConfig()
    {
        return array(
            'helperPaths' => array(
                'ManipleRequirejs_View_Helper_' => __DIR__ . '/library/ManipleRequirejs/View/Helper/',
            ),
        );
    }

    public function getAutoloaderConfig()
    {
        return array(
            'prefixes' => array(
                'ManipleRequirejs_' => __DIR__ . '/library/ManipleRequirejs/',
            ),
        );
    }

    protected function _initView()
    {
        // Make sure View is bootstrapped when Requirejs resource is retrieved
        // inside dependent modules
        $this->getApplication()->bootstrap('View');
    }
}

Make sure View is bootstrapped when Requirejs resource is retrieved inside dependent modules


<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 24.10.2014
 * Time: 16:10
 */

namespace mpf\widgets\viewtable\columns;

use mpf\base\Object;
use mpf\web\helpers\Html;

class Basic extends Object {

    public $name;

    public $label;

    public $value;

    public $htmlOptions = [];

    public $headerHtmlOptions = [];

    public $rowHtmlOptions = [];

    /**
     * Can be 'input' or 'raw'. If type is raw then it will not apply any escape to it. If not it will use html_encode from Html helper.
     * @var string
     */
    public $type = 'input';

    /**
     * @var \mpf\widgets\viewtable\Table
     */
    public $table;

    public function display(){
        return Html::get()->tag('tr', $this->getRowContent(), $this->rowHtmlOptions);
    }

    protected function getRowContent(){
        return Html::get()->tag('th', $this->getLabel(), $this->headerHtmlOptions) . Html::get()->tag('td', $this->getValue(), $this->htmlOptions);
    }

    protected function getLabel(){
        return $this->label?:$this->table->getLabel($this->name);
    }

    protected function getValue(){
        return $this->value?:$this->table->model->{$this->name};
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 24.10.2014
 * Time: 16:10
 */

namespace mpf\widgets\viewtable\columns;

use mpf\base\TranslatableObject;
use mpf\web\helpers\Html;

class Basic extends TranslatableObject {

    public $name;

    public $label;

    public $value;

    public $htmlOptions = [];

    public $headerHtmlOptions = [];

    public $rowHtmlOptions = [];

    /**
     * Can be 'input' or 'raw'. If type is raw then it will not apply any escape to it. If not it will use html_encode from Html helper.
     * @var string
     */
    public $type = 'input';

    /**
     * @var \mpf\widgets\viewtable\Table
     */
    public $table;

    public function display(){
        return Html::get()->tag('tr', $this->getRowContent(), $this->rowHtmlOptions);
    }

    protected function getRowContent(){
        return Html::get()->tag('th', $this->getLabel(), $this->headerHtmlOptions) . Html::get()->tag('td', $this->getValue(), $this->htmlOptions);
    }

    protected function getLabel(){
        return $this->translate($this->label?:$this->table->getLabel($this->name));
    }

    protected function getValue(){
        return $this->value?:$this->table->model->{$this->name};
    }

}

Allow columns to be translated

Allow columns to be translated


<?php

namespace Ibuildings\QaTools\Core\Assert;

use Assert\Assertion as BaseAssertion;
use Ibuildings\QaTools\Core\Exception\InvalidArgumentException;

/**
 * @method static void nullOrNonEmptyString($value, $propertyPath = null)
 * @method static void allNonEmptyString($value, $propertyPath = null)
 * @method static void nullOrallNonEmptyString($value, $propertyPath = null)
 */
final class Assertion extends BaseAssertion
{
    const INVALID_NON_EMPTY_STRING   = 1001;

    protected static $exceptionClass = InvalidArgumentException::class;

    /**
     * @param string $value
     * @param string $propertyPath
     * @return void
     */
    public static function nonEmptyString($value, $propertyPath)
    {
        if (!is_string($value) || trim($value) === '') {
            $message = 'Expected non-empty string for "%s", "%s" given';

            throw static::createException(
                $value,
                sprintf($message, $propertyPath, static::stringify($value)),
                static::INVALID_NON_EMPTY_STRING,
                $propertyPath
            );
        }
    }
}

<?php

namespace Ibuildings\QaTools\Core\Assert;

use Assert\Assertion as BaseAssertion;
use Ibuildings\QaTools\Core\Exception\InvalidArgumentException;

/**
 * @method static void nullOrNonEmptyString($value, $propertyPath = null)
 * @method static void allNonEmptyString($value, $propertyPath = null)
 * @method static void nullOrallNonEmptyString($value, $propertyPath = null)
 */
final class Assertion extends BaseAssertion
{
    const INVALID_NON_EMPTY_STRING   = 1001;
    const PATH_NOT_EXISTS            = 1002;

    protected static $exceptionClass = InvalidArgumentException::class;

    /**
     * @param string $value
     * @param string $propertyPath
     * @return void
     */
    public static function nonEmptyString($value, $propertyPath)
    {
        if (!is_string($value) || trim($value) === '') {
            $message = 'Expected non-empty string for "%s", "%s" given';

            throw static::createException(
                $value,
                sprintf($message, $propertyPath, static::stringify($value)),
                static::INVALID_NON_EMPTY_STRING,
                $propertyPath
            );
        }
    }

    /**
     * @param string      $path
     * @param string|null $message
     * @param string|null $propertyPath
     */
    public static function pathNotExists($path, $message = null, $propertyPath = null)
    {
        self::string($path, 'Expected path to be a string, got "%s" of type "%s"');

        if (file_exists($path)) {
            $message = $message ?: 'Expected path "%s" to not exist';

            throw static::createException(
                $path,
                sprintf($message, $path),
                static::PATH_NOT_EXISTS,
                $propertyPath
            );
        }
    }
}

Allow assertion that path does not exist


<?php

use Manialib\Formatting\Converter\Html;
use Manialib\Formatting\ManiaplanetString;

class HtmlTest extends PHPUnit_Framework_TestCase
{

    public function convertProvider()
    {
        return [
            [
                '$cfeg$fff๐u1 $666ツ',
                'g๐u1 ツ'
            ],
            ['a$>b', 'ab']
        ];
    }

    /**
     * @dataProvider convertProvider
     */
    public function testConvert($input, $expected)
    {
        $this->assertEquals($expected, (new ManiaplanetString($input))->toHtml());
    }

    /**
     * @dataProvider convertProvider
     */
    public function testReuseConverter($input, $expected)
    {

        $converter = new Html();
        $this->assertEquals(
            $converter->setInput(new ManiaplanetString($input))->getOutput(),
            $converter->setInput(new ManiaplanetString($input))->getOutput());
    }

    public function nicknamesProvider()
    {
        return [
            ['']
        ];
    }

    /**
     * @dataProvider nicknamesProvider
     */
    public function testNoErrors($input)
    {
        (new ManiaplanetString($input))->toHtml();
    }

}

<?php

use Manialib\Formatting\Converter\Html;
use Manialib\Formatting\ManiaplanetString;

class HtmlTest extends PHPUnit_Framework_TestCase
{

    public function convertProvider()
    {
        return [
            [
                '$cfeg$fff๐u1 $666ツ',
                'g๐u1 ツ'
            ],
            [
                'a$>b',
                'ab'
            ],
            [
                'foo$<$f20foo$>bar',
                'foofoobar'
            ]
        ];
    }

    /**
     * @dataProvider convertProvider
     */
    public function testConvert($input, $expected)
    {
        $this->assertEquals($expected, (new ManiaplanetString($input))->toHtml());
    }

    /**
     * @dataProvider convertProvider
     */
    public function testReuseConverter($input, $expected)
    {

        $converter = new Html();
        $this->assertEquals(
            $converter->setInput(new ManiaplanetString($input))->getOutput(),
            $converter->setInput(new ManiaplanetString($input))->getOutput());
    }

    public function nicknamesProvider()
    {
        return [
            ['']
        ];
    }

    /**
     * @dataProvider nicknamesProvider
     */
    public function testNoErrors($input)
    {
        (new ManiaplanetString($input))->toHtml();
    }

}

Add a test about parsing $< and $> (that was failing before fix)


<?php
	namespace Bolt\Api;

	class Connections extends \Bolt\Base
	{
		public $sources;

		public function __construct($connections = null)
		{
			if ($connections !== null)
			{
				if (is_array($connections))
				{
					foreach ($connections as $connection)
					{
						$this->add($connection);
					}
				}
				else
				{
					$this->add($connections);
				}
			}
		}

		public function add($connection)
		{
			$this->sources[] = $connection;
		}

		public function dbo()
		{
			return $this->filter("Bolt\Dbo");
		}

		public function eso()
		{
			return $this->filter("Bolt\Eso");
		}

		private function filter($className)
		{
			$results = array();

			foreach ($this->sources as $source)
			{
				if ($source->className() == $className)
				{
					$results[] = $source;
				}
			}

			return $results;
		}
	}
?>

<?php
	namespace Bolt\Api;

	class Connections extends \Bolt\Base
	{
		public $sources;

		public function __construct($connections = null)
		{
			if ($connections !== null)
			{
				if (is_array($connections))
				{
					foreach ($connections as $connection)
					{
						$this->add($connection);
					}
				}
				else
				{
					$this->add($connections);
				}
			}
		}

		public function add($connection)
		{
			$this->sources[] = $connection;
		}

		public function assign($name, $index)
		{
			$this->$name = &$this->sources[$index];
		}

		private function filter($className)
		{
			$results = array();

			foreach ($this->sources as $source)
			{
				if ($source->className() == $className)
				{
					$results[] = $source;
				}
			}

			return $results;
		}
	}
?>

Replace type filtering method with a name based assign() method


<?php

namespace webignition\WebResource\Sitemap\UrlExtractor;

class SitemapsOrgXmlIndexUrlExtractor extends UrlExtractor {

    public function extract($content) {
        $urls = array();
        $queryPath = new \QueryPath();

        try {
            $queryPath->withXML($content, 'sitemap loc')->each(function ($index, \DOMElement $domElement) use (&$urls) {
                if ($domElement->nodeName == 'loc') {
                    $urls[] = \trim($domElement->nodeValue);
                }
            });
        } catch (QueryPath\ParseException $parseException) {
            // Invalid XML
        }

        return $urls;
    }

}

<?php

namespace webignition\WebResource\Sitemap\UrlExtractor;

class SitemapsOrgXmlIndexUrlExtractor extends UrlExtractor {

    public function extract($content) {
        $urls = array();

        $xmlParser = new \Hobnob\XmlStreamReader\Parser();
        $xmlParser->registerCallback(
            '/sitemapindex/sitemap',
            function( \Hobnob\XmlStreamReader\Parser $parser, \SimpleXMLElement $node) use (&$urls) {
                $urls[] = (string)$node;
            }
        );
        $xmlParser->parse($content);

        return $urls;
    }

}

Switch sitemap index extractor to use sax speediness


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => env('SES_REGION', 'us-east-1'),
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => env('SES_REGION', 'us-east-1'),
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

];

Add missing Mailgun 'endpoint' option

Add missing Mailgun 'endpoint' option

Counterpart to https://github.com/laravel/framework/pull/25010


<?php
namespace MapasCulturais;

class Definition implements \JsonSerializable{
    use \MapasCulturais\Traits\MagicGetter,
        \MapasCulturais\Traits\MagicSetter;

    public function isDefinition(){
        return true;
    }

    public function jsonSerialize() {
        $result = [];
        foreach ($this as $prop => $val)
            if($prop[0] !== '_')
                $result[$prop] = $val;

        return $result;
    }
}

<?php
namespace MapasCulturais;

class Definition implements \JsonSerializable{
    use \MapasCulturais\Traits\MagicGetter,
        \MapasCulturais\Traits\MagicSetter,
        \MapasCulturais\Traits\MagicCallers;

    public function isDefinition(){
        return true;
    }

    public function jsonSerialize() {
        $result = [];
        foreach ($this as $prop => $val)
            if($prop[0] !== '_')
                $result[$prop] = $val;

        return $result;
    }
}

Fix entity attribute and verify metadata use.


<?php

$default = [
    'Demo\\Application\\Adapter\\TwigAdapter' => [
        'class' => 'Demo\\Application\\Adapter\\TwigAdapter',
        'arguments' => [
            'config',
        ],
    ],
];

return array_merge(
    $default,
    require __DIR__ . '/../src/Config/Service.php'
);

<?php

$default = [
    'Demo\\Application\\Adapter\\TwigAdapter' => [
        'class' => 'Demo\\Application\\Adapter\\TwigAdapter',
        'arguments' => [
            'Colonel\\Configuration',
        ],
    ],
];

return array_merge(
    $default,
    require __DIR__ . '/../src/Config/Service.php'
);

Change how the config class is called

Change how the config class is called


<?php

namespace AppBundle\TestsService;

use AppBundle\Service\ObservationService;
use AppBundle\Entity\Observation;
use PHPUnit\Framework\TestCase;

use OC\BookingBundle\Service\Utils;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class ObservationTest extends WebTestCase
{

    protected static $translation;
    protected static $em;

    public static function setUpBeforeClass()
    {
        $kernel = static::createKernel();
        $kernel->boot();
        self::$translation = $kernel->getContainer()->get('translator');
        self::$em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
    }

    /**
     *  Get last 3 Observations
     *
     * @return [type] [description]
     */
    public function testObservations()
    {
        $ts = new TokenStorage();
        $obs = new ObservationService(self::$em, $ts);
        $result = $obs->getLastObersations(2);
        $this->assertCount(2, $result);
    }
}

Fix (Observation test): change method name


<?php

namespace solutionweb\gatekeeper\utils;

use mako\application\Package;

/**
 * Package registraion class.
 *
 * @author Bert Peters <bert@solution-web.nl>
 */
class GatekeeperUtilsPackage extends Package
{
    protected $packageName = "solution-web/gatekeeper-utils";

    /**
     * Register the available commands.
     */
    protected $commands = [
        "gatekeeper::user.create" => 'solutionweb\gatekeeper\utils\commands\CreateUserCommand',
        "gatekeeper::user.activate" => 'solutionweb\gatekeeper\utils\commands\ActivateUserCommand',
        "gatekeeper::user.password" => 'solutionweb\gatekeeper\utils\commands\SetPasswordCommand',
        "gatekeeper::group.create" => 'solutionweb\gatekeeper\utils\commands\CreateGroupCommand',
        "gatekeeper::group.delete" => 'solutionweb\gatekeeper\utils\commands\DeleteGroupCommand',
        "gatekeeper::group.member" => 'solutionweb\gatekeeper\utils\commands\GroupMemberCommand',
    ];
}

<?php

namespace solutionweb\gatekeeper\utils;

use mako\application\Package;
use solutionweb\gatekeeper\utils\commands\ActivateUserCommand;
use solutionweb\gatekeeper\utils\commands\CreateGroupCommand;
use solutionweb\gatekeeper\utils\commands\CreateUserCommand;
use solutionweb\gatekeeper\utils\commands\DeleteGroupCommand;
use solutionweb\gatekeeper\utils\commands\GroupMemberCommand;
use solutionweb\gatekeeper\utils\commands\SetPasswordCommand;

/**
 * Package registraion class.
 *
 * @author Bert Peters <bert@solution-web.nl>
 */
class GatekeeperUtilsPackage extends Package
{
    protected $packageName = "solution-web/gatekeeper-utils";

    /**
     * Register the available commands.
     */
    protected $commands = [
        "gatekeeper::user.create" => CreateUserCommand::class,
        "gatekeeper::user.activate" => ActivateUserCommand::class,
        "gatekeeper::user.password" => SetPasswordCommand::class,
        "gatekeeper::group.create" => CreateGroupCommand::class,
        "gatekeeper::group.delete" => DeleteGroupCommand::class,
        "gatekeeper::group.member" => GroupMemberCommand::class,
    ];
}

Use class constants instead of class names.


<?php
namespace JLSalinas\RWGen;

trait GeneratorAggregateHack
{
    public function send($value)
    {
        static $generator = null;

        if ($generator === null) {
            if ($value === null) {
                return;
            }
            $generator = $this->getGenerator();
        }
        $generator->send($value);
        if ($value === null) {
            $generator = null;
        }
    }

    public function __destruct()
    {
        $this->send(null);
    }
}

<?php
namespace JLSalinas\RWGen;

trait GeneratorAggregateHack
{
    protected $generator = null;
    public function send($value)
    {
        if ($this->generator === null) {
            if ($value === null) {
                return;
            }
            $this->generator = $this->getGenerator();
        }
        $this->generator->send($value);
        if ($value === null) {
            $this->generator = null;
        }
    }

    public function __destruct()
    {
        $this->send(null);
    }
}

Fix static generator causing only one output at a time


<?php

namespace MessageBird\Resources\Conversation;

use MessageBird\Common\HttpClient;
use MessageBird\Exceptions;
use MessageBird\Objects\Conversation\SendMessage;
use MessageBird\Objects\Conversation\SendMessageResult;
use MessageBird\Resources\Base;

class Send extends Base
{
    const RESOURCE_NAME = 'conversations/send';

    public function __construct(HttpClient $httpClient)
    {
        parent::__construct($httpClient);

        $this->setObject(new SendMessageResult());
        $this->setResourceName(self::RESOURCE_NAME);
    }

    /**
     * Starts a conversation or adding a message to the conversation when a conversation with the contact already exist.
     *
     * @param SendMessage $object
     * @param array|null $query
     *
     * @return SendMessageResult
     *
     * @throws Exceptions\HttpException
     * @throws Exceptions\RequestException
     * @throws Exceptions\ServerException
     */
    public function send($object, $query = null)
    {
        $body = json_encode($object);

        list(, , $body) = $this->HttpClient->performHttpRequest(
            HttpClient::REQUEST_POST,
            $this->getResourceName(),
            $query,
            $body
        );

        return $this->processRequest($body);
    }
}

<?php

namespace MessageBird\Resources\Conversation;

use MessageBird\Common\HttpClient;
use MessageBird\Exceptions;
use MessageBird\Objects\Conversation\SendMessage;
use MessageBird\Objects\Conversation\SendMessageResult;
use MessageBird\Resources\Base;

class Send extends Base
{
    const RESOURCE_NAME = 'send';

    public function __construct(HttpClient $httpClient)
    {
        parent::__construct($httpClient);

        $this->setObject(new SendMessageResult());
        $this->setResourceName(self::RESOURCE_NAME);
    }

    /**
     * Starts a conversation or adding a message to the conversation when a conversation with the contact already exist.
     *
     * @param SendMessage $object
     * @param array|null $query
     *
     * @return SendMessageResult
     *
     * @throws Exceptions\HttpException
     * @throws Exceptions\RequestException
     * @throws Exceptions\ServerException
     */
    public function send($object, $query = null)
    {
        $body = json_encode($object);

        list(, , $resultBody) = $this->HttpClient->performHttpRequest(
            HttpClient::REQUEST_POST,
            $this->getResourceName(),
            $query,
            $body
        );

        return $this->processRequest($resultBody);
    }
}

Use the right URI for send

Use the right URI for send


<?php

class PointsOfInterestLayerTest extends SapphireTest {

	public function testGetCMSFields() {
		$this->markTestSkipped('TODO');
	}
}

<?php

class PointsOfInterestLayerTest extends SapphireTest {

	public function testUpdateCMSFields() {
		$layer = new PointsOfInterestLayer();
		$fields = $layer->getCMSFields();
		$root = $fields->fieldByName('Root.Main');
		$fields = $root->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}

		error_log(print_r($names,1));
		$expected = array('Name', 'ShowGuideMarkers', 'DefaultIcon');
		$this->assertEquals($expected, $names);

	}

}

class PointsOfInterestLayerTestObjectTO extends DataObject implements TestOnly {
}

Test for points of interest layer

ENHANCEMENT: Test for points of interest layer


<?php

namespace PSFS\base\types;

use PSFS\base\Security;

/**
 * Class AuthController
 * @package PSFS\base\types
 */
trait SecureTrait {

    /**
     * @Inyectable
     * @var \PSFS\base\Security Seguridad del controlador
     */
    protected $security;

    /**
     * Constructor por defecto
     */
    public function __construct()
    {
        $this->security = Security::getInstance();
    }

    /**
     * Método que verifica si está autenticado el usuario
     * @return boolean
     */
    public function isLogged() {
        return (null !== $this->security->getUser());
    }

    /**
     * Método que devuelve si un usuario es administrador de la plataforma
     * @return boolean
     */
    public function isAdmin() {
        return $this->security->canAccessRestrictedAdmin();
    }

    /**
     * Método que define si un usuario puede realizar una acción concreta
     * @param $action
     * TODO
     * @return bool
     */
    public function canDo($action) {
        return true;
    }

}

<?php

namespace PSFS\base\types;

use PSFS\base\Security;

/**
 * Class AuthController
 * @package PSFS\base\types
 */
trait SecureTrait {

    /**
     * @Inyectable
     * @var \PSFS\base\Security Seguridad del controlador
     */
    protected $security;

    /**
     * Constructor por defecto
     */
    public function __construct()
    {
        $this->security = Security::getInstance();
    }

    /**
     * Método que verifica si está autenticado el usuario
     * @return boolean
     */
    public function isLogged() {
        return (null !== $this->security->getUser() || $this->isAdmin());
    }

    /**
     * Método que devuelve si un usuario es administrador de la plataforma
     * @return boolean
     */
    public function isAdmin() {
        return $this->security->canAccessRestrictedAdmin();
    }

    /**
     * Método que define si un usuario puede realizar una acción concreta
     * @param $action
     * TODO
     * @return bool
     */
    public function canDo($action) {
        return true;
    }

}

Check if admin is logged in AuthControllers


<?php

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

namespace Sylius\Component\Order;

class InventoryUnitTransitions
{
    const SYLIUS_HOLD       = 'hold';
    const SYLIUS_BACKORDER  = 'backorder';
    const SYLIUS_SOLD       = 'sold';
    const SYLIUS_RETURN     = 'return';
}

<?php

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

namespace Sylius\Component\Order;

class InventoryUnitTransitions
{
    const GRAPH = 'sylius_inventory_unit';

    const SYLIUS_HOLD       = 'hold';
    const SYLIUS_BACKORDER  = 'backorder';
    const SYLIUS_SOLD       = 'sold';
    const SYLIUS_RETURN     = 'return';
}

Use constant for graph names

Use constant for graph names


<?php
/**
 * The template for displaying post snippets. Used for both single and index/archive/search.
 *
 * @package NotebookHeavy
 * @subpackage NH2013
 * @since NH2013 1.0
 */
?>

<article id="post-<?php the_ID(); ?>">

    	<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark">

<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark"><?php the_title(); ?>

            <time><?php the_date('Y-m-d'); ?></time>

               <?php the_tags(); ?>

            <?php the_excerpt(); ?>

       <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark">Continue Reading

<?php
/**
 * The template for displaying post snippets. Used for both single and index/archive/search.
 *
 * @package NotebookHeavy
 * @subpackage NH2013
 * @since NH2013 1.0
 */
?>

<article id="post-<?php the_ID(); ?>">

    	<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark">

<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark"><?php the_title(); ?>

            <time><?php the_date('Y-m-d'); ?></time>

               <?php the_tags('', ', ',''); ?>

            <?php the_excerpt(); ?>

       <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' )  ) ); ?>" rel="bookmark">Continue Reading

Change the way tags are rendered.

Change the way tags are rendered.


<!-- jQuery -->
    <script src="js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

    <script type="text/javascript" src="<?php echo base_url("assets/js/jquery-2.1.4.min.js"); ?>"></script>
   <script type="text/javascript" src="<?php echo base_url("assets/js/bootstrap.js"); ?>"></script>
   <script type="text/javascript" src="<?php echo base_url("assets/js/editabletable.js"); ?>"></script>

    <!-- Menu Toggle Script -->
    <script>
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("toggled");
    });
    </script>

</body>

</html>

Move several script loads to header-user.php.


<?php
namespace Nodes\Api\Routing;

use Dingo\Api\Routing\Helpers as DingoRoutingHelpers;

/**
 * Class Helpers
 *
 * @trait
 * @package  Nodes\Api\Routing
 *
 * @property \Illuminate\Database\Eloquent\Model $user
 * @property \Nodes\Api\Auth\Auth                $auth
 * @property \Nodes\Api\Http\Response\Factory    $response
 */
trait Helpers
{
    use DingoRoutingHelpers;

    /**
     * Get the authenticated user
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access protected
     * @return \Illuminate\Database\Eloquent\Model
     */
    protected function user()
    {
        return app('api.auth')->user();
    }

    /**
     * Get the auth instance
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access public
     * @return \Nodes\Api\Auth\Auth
     */
    protected function auth()
    {
        return app('api.auth');
    }

    /**
     * Get the response factory instance
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access protected
     * @return \Nodes\Api\Http\Response\Factory
     */
    protected function response()
    {
        return app('api.http.response');
    }
}

<?php
namespace Nodes\Api\Routing;

use Dingo\Api\Routing\Helpers as DingoRoutingHelpers;

/**
 * Class Helpers
 *
 * @trait
 * @package  Nodes\Api\Routing
 *
 * @property \Illuminate\Database\Eloquent\Model $user
 * @property \Nodes\Api\Auth\Auth                $auth
 * @property \Nodes\Api\Http\Response\Factory    $response
 * @method Response item() item($item, $transformer, array $parameters = [], Closure $after = null) Bind an item to a transformer and start building a response
 */
trait Helpers
{
    use DingoRoutingHelpers;

    /**
     * Get the authenticated user
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access protected
     * @return \Illuminate\Database\Eloquent\Model
     */
    protected function user()
    {
        return app('api.auth')->user();
    }

    /**
     * Get the auth instance
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access public
     * @return \Nodes\Api\Auth\Auth
     */
    protected function auth()
    {
        return app('api.auth');
    }

    /**
     * Get the response factory instance
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access protected
     * @return \Nodes\Api\Http\Response\Factory
     */
    protected function response()
    {
        return app('api.http.response');
    }
}

Add phpdoc for magic item() method

Add phpdoc for magic item() method


<?php

if (!defined ('TYPO3_MODE')) die ('Access denied.');

// Automatically include TypoScript dependencies
FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:css_styled_content/static/v6.2');
FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:tev/Configuration/TypoScript');

// Hook into RealURL config generation
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/realurl/class.tx_realurl_autoconfgen.php']['extensionConfiguration']['tev'] = 'Tev\\Tev\\Hook\\RealUrlAutoConfigurationHook->updateConfig';

// Add new cache type to clear RealURL config
$TYPO3_CONF_VARS['SC_OPTIONS']['additionalBackendItems']['cacheActions'][] = 'Tev\\Tev\\Url\\CacheMenu';
$TYPO3_CONF_VARS['BE']['AJAX']['tx_tev::clearcacheurl'] = 'Tev\\Tev\\Url\\Cache->clear';

<?php

if (!defined ('TYPO3_MODE')) {
    die ('Access denied.');
}

// Automatically include TypoScript dependencies

\FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:css_styled_content/static/');
\FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:tev/Configuration/TypoScript');

// Hook into RealURL config generation

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/realurl/class.tx_realurl_autoconfgen.php']['extensionConfiguration']['tev'] = 'Tev\\Tev\\Hook\\RealUrlAutoConfigurationHook->updateConfig';

// Add new cache type to clear RealURL config

$TYPO3_CONF_VARS['SC_OPTIONS']['additionalBackendItems']['cacheActions'][] = 'Tev\\Tev\\Url\\CacheMenu';
$TYPO3_CONF_VARS['BE']['AJAX']['tx_tev::clearcacheurl'] = 'Tev\\Tev\\Url\\Cache->clear';

Include up to date CSS Styled Content TS


<?php
$project_files = array(
	"*.php",
	"*/*.php",
	"*/*/*.php",
	"*/*/*/*.php",
	"*/*/*/*/*.php",
	"*/*/*/*/*/*.php",
	"*/*/*/*/*/*/*.php"
);

$project_files_exclude_regexes = array(
	"|^cache/|",
	"|^docs/|",
	"|^tags/|",
	"|^oauth-php/|",
	"|^modules/facebook/php-sdk/|",
	"|^dbupgrade/|",
	"|^phptidy/|",
	"|^twig/|"
);

$default_package = "StartupAPI";
$indent_char = "\t";

<?php
$project_files = array(
	"*.php",
	"*/*.php",
	"*/*/*.php",
	"*/*/*/*.php",
	"*/*/*/*/*.php",
	"*/*/*/*/*/*.php",
	"*/*/*/*/*/*/*.php"
);

$project_files_exclude_regexes = array(
	"|^cache/|",
	"|^docs/|",
	"|^tags/|",
	"|^oauth-php/|",
	"|^modules/facebook/facebook-php-sdk/|",
	"|^php-bootstrap/|",
	"|^dbupgrade/|",
	"|^phptidy/|",
	"|^twig/|"
);

$default_package = "StartupAPI";
$indent_char = "\t";

Fix phptidy configuration to exclude new facebook sdk path and php-bootstrap project


<?php

namespace spec\Rojtjo\Notifier;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Rojtjo\Notifier\Notification;

class NotificationsSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith([
            Notification::success('It is successful'),
            Notification::error('It is an error'),
        ]);
    }

    function it_is_an_iterator()
    {
        $this->shouldImplement('IteratorAggregate');
    }

    function it_is_countable()
    {
        $this->shouldImplement('Countable');
        $this->count()->shouldBe(2);
    }
}

<?php

namespace spec\Rojtjo\Notifier;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Rojtjo\Notifier\Notification;

class NotificationsSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith([
            Notification::success('It is successful'),
            Notification::error('It is an error'),
        ]);
    }

    function it_is_an_iterator()
    {
        $this->shouldImplement('IteratorAggregate');
        $this->getIterator()->shouldHaveType('ArrayIterator');
    }

    function it_is_countable()
    {
        $this->shouldImplement('Countable');
        $this->count()->shouldBe(2);
    }
}

Check if the result is indeed an ArrayIterator


<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\Bundle\LegacyIntegrationBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('webfactory_legacy_integration')
            ->children()
                ->scalarNode('legacyApplicationBootstrapFile')->defaultValue('%project.webdir%/wfD2Engine.php')->end()
                ->scalarNode('parsingMode')
                    ->isRequired()
                    ->validate()
                        ->ifNotInArray(['html5', 'xhtml10'])
                        ->thenInvalid('Invalid parsing mode (choose html5 or xhtm10)')
                ->end();

        return $treeBuilder;
    }
}

<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\Bundle\LegacyIntegrationBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('webfactory_legacy_integration');

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('webfactory_legacy_integration');
        }

        $rootNode
            ->children()
                ->scalarNode('legacyApplicationBootstrapFile')->defaultValue('%project.webdir%/wfD2Engine.php')->end()
                ->scalarNode('parsingMode')
                    ->isRequired()
                    ->validate()
                        ->ifNotInArray(['html5', 'xhtml10'])
                        ->thenInvalid('Invalid parsing mode (choose html5 or xhtm10)')
                ->end();

        return $treeBuilder;
    }
}

Fix Symfony 4.3 deprecation (Case 98936)


<?php

use Controller\ProxyController;
use GuzzleHttp\Client as HttpClient;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;

class Application extends Silex\Application
{
    /**
     * {@inheritdoc}
     *
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        $values['http_client'] = $this->share(function (Application $app) {
            return new HttpClient();
        });
        $values['controller.proxy'] = $this->share(function (Application $app) {
            return new ProxyController($app['url_generator'], $app['http_client']);
        });

        parent::__construct($values);

//        $this->register(new TwigServiceProvider(), [
//            'twig.path'    => __DIR__.'/../views',
//            'twig.options' => [
//                'cache' => is_writable(__DIR__.'/..') ? __DIR__.'/../cache/twig' : false,
//            ],
//        ]);
        $this->register(new UrlGeneratorServiceProvider());
        $this->register(new ServiceControllerServiceProvider());

        $this
            ->match('/{url}', 'controller.proxy:indexAction')
            ->bind('index')
            ->assert('url', '.*')
        ;
    }
}

<?php

use Controller\ProxyController;
use GuzzleHttp\Client as HttpClient;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\HttpKernel\KernelEvents;

class Application extends Silex\Application
{
    /**
     * {@inheritdoc}
     *
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        $values['http_client'] = $this->share(function (Application $app) {
            return new HttpClient();
        });
        $values['controller.proxy'] = $this->share(function (Application $app) {
            return new ProxyController($app['url_generator'], $app['http_client']);
        });

        parent::__construct($values);

        // Remove ResponseListener to avoid headers replacement
        $this['dispatcher'] = $this->extend('dispatcher', $this->share(function (EventDispatcherInterface $dispatcher) {
            $listeners = $dispatcher->getListeners(KernelEvents::RESPONSE);
            foreach ($listeners as $listener) {
                list($object, $method) = $listener;
                if ($object instanceof ResponseListener) {
                    $dispatcher->removeListener(KernelEvents::RESPONSE, $listener);
                }
            }

            return $dispatcher;
        }));

//        $this->register(new TwigServiceProvider(), [
//            'twig.path'    => __DIR__.'/../views',
//            'twig.options' => [
//                'cache' => is_writable(__DIR__.'/..') ? __DIR__.'/../cache/twig' : false,
//            ],
//        ]);
        $this->register(new UrlGeneratorServiceProvider());
        $this->register(new ServiceControllerServiceProvider());

        $this
            ->match('/{url}', 'controller.proxy:indexAction')
            ->bind('index')
            ->assert('url', '.*')
        ;
    }
}


<?php

use GeneaLabs\LaravelCaffeine\Http\Controllers\LaravelCaffeineController;

if (hasWebMiddleware()) {
    Route::group(['middleware' => ['web']], function () {
        Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
    });
} else {
    Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
}

function hasWebMiddleware()
{
    $routes = Route::getRoutes()->getRoutes();

    foreach ($routes as $route) {
        $actions = (array) $route->getAction();

        if (array_key_exists('middleware', $actions)
            && in_array('web', (array) $actions['middleware'])
        ) {
            return true;
        }
    }

    return false;
}

<?php

use GeneaLabs\LaravelCaffeine\Helper;
use GeneaLabs\LaravelCaffeine\Http\Controllers\LaravelCaffeineController;

if ((new Helper())->routeHasMiddlewareGroup('web')) {
    Route::group(['middleware' => ['web']], function () {
        Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
    });
} else {
    Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
}

Use helper class to determine if middleware group exists


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('master', [
    'currentSection' => 'community',
    'currentAction' => 'profile',
])

@section('content')

{{ trans('users.show.not_found.title') }}

{{ trans('users.show.not_found.reason_header') }}

{{ trans('users.show.not_found.reason_1') }}

{{ trans('users.show.not_found.reason_2') }}

{{ trans('users.show.not_found.reason_3') }}

@endsection

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('master', [
    'currentSection' => 'community',
    'currentAction' => 'profile',
    'legacyNav' => false,
])

@section('content')
    @include('layout._page_header_v4', ['params' => [
        'section' => trans('layout.header.users._'),
        'subSection' => trans('layout.header.users.show'),
        'theme' => 'default',
    ]])

{{ trans('users.show.not_found.title') }}

{{ trans('users.show.not_found.reason_header') }}

{{ trans('users.show.not_found.reason_1') }}

{{ trans('users.show.not_found.reason_2') }}

{{ trans('users.show.not_found.reason_3') }}

@endsection

Update header of user 404 page

Update header of user 404 page


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Use this file to override any settings from config.php
 *
 * For descriptions of the options please refer to config.php.
 */

// set this to a 32char random string
$config['encryption_key'] = '';

$config['upload_path'] = FCPATH.'data/uploads';

$config['index_page'] = 'index.php';

$config['cache_backend'] = "dummy";

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Use this file to override any settings from config.php
 *
 * For descriptions of the options please refer to config.php.
 */

# URL to the application
$config['base_url'] = '';

// set this to a 32char random string
$config['encryption_key'] = '';

$config['upload_path'] = FCPATH.'data/uploads';

$config['index_page'] = 'index.php';

$config['cache_backend'] = "dummy";

Put base_url in example config file

Put base_url in example config file

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>