<?php
/*
 * This file is part of the Harmony package.
 *
 * (c) Tim Goudriaan <tim@harmony-project.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Harmony\Component\ModularRouting\Manager;

use Harmony\Component\ModularRouting\Model\ModuleInterface;

/**
 * ModuleManagerInterface
 *
 * Interacts with Module entities
 *
 * @author Tim Goudriaan <tim@harmony-project.io>
 */
interface ModuleManagerInterface
{
    /**
     * Finds a single Module entity by a set of criteria.
     *
     * @param array $criteria The criteria
     *
     * @return ModuleInterface
     */
    public function findModuleBy(array $criteria);
}

<?php
/*
 * This file is part of the Harmony package.
 *
 * (c) Tim Goudriaan <tim@harmony-project.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Harmony\Component\ModularRouting\Manager;

use Harmony\Component\ModularRouting\Model\ModuleInterface;

/**
 * ModuleManagerInterface
 *
 * Interacts with Module entities
 *
 * @author Tim Goudriaan <tim@harmony-project.io>
 */
interface ModuleManagerInterface
{
    /**
     * Finds a single Module entity by a set of criteria.
     *
     * @param array $criteria The criteria
     *
     * @return ModuleInterface|null
     */
    public function findModuleBy(array $criteria);
}

Allow ModuleManager objects to return null on findModuleBy


<?php

/*
 * This file is part of Slim JSON Web Token Authentication middleware
 *
 * Copyright (c) 2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-jwt-auth
 *
 */

namespace Slim\Middleware\JwtAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

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

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
    }
}

<?php

/*
 * This file is part of Slim JSON Web Token Authentication middleware
 *
 * Copyright (c) 2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   https://github.com/tuupola/slim-jwt-auth
 *
 */

namespace Slim\Middleware\JwtAuthentication;

class RequestPathRule implements RuleInterface
{
    protected $options = array(
        "path" => "/",
        "passthrough" => array()
    );

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

    public function __invoke(\Slim\Slim $app)
    {
        /* If request path is matches passthrough should not authenticate. */
        foreach ($this->options["passthrough"] as $passthrough) {
            $passthrough = rtrim($passthrough, "/");
            if (!!preg_match("@^{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
                return false;
            }
        }

        /* Otherwise check if path matches and we should authenticate. */
        $path = rtrim($this->options["path"], "/");
        return !!preg_match("@^{$path}(/.*)?$@", $app->request->getResourceUri());
    }
}

Fix regexp logic when installed into subfolder


<?php
class Kwc_Newsletter_Subscribe_Update_20170819SubscriberLogState extends Kwf_Update
{
    public function postUpdate()
    {
        parent::postUpdate();

        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass('Kwc_Newsletter_Component') as $c) {
            $s = new Kwf_Model_Select();
            $s->whereEquals('newsletter_component_id', $c->dbId);
            $select = new Kwf_Model_Select();
            $select->where(new Kwf_Model_Select_Expr_Parent_Contains('Subscriber', $s));
            foreach (Kwf_Model_Abstract::getInstance('Kwc_Newsletter_Subscribe_LogsModel')->getRows($select) as $row) {
                if (stripos($row->message, $c->trlKwf('Activated')) !== false) {
                    $row->state = 'activated';
                } else if (stripos($row->message, $c->trlKwf('Unsubscribed')) !== false) {
                    $row->state = 'unsubscribed';
                } else if (stripos($row->message, $c->trlKwf('Subscribed')) !== false) {
                    $row->state = 'subscribed';
                }

                if ($row->isDirty('state')) $row->save();
            }
        }
    }
}

<?php
class Kwc_Newsletter_Subscribe_Update_20170819SubscriberLogState extends Kwf_Update
{
    public function postUpdate()
    {
        parent::postUpdate();
        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass('Kwc_Newsletter_Component') as $c) {
            $keywords = array(
                'subscribed' => $c->trlKwf('Subscribed'),
                'activated' => $c->trlKwf('Activated'),
                'unsubscribed' => $c->trlKwf('Unsubscribed'),
            );
            foreach ($keywords as $state => $keyword) {
                $query = "UPDATE kwc_newsletter_subscriber_logs l, kwc_newsletter_subscribers s set l.state='{$state}' WHERE l.subscriber_id=s.id AND s.newsletter_component_id='{$c->dbId}' AND LOCATE(LOWER('$keyword'), LOWER(message)) > 0";
                Kwf_Registry::get('db')->query($query);
            }
        }
    }
}

Accelerate logs update for newsletter subscribers

Current solution was slow and caused a memory limit error above 100k subscribers


<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

An uncaught Exception was encountered

Type:        <?php echo get_class($exception), "\n"; ?>
Message:     <?php echo $message, "\n"; ?>
Filename:    <?php echo $exception->getFile(), "\n"; ?>
Line Number: <?php echo $exception->getLine(); ?>

<?php if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE === TRUE): ?>

	Backtrace:
	<?php foreach ($exception->getTrace() as $error): ?>
		<?php if (isset($error['file']) && strpos($error['file'], realpath(BASEPATH)) !== 0): ?>
			File: <?php echo $error['file'], "\n"; ?>
			Line: <?php echo $error['line'], "\n"; ?>
			Function: <?php echo $error['function'], "\n\n"; ?>
		<?php endif ?>
	<?php endforeach ?>

<?php endif ?>

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

An uncaught Exception was encountered

Type:        <?php echo get_class($exception), "\n"; ?>
Message:     <?php echo $message, "\n"; ?>
Filename:    <?php echo $exception->getFile(), "\n"; ?>
Line Number: <?php echo $exception->getLine(); ?>

<?php if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE === TRUE): ?>

Backtrace:
<?php	foreach ($exception->getTrace() as $error): ?>
<?php		if (isset($error['file'])): ?>
	File: <?php echo $error['file'], "\n"; ?>
	Line: <?php echo $error['line'], "\n"; ?>
	Function: <?php echo $error['function'], "\n\n"; ?>
<?php		endif ?>
<?php	endforeach ?>

<?php endif ?>

Fix layout of cli error exception template


<?php namespace Anomaly\StreamsDistribution\Http\Controller;

use Anomaly\Streams\Platform\Application\Application;
use Anomaly\Streams\Platform\Http\Controller\PublicController;
use Anomaly\StreamsDistribution\Form\InstallerFormBuilder;

/**
 * Class InstallerController
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\StreamsDistribution\Http\Controller
 */
class InstallerController extends PublicController
{

    /**
     * Create a new InstallerController instance.
     *
     * @param InstallerFormBuilder $form
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function index(InstallerFormBuilder $form, Application $application)
    {
        if ($application->isInstalled()) {
            throw new \Exception("Please delete the config/distribution.php file before installing.");
        }

        return $form->render();
    }

    /**
     * Show the complete page.
     *
     * @return \Illuminate\View\View
     */
    public function complete()
    {
        return view('anomaly.distribution.streams::complete');
    }
}

<?php namespace Anomaly\StreamsDistribution\Http\Controller;

use Anomaly\Streams\Platform\Application\Application;
use Anomaly\Streams\Platform\Http\Controller\PublicController;
use Anomaly\StreamsDistribution\Form\InstallerFormBuilder;

/**
 * Class InstallerController
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\StreamsDistribution\Http\Controller
 */
class InstallerController extends PublicController
{

    /**
     * Create a new InstallerController instance.
     *
     * @param InstallerFormBuilder $form
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function index(InstallerFormBuilder $form, Application $application)
    {
        if ($application->isInstalled()) {
            throw new \Exception("Please delete the .env file before installing.");
        }

        return $form->render();
    }

    /**
     * Show the complete page.
     *
     * @return \Illuminate\View\View
     */
    public function complete()
    {
        return view('anomaly.distribution.streams::complete');
    }
}

Update the delete the .env file before installing message


<?php
namespace Loct\Pinger\Provider;

use \Illuminate\Config\FileLoader;
use \Illuminate\Config\Repository;
use \Illuminate\Filesystem\Filesystem;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;

class ConfigProvider implements ServiceProviderInterface
{

    public function register(Container $pimple)
    {
        $pimple['config_path'] = function ($pimple) {
            return $pimple['app_path'] . '/config';
        };

        $pimple['environment'] = function ($pimple) {
            return file_exists($pimple['config_path'] . '/dev') ? 'dev' : 'production';
        };

        $pimple['config'] = function ($pimple) {
            $filesystem = new Filesystem();
            $loader = new FileLoader($filesystem, $pimple['config_path']);

            return new Repository($loader, $pimple['environment']);
        };
    }

}

<?php
namespace Loct\Pinger\Provider;

use \Illuminate\Config\FileLoader;
use \Illuminate\Config\Repository;
use \Illuminate\Filesystem\Filesystem;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;

/**
 * Service provider for configuration related classes and parameters.
 *
 * @author herloct <herloct@gmail.com>
 */
class ConfigProvider implements ServiceProviderInterface
{

    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple An Container instance
     */
    public function register(Container $pimple)
    {
        $pimple['config_path'] = function ($pimple)
        {
            return $pimple['app_path'] . '/config';
        };

        $pimple['environment'] = function ($pimple)
        {
            return file_exists($pimple['config_path'] . '/dev') ? 'dev' : 'production';
        };

        $pimple['config'] = function ($pimple)
        {
            $filesystem = new Filesystem();
            $loader = new FileLoader($filesystem, $pimple['config_path']);

            return new Repository($loader, $pimple['environment']);
        };
    }
}

Add docblock and format source to PSR-2

Add docblock and format source to PSR-2


<?php

namespace PHPeg\Generator;

use PHPeg\Combinator\Grammar;
use PHPeg\Grammar\Parser;
use PHPeg\Grammar\ParserFactory;

class ParserGenerator
{
    private $parserFactory;

    public function __construct(ParserFactory $parserFactory)
    {
        $this->parserFactory = $parserFactory;
    }
    public function createParser($filename)
    {
        $contents = file_get_contents($filename);
        $parser = $this->parserFactory->createParser();
        $tree = $parser->parse($contents);

        $grammar = new Grammar();
        $tree->accept(new ToCombinatorVisitor($grammar));
        return new Parser($grammar);
    }
}

<?php

namespace PHPeg\Generator;

use PHPeg\Combinator\Grammar;
use PHPeg\Grammar\Parser;
use PHPeg\Grammar\ParserFactory;

class ParserGenerator
{
    private $parserFactory;

    public function __construct(ParserFactory $parserFactory)
    {
        $this->parserFactory = $parserFactory;
    }
    public function createParser($filename)
    {
        $contents = file_get_contents($filename);
        $parser = $this->parserFactory->createParser();
        $tree = $parser->parse($contents);
        $class = $tree->getName();

        if (!class_exists($class)) {
            $visitor = new ToClassVisitor();
            $tree->accept($visitor);
            eval($visitor->getResult());
        }

        return new $class();
    }
}

Use code generation instead of combinators


<?php
// This sets initial path for the include. Further includes will be initialized through PathFinder
ini_set('include_path','.'.PATH_SEPARATOR.'.'.DIRECTORY_SEPARATOR.'lib'.PATH_SEPARATOR.dirname(__FILE__).'/lib');
include 'static.php';
?>

<?php
// This sets initial path for the include. Further includes will be initialized through PathFinder
ini_set('include_path','.'.PATH_SEPARATOR.'.'.DIRECTORY_SEPARATOR.'lib'.PATH_SEPARATOR.dirname(__FILE__).'/lib');
include dirname(__FILE__).'lib/static.php';
?>

Fix including of static.php for phpfog.com


{{ Form::open(['route'=> ['sessions.store'], 'id' => 'sign_in_form']) }}

  {{ Form::hidden('candidate_id', (isset($candidate->id) ? $candidate->id : null)) }}

  {{ Form::label('first_name', 'First Name') }}
  {{ form_error('first_name', $errors) }}
  {{ Form::text('first_name') }}

  {{ Form::label('phone', 'Cell Number') }}
  {{ form_error('phone', $errors) }}
  {{ Form::text('phone') }}

  {{ Form::label('birthdate', 'Birthdate') }}
  {{ form_error('birthdate', $errors) }}
  {{ Form::text('birthdate',  null, ['placeholder' => 'MM/DD/YYYY']) }}

  {{ Form::submit('Sign In', ['class' => 'btn']) }}
{{ Form::close() }}

{{ Form::open(['route'=> ['sessions.store'], 'id' => 'sign_in_form']) }}

  {{ Form::hidden('candidate_id', (isset($candidate->id) ? $candidate->id : null)) }}

  {{ Form::label('first_name', 'First Name') }}
  {{ form_error('first_name', $errors) }}
  {{ Form::text('first_name', null, ['placeholder' => 'What\'s your name?']) }}

  {{ Form::label('birthdate', 'Birthdate') }}
  {{ form_error('birthdate', $errors) }}
  {{ Form::text('birthdate',  null, ['placeholder' => 'MM/DD/YYYY']) }}

  {{ Form::label('phone', 'Cell Number') }}
  {{ form_error('phone', $errors) }}
  {{ Form::text('phone') }} {{-- @TODO: add placeholder--}}

  {{ Form::submit('Sign In', ['class' => 'btn']) }}
{{ Form::close() }}

Make cell form match the other form.

Make cell form match the other form.


<?php

namespace Rogue\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application,
     * sourced from 'config/trustedproxy.php'.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The current proxy header mappings.
     *
     * @var array
     */
    protected $headers = [
        Request::HEADER_FORWARDED => 'FORWARDED',
        Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
        Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
        Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
        Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
    ];
}

<?php

namespace Rogue\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application,
     * sourced from 'config/trustedproxy.php'.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The current proxy header mappings.
     *
     * @var array
     */
    protected $headers = [
        Request::HEADER_FORWARDED => null, // Not set on AWS or Heroku.
        Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
        Request::HEADER_X_FORWARDED_HOST => null, // Not set on AWS or Heroku.
        Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
        Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
    ];
}

Discard 'Forwarded' & 'X-Forwarded-Host' headers.


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

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

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment() !== 'production') {
            $this->app->register(IdeHelperServiceProvider::class);
        }
    }
}

Add check for Laravel IDE Helper to work only on non-production env's


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Handle reverse proxy correctly
        if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            \URL::forceSchema($_SERVER['HTTP_X_FORWARDED_PROTO']);
        }
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Handle HTTPS reverse proxies correctly

Handle HTTPS reverse proxies correctly


<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')
            ->getMostRecentPosts()
        ;

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id);

        if (!$post) {
            throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id));
        }

        return array('post' => $post);
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')
            ->getMostRecentPosts()
        ;

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')
            ->getPublishedPost($id)
        ;

        if (!$post) {
            throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id));
        }

        return array('post' => $post);
    }
}

Use getPublishedPost when displaying a post


<?php

/*

-> /galahad/addressing/US/adminstrative-areas
<- {
     "label": "State",
     "expected_length": 2,
	 "options": {
        "AL": "Alabama"
     }
   }

*/

Route::group(['prefix' => 'galahad/addressing'], function() {

	Route::get('/{country}/administrative-areas', [
		'as' => 'galahad.addressing.administrative-areas',
		'uses' => '\\Galahad\\LaravelAddressing\\Controller@getAdministrativeAreas'
	]);

});

<?php

/*

-> /galahad/addressing/US/adminstrative-areas
<- {
     "label": "State",
     "expected_length": 2,
	 "options": {
        "AL": "Alabama"
     }
   }

*/

Route::group(['prefix' => 'galahad/addressing'], function() {

	Route::get('/{country}/administrative-areas', [
		'as' => 'galahad.addressing.administrative-areas',
		'uses' => '\\Galahad\\LaravelAddressing\\Controller@getAdministrativeAreas',
	]);

    Route::get('/countries', [
        'as' => 'galahad.addressing.countries',
        'uses' => '\\Galahad\\LaravelAddressing\\Controller@getCountries',
    ]);

});

Add route for getting all countries

Add route for getting all countries


<?php

namespace UCP\AbsenceBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`User`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=15, nullable=true)
     */
    private $phone;
}

<?php

namespace UCP\AbsenceBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=15, nullable=true)
     */
    private $phone;
}

Remove table name quoting (seems useless)


<?php
require_once "config.inc.php";

$router=$_REQUEST["router"];
$fileExtension = '';
$baseurl="./";

switch ($_REQUEST["type"]) {
    case '0':
        $type = 'factory';
        break;
    case '1':
        $type = 'sysupgrade';
        $fileExtension = '-sysupgrade';
        break;
    default:
        $type = 'factory';
}

switch ($_REQUEST["choose_comunity"]) {
    case '0':
        $community = 'notset';
        break;
    case '1':
        $community = 'nordlab';
        break;
    default:
        $community = 'notset';
}

$router = $_REQUEST["router"];

if($router === '-1') {
    backlink('Bitte wähle eine Router aus. Den genauen Namen und die Version deines Routers findest du auf seiner Unterseite.');
} else{
    if($community == 'notset'){
        backlink('Bitte gib eine Comunity an.');
    }
    else {
        $href=$baseurl.'media/firmware/' . $community . '/' . $type . '/' . $firmware_prefix . $router . $fileExtension . '.bin';
        header('location: '.$href);
        echo 'redirecting';
    }
}

function backlink($t){
    echo $t;
    ?>

<a href="<?=$_SERVER["referer"]?>">zurück<?
}

<?php
require_once "config.inc.php";

$router=$_REQUEST["router"];
$fileExtension = '';
$baseurl="./";

switch ($_REQUEST["type"]) {
    case '0':
        $type = 'factory';
        break;
    case '1':
        $type = 'sysupgrade';
        $fileExtension = '-sysupgrade';
        break;
    default:
        $type = 'factory';
}

switch ($_REQUEST["choose_comunity"]) {
    case '0':
        $community = 'notset';
        break;
    case '1':
        $community = 'nordlab';
        break;
    default:
        $community = 'notset';
}

$router = $_REQUEST["router"];

if($router === '-1') {
    backlink('Bitte wähle eine Router aus. Den genauen Namen und die Version deines Routers findest du auf seiner Unterseite.');
} else{
    if($community == 'notset'){
        backlink('Bitte gib eine Comunity an.');
    }
    else {
        $href=$baseurl.'media/firmware/' . $community . '/' . $type . '/' . $firmware_prefix . $router . $fileExtension . '.bin';
        header('Location: '.$href);
        echo 'redirecting';
    }
}

function backlink($t){
    echo $t;
    ?>

<a href="<?=$_SERVER["referer"]?>">zurück
}

Fix syntax error in fallback download script


<?php

namespace OpenDominion\Contracts\Services\Actions;

use OpenDominion\Models\Dominion;

interface RezoneActionServiceContract
{
    /**
     * Does a rezone action for a Dominion.
     *
     * @param \OpenDominion\Models\Dominion $dominion
     *   The dominion to rezone.
     * @param array $remove
     *   The land to remove.
     * @param array $add
     *   The land to add.
     *
     * @return int
     *   The amount of platinum spent.
     * @throws \OpenDominion\Exceptions\BadInputException
     * @throws \OpenDominion\Exceptions\NotEnoughResourcesException
     * @throws \OpenDominion\Exceptions\DominionLockedException
     */
    public function rezone(Dominion $dominion, array $remove, array $add);
}

<?php

namespace OpenDominion\Contracts\Services\Actions;

use OpenDominion\Exceptions\BadInputException;
use OpenDominion\Exceptions\DominionLockedException;
use OpenDominion\Exceptions\NotEnoughResourcesException;
use OpenDominion\Models\Dominion;

interface RezoneActionServiceContract
{
    /**
     * Does a rezone action for a Dominion.
     *
     * @param Dominion $dominion
     * @param array $remove Land to remove
     * @param array $add Land to add.
     * @return array
     * @throws DominionLockedException
     * @throws BadInputException
     * @throws NotEnoughResourcesException
     */
    public function rezone(Dominion $dominion, array $remove, array $add);
}

Refactor rezone action service contract

Refactor rezone action service contract


<?php

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

class CreateRacePerksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('race_perks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('race_id')->unsigned();
            $table->integer('race_perk_type_id')->unsigned();
            $table->decimal('value');
            $table->timestamps();

            $table->foreign('race_id')->references('id')->on('races');
            $table->foreign('race_perk_type_id')->references('id')->on('race_perk_types');
        });
    }

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

<?php

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

class CreateRacePerksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('race_perks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('race_id')->unsigned();
            $table->integer('race_perk_type_id')->unsigned();
            $table->float('value');
            $table->timestamps();

            $table->foreign('race_id')->references('id')->on('races');
            $table->foreign('race_perk_type_id')->references('id')->on('race_perk_types');
        });
    }

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

Use floats instead of decimals

Use floats instead of decimals


		<?php if ($content_type = Controller::$view->mime_type): ?>
			<?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?>
			 <meta http-equiv="Content-Type" content="<?php echo $content_type ?>">
		<?php endif; ?>
		<?php if ($author = Backend::getConfig('application.author')): ?>
			<meta name="author" content="<?php echo $author ?>">
		<?php endif; ?>
		<?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?>
			<meta name="description" content="<?php echo $meta_description ?>">
		<?php endif; ?>
		<meta name="generator" content="backend-php.net">
		<?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?>
			<meta name="keywords" content="<?php echo $keywords ?>">
		<?php endif; ?>
		<?php if (!empty($meta_values) && is_array($meta_values)): ?>
			<?php foreach($meta_values as $name => $value): ?>
				<meta property="<?php echo $name ?>" value="<?php echo $value ?>"/>
			<?php endforeach; ?>
		<?php endif; ?>

		<?php if ($content_type = Controller::$view->mime_type): ?>
			<?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?>
			 <meta http-equiv="Content-Type" content="<?php echo $content_type ?>">
		<?php endif; ?>
		<?php if ($author = Backend::getConfig('application.author')): ?>
			<meta name="author" content="<?php echo $author ?>">
		<?php endif; ?>
		<?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?>
			<meta name="description" content="<?php echo $meta_description ?>">
		<?php endif; ?>
		<meta name="generator" content="backend-php.net">
		<?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?>
			<meta name="keywords" content="<?php echo $keywords ?>">
		<?php endif; ?>
		<?php if (!empty($meta_values) && is_array($meta_values)): ?>
			<?php foreach($meta_values as $name => $value): ?>
				<meta property="<?php echo $name ?>" content="<?php echo $value ?>"/>
			<?php endforeach; ?>
		<?php endif; ?>

Use content instead of value for meta tags


@extends('master')

@section('title')
Micropub Config «
@stop

@section('content')

The values for your micropub endpoint.

Me (your url)

{{ $data['me'] }}

Token

{{ $data['token'] }}

Syndication Targets

@if(is_array($data['syndication']))
@foreach ($data['syndication'] as $syn)
{{ $syn['name'] }} ({{ $syn['target'] }})
@endforeach
@else{{ $data['syndication'] }}@endif

Media Endpoint

{{ $data['media-endpoint'] }}

Re-query the endpoint.

@stop

@extends('master')

@section('title')
Micropub Config «
@stop

@section('content')

The values for your micropub endpoint.

Me (your url)

{{ $data['me'] }}

Token

{{ $data['token'] }}

Syndication Targets

@if(is_array($data['syndication']))
@foreach ($data['syndication'] as $syn)
{{ $syn['name'] }} ({{ $syn['target'] }})
@endforeach
@else{{ $data['syndication'] }}@endif

Media Endpoint

{{ $data['media-endpoint'] }}

Re-query the endpoint.

Return to client.
@stop

Add a link back to the client from the config page


<?php

namespace Demo\Application\Adapter;

use Colonel\Configuration;
use Colonel\Profiler;
use Twig_Loader_Filesystem;
use Twig_Environment;

class TwigAdapter
{
    private $twig;
    private $loader;

    public function __construct(
        Configuration $configuration
    ) {
        $this->configuration = $configuration;
        $this->initialise();
    }

    public function initialise()
    {
        $this->loader = new Twig_Loader_Filesystem;

        $this->setPaths(
            $this->configuration['kernel']['root'],
            $this->configuration['twig']['paths']
        );

        $this->twig = new Twig_Environment(
            $this->loader,
            $this->configuration['twig']['options']
        );

        $this->twig->addFunction(new \Twig_SimpleFunction('dump', function() {
            echo '<pre>';
            var_dump(func_get_args());
            echo '</pre>';
        }));
    }

    public function render($view, array $parameters = [])
    {
        $view = $this->twig->render($view, $parameters);
        return $view;
    }

    private function setPaths($projectRoot, array $paths = [])
    {
        foreach ($paths as $namespace => $path) {
            $this->loader->addPath(
                sprintf('%s/%s', $projectRoot, $path),
                $namespace
            );
        }
    }
}

<?php

namespace Demo\Application\Adapter;

use Colonel\Configuration;
use Twig_Loader_Filesystem;
use Twig_Environment;

class TwigAdapter
{
    private $twig;
    private $loader;

    public function __construct(
        Configuration $configuration
    ) {
        $this->configuration = $configuration;
        $this->initialise();
    }

    public function initialise()
    {
        $this->loader = new Twig_Loader_Filesystem;

        $this->setPaths(
            $this->configuration['kernel']['root'],
            $this->configuration['twig']['paths']
        );

        $this->twig = new Twig_Environment(
            $this->loader,
            $this->configuration['twig']['options']
        );

        $this->twig->addFunction(new \Twig_SimpleFunction('dump', function() {
            echo '<pre>';
            var_dump(func_get_args());
            echo '</pre>';
        }));
    }

    public function render($view, array $parameters = [])
    {
        $view = $this->twig->render($view, $parameters);
        return $view;
    }

    private function setPaths($projectRoot, array $paths = [])
    {
        foreach ($paths as $namespace => $path) {
            $this->loader->addPath(
                sprintf('%s/%s', $projectRoot, $path),
                $namespace
            );
        }
    }
}

Remove `Profiler` functions from demo

Remove `Profiler` functions from demo


<?php

namespace Elasticquent;

trait ElasticquentConfigTrait
{
    /**
     * Get the Elasticquent config
     *
     * @param string $key the configuration key
     * @param string $prefix filename of configuration file
     * @return array configuration
     */
    protected function getElasticConfig($key = 'config', $prefix = 'elasticquent')
    {
        $config = array();

        $key = $prefix . ($key ? '.' : '') . $key;

        // Laravel 4 support
        if (!function_exists('config')) {
            $config_helper = app('config');
        } else {
            $config_helper = config();
        }

        if ($config_helper->has($key)) {
            $config = $config_helper->get($key);
        }

        return $config;
    }

}

<?php

namespace Elasticquent;

trait ElasticquentConfigTrait
{
    /**
     * Get the Elasticquent config
     *
     * @param string $key the configuration key
     * @param string $prefix filename of configuration file
     * @return array configuration
     */
    public function getElasticConfig($key = 'config', $prefix = 'elasticquent')
    {
        $config = array();

        $key = $prefix . ($key ? '.' : '') . $key;

        if (function_exists('config')) { // Laravel 5
            $config_helper = config();
        } elseif (function_exists('app')) { // Laravel 4
            $config_helper = app('config');
        } else { // stand-alone Eloquent
            $config_helper = $this->getConfigHelper();
        }

        return $config_helper->get($key);
    }

    /**
     * Inject given config file into an instance of Laravel's config
     *
     * @return object Illuminate\Config\Repository
     */
    protected function getConfigHelper()
    {
        $config_file = $this->getConfigFile();

        if (!file_exists($config_file)) {
            throw new \Exception('Config file not found.');
        }

        return new \Illuminate\Config\Repository(array('elasticquent' => require($config_file)));
    }

    /**
     * Get the config path and file name to use when Laravel framework isn't present
     * e.g. using Eloquent stand-alone or running unit tests
     *
     * @return string config file path
     */
    protected function getConfigFile()
    {
        return __DIR__.'/config/elasticquent.php';
    }
}

Remove dependency on Laravel framework being present. This allows Elasticquent to be used on projects that use Eloquent stand-alone, but more significantly makes the whole packagable more testable.


<?php

namespace Hmaus\Spas\Formatter;

class FormatterService
{
    /**
     * @var Formatter[]
     */
    private $formatters = [];

    /**
     * Add formatters to the service.
     * Done by a compiler pass
     *
     * @param Formatter $formatter
     */
    public function addFormatter(Formatter $formatter)
    {
        foreach ($formatter->getContentTypes() as $supportedType) {
            $this->formatters[$supportedType] = $formatter;
        }
    }

    /**
     * Retrieve the correct formatter by content-type string, e.g. "application/json"
     *
     * @param string $type
     * @return Formatter
     * @throws \Exception
     */
    public function getFormatterByContentType(string $type) : Formatter
    {
        if (!isset($this->formatters[$type])) {
            throw new \Exception(
                sprintf('Content-type "%s" is not supported', $type)
            );
        }

        return $this->formatters[$type];
    }
}

<?php

namespace Hmaus\Spas\Formatter;

class FormatterService
{
    /**
     * @var Formatter[]
     */
    private $formatters = [];

    /**
     * Add formatters to the service.
     * Done by a compiler pass
     *
     * @param Formatter $formatter
     */
    public function addFormatter(Formatter $formatter)
    {
        foreach ($formatter->getContentTypes() as $supportedType) {
            $this->formatters[$supportedType] = $formatter;
        }
    }

    /**
     * Retrieve the correct formatter by content-type string, e.g. "application/json"
     *
     * @param string $type
     * @return Formatter
     * @throws \Exception
     */
    public function getFormatterByContentType(string $type) : Formatter
    {
        foreach ($this->formatters as $formatter) {
            foreach ($formatter->getContentTypes() as $contentType) {
                if (strpos($type, $contentType) !== false) {
                    return $formatter;
                }
            }
        }

        throw new \Exception(
            sprintf('Content-type "%s" is not supported', $type)
        );
    }
}

Allow mime-types like 'text/html; charset=utf-8'


<?php

namespace Jade\Lexer;

/**
 * Class Jade\Lexer\MixinScanner.
 */
abstract class MixinScanner extends CaseScanner
{
    /**
     * @return object
     */
    protected function scanCall()
    {
        if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) {
            $this->consume($matches[0]);
            $token = $this->token('call', $matches[1]);

            // check for arguments
            if (preg_match('/^ *\((.*?)\)/', $this->input, $matchesArguments)) {
                $this->consume($matchesArguments[0]);
                $token->arguments = $matchesArguments[1];
            }

            return $token;
        }
    }

    /**
     * @return object
     */
    protected function scanMixin()
    {
        if (preg_match('/^mixin +(\w[-\w]*)(?: *\((.*)\))?/', $this->input, $matches)) {
            $this->consume($matches[0]);
            $token = $this->token('mixin', $matches[1]);
            $token->arguments = isset($matches[2]) ? $matches[2] : null;

            return $token;
        }
    }
}

<?php

namespace Jade\Lexer;

/**
 * Class Jade\Lexer\MixinScanner.
 */
abstract class MixinScanner extends CaseScanner
{
    /**
     * @return object
     */
    protected function scanCall()
    {
        if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) {
            $this->consume($matches[0]);
            $token = $this->token('call', $matches[1]);

            // check for arguments
            if (preg_match('/^ *' . Scanner::PARENTHESES . '/', $this->input, $matchesArguments)) {
                $this->consume($matchesArguments[0]);
                $token->arguments = trim(substr($matchesArguments[1], 1, -1));
            }

            return $token;
        }
    }

    /**
     * @return object
     */
    protected function scanMixin()
    {
        if (preg_match('/^mixin +(\w[-\w]*)(?: *\((.*)\))?/', $this->input, $matches)) {
            $this->consume($matches[0]);
            $token = $this->token('mixin', $matches[1]);
            $token->arguments = isset($matches[2]) ? $matches[2] : null;

            return $token;
        }
    }
}

Use more precise RegExp for mixin scan

Use more precise RegExp for mixin scan


<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_9;

use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroUserBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addTitleColumn($schema);
    }

    /**
     * @param Schema $schema
     */
    public static function addTitleColumn(Schema $schema)
    {
        $userTable = $schema->getTable('oro_user');
        $userTable->addColumn(
            'title',
            'string',
            [
                'length' => 255,
                'oro_options' => [
                    'extend'   => ['owner' => ExtendScope::OWNER_CUSTOM],
                    'datagrid' => ['is_visible' => true],
                    'merge'    => ['display' => true],
                ],
            ]
        );
    }
}

<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_9;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;

class OroUserBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addTitleColumn($schema);
    }

    /**
     * @param Schema $schema
     */
    public static function addTitleColumn(Schema $schema)
    {
        $userTable = $schema->getTable('oro_user');
        $userTable->addColumn(
            'title',
            'string',
            [
                'length'      => 255,
                'oro_options' => [
                    'extend'   => ['owner' => ExtendScope::OWNER_CUSTOM],
                    'datagrid' => ['is_visible' => false],
                ],
            ]
        );
    }
}

BAP-6919: Add Title field to User
  - do not show in grid by default


<?php

use PicoFarad\Router;
use PicoFarad\Response;
use PicoFarad\Request;
use PicoFarad\Session;
use PicoFarad\Template;

// Flush console messages
Router\get_action('flush-console', function() {

    @unlink(DEBUG_FILENAME);
    Response\redirect('?action=console');
});

// Display console
Router\get_action('console', function() {

    Response\html(Template\layout('console', array(
        'content' => @file_get_contents(DEBUG_FILENAME),
        'title' => t('Console')
    )));
});

<?php

use PicoFarad\Router;
use PicoFarad\Response;
use PicoFarad\Request;
use PicoFarad\Session;
use PicoFarad\Template;

// Flush console messages
Router\get_action('flush-console', function() {

    @unlink(DEBUG_FILENAME);
    Response\redirect('?action=console');
});

// Display console
Router\get_action('console', function() {

    Response\html(Template\layout('console', array(
        'content' => @file_get_contents(DEBUG_FILENAME),
        'menu' => 'config',
        'title' => t('Console')
    )));
});

Fix PHP Notice: Undefined variable: menu


<?php
/**
 * Encapsulation of model manipulation and business rules
 */
abstract class Jaded_Service
{
	/**
	 * Singleton instances of services
	 */
	protected static $aInstances = array();

	////////////////////////////////////////////////////////////////////////////////
	// PUBLIC STATIC //////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////

	/**
	 * Returns an instance of the requested service
	 * @param string $sType
	 * @return Jaded_Service
	 * @throws Jaded_Service_Exception if the type requested is an invalid service
	 */
	public static function instance($sType)
	{
		if (empty(self::$aInstances[$sType])) {
			if (!is_subclass_of($sType, __CLASS__)) {
				throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType);
			}
			self::$aInstances[$sType] = new $sType();
		}
		return self::$aInstances[$sType];
	}
}

<?php
/**
 * Encapsulation of model manipulation and business rules
 */
abstract class Jaded_Service
{
	/**
	 * Singleton instances of services
	 */
	protected static $aInstances = array();

	////////////////////////////////////////////////////////////////////////////////
	// PUBLIC STATIC //////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////

	/**
	 * Returns an instance of the requested service
	 * @param string $sType
	 * @return Jaded_Service
	 * @throws Jaded_Service_Exception if the type requested is an invalid service
	 */
	public static function instance($sType)
	{
		if (empty(self::$aInstances[$sType])) {
			if (!is_subclass_of($sType, __CLASS__)) {
				throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType);
			}
			self::set($sType, new $sType());
		}
		return self::$aInstances[$sType];
	}

	/**
	 * Set a service instance
	 * @param string $sType
	 * @param Jaded_Service $oService
	 */
	public static function set($sType, Jaded_Service $oService)
	{
		self::$aInstances[$sType] = $oService;
	}
}

Allow setting of services, mainly for testing purposes.


<?php

namespace Tsuka\DB\Binder;

use Katana\Sdk\Action;
use Tsuka\DB\Entity;

/**
 * Set a multiple relation of an Entity with a list of ids.
 *
 * The Entity must have an id property to set the relationship.
 *
 * The list of ids is looked for in an Entity field with the name of the
 * relation as a comma separated list.
 *
 * This Binder relies on a service named as the relation with a "list" action
 * that accepts an "ids" parameter with a comma separated list.
 *
 * @package Tsuka\DB\Binder
 */
class IdListBinder implements BinderInterface
{
    /**
     * @param Action $action
     * @param Entity $entity
     * @param string $relation
     */
    public function bind(Action $action, Entity $entity, string $relation)
    {
        if (!$entity->$relation) {
            return;
        }

        $action->relateMany(
            $entity->id,
            $relation,
            explode(',', $entity->$relation)
        );

        $action->deferCall(
            $relation,
            $action->getVersion(),
            'list',
            [
                $action->newParam('ids', $entity->$relation),
            ]
        );
    }
}

<?php

namespace Tsuka\DB\Binder;

use Katana\Sdk\Action;
use Tsuka\DB\Entity;

/**
 * Set a multiple relation of an Entity with a list of ids.
 *
 * The Entity must have an id property to set the relationship.
 *
 * The list of ids is looked for in an Entity field with the name of the
 * relation as a comma separated list.
 *
 * This Binder relies on a service named as the relation with a "list" action
 * that accepts an "ids" parameter with a comma separated list.
 *
 * @package Tsuka\DB\Binder
 */
class IdListBinder implements BinderInterface
{
     /**
     * @var string
     */
    public $version = '';

    /**
     * @param   string  $version        The version to execute the bind against
     */
    public function __construct(string $version)
    {
        $this->version = $version;
    }

    /**
     * @param Action $action
     * @param Entity $entity
     * @param string $relation
     */
    public function bind(Action $action, Entity $entity, string $relation, string $version)
    {
        if (!$entity->$relation) {
            return;
        }

        $action->relateMany(
            $entity->id,
            $relation,
            explode(',', $entity->$relation)
        );

        $action->deferCall(
            $relation,
            $this->version,
            'list',
            [
                $action->newParam('ids', $entity->$relation),
            ]
        );
    }
}

Add version to construct and bind

Add version to construct and bind


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Locale\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Locales;

class Locale implements LocaleInterface
{
    use TimestampableTrait;

    /** @var mixed  */
    protected $id = null;

    protected ?string $code = null;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    public function __toString(): string
    {
        return (string) $this->getName();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(?string $code): void
    {
        $this->code = $code;
    }

    public function getName(?string $locale = null): ?string
    {
        return Locales::getName($this->getCode(), $locale);
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Locale\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Locales;

class Locale implements LocaleInterface
{
    use TimestampableTrait;

    /** @var mixed  */
    protected $id = null;

    /**
     * @var string|null
     */
    protected $code;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    public function __toString(): string
    {
        return (string) $this->getName();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(?string $code): void
    {
        $this->code = $code;
    }

    public function getName(?string $locale = null): ?string
    {
        return Locales::getName($this->getCode(), $locale);
    }
}

Remove types in public and protected properies in not final classes (in components)


<?php

namespace HeyDoc;

class Config
{
    protected $config;

    /**
     *
     *
     * @param array  $config  The container
     */
    public function __construct(array $config)
    {

        $this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
    }

    public function has($key)
    {
        return $this->config->offsetExists($key);
    }

    public function get($key)
    {
        return $this->config->offsetGet($key);
    }

    public function getDefaults()
    {
        return array(
            'theme'      => 'default',
            'debug'      => false,
            'title'      => 'HeyDoc',
            'theme_dirs' => array(),
            // 'cache_dir'  => getcwd() . '/cache',
        );
    }
}

<?php

namespace HeyDoc;

class Config
{
    protected $config;

    /**
     *
     *
     * @param array  $config  The container
     */
    public function __construct(array $config)
    {
        $this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
    }

    public function has($key)
    {
        return $this->config->offsetExists($key);
    }

    public function get($key)
    {
        if (! $this->has($key)) {
            throw new \RuntimeException(sprintf('%s does not contain value for key "%s"', __CLASS__, $key));
        }
        return $this->config->offsetGet($key);
    }

    public function getDefaults()
    {
        return array(
            'theme'      => 'default',
            'debug'      => false,
            'title'      => 'HeyDoc',
            'theme_dirs' => array(),
            // 'cache_dir'  => getcwd() . '/cache',
        );
    }

    public function __call($name, $arguments)
    {
        return $this->get($name);
    }
}

Clean config and update it form twig call


<?php

namespace League\StatsD\Test;

class ConfigurationTest extends TestCase
{

    /**
     * Large ports should be out of range
     * @expectedException League\StatsD\Exception\ConfigurationException
     */
    public function testLargePort()
    {
        $this->client->configure(array(
            'port' => 65536
        ));
    }

    /**
     * Non-integer ports are not acceptable
     * @expectedException League\StatsD\Exception\ConfigurationException
     */
    public function testStringPort()
    {
        $this->client->configure(array(
            'port' => 'not-integer'
        ));
    }

    /**
     * Default Port
     */
    public function testDefaultPort()
    {
        $this->assertEquals($this->client->getPort(), 8125);
    }

    /**
     * Valid Port
     */
    public function testValidPort()
    {
        $this->client->configure(array(
            'port' => 1234
        ));
        $this->assertEquals($this->client->getPort(), 1234);
    }

}

<?php

namespace League\StatsD\Test;

class ConfigurationTest extends TestCase
{

    /**
     * Large ports should be out of range
     * @expectedException League\StatsD\Exception\ConfigurationException
     */
    public function testLargePort()
    {
        $this->client->configure(array(
            'port' => 65536
        ));
    }

    /**
     * Test that user can configure port 0
     */
    public function testPort0()
    {
        $this->client->configure(array(
            'port' => 0
        ));

        $this->assertEquals($this->client->getPort(), 0);
    }

    /**
     * Non-integer ports are not acceptable
     * @expectedException League\StatsD\Exception\ConfigurationException
     */
    public function testStringPort()
    {
        $this->client->configure(array(
            'port' => 'not-integer'
        ));
    }

    /**
     * Negative ports are not acceptable
     * @expectedException League\StatsD\Exception\ConfigurationException
     */
    public function testNegativePort()
    {
        $this->client->configure(array(
            'port' => -1
        ));
    }

    /**
     * Default Port
     */
    public function testDefaultPort()
    {
        $this->assertEquals($this->client->getPort(), 8125);
    }

    /**
     * Valid Port
     */
    public function testValidPort()
    {
        $this->client->configure(array(
            'port' => 1234
        ));
        $this->assertEquals($this->client->getPort(), 1234);
    }

}

Add unit testing for new port options

Add unit testing for new port options


<?php

use Fhaculty\Graph\Algorithm\Complete;

use Fhaculty\Graph\Algorithm\Directed;

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges());
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs

        $alg = new Directed($graph);
        $this->assertTrue($alg->isDirected());

        $alg = new Complete($graph);
        $this->assertTrue($alg->isComplete());
    }
}

<?php

use Fhaculty\Graph\Algorithm\Complete;

use Fhaculty\Graph\Algorithm\Directed;

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges());
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs

        $alg = new Directed($graph);
        $this->assertTrue($alg->isDirected());

        $alg = new Complete($graph);
        $this->assertTrue($alg->isComplete());
    }
}

Replace all occurances of $graph->getNumberOfVertices() replaced with count($graph->getVertices())


<?php
namespace Icicle\Tests\Socket\Stream;

use Icicle\Loop;
use Icicle\Tests\Socket\TestCase;

abstract class StreamTest extends TestCase
{
    const CHUNK_SIZE = 8192;
    const TIMEOUT = 0.1;
    const HWM = 8192;
    const WRITE_STRING = 'abcdefghijklmnopqrstuvwxyz';

    /**
     * @return \Icicle\Stream\StreamInterface[]
     */
    abstract public function createStreams();

    public function tearDown()
    {
        Loop\clear();
    }
}

<?php
namespace Icicle\Tests\Socket\Stream;

use Icicle\Loop;
use Icicle\Loop\SelectLoop;
use Icicle\Tests\Socket\TestCase;

abstract class StreamTest extends TestCase
{
    const CHUNK_SIZE = 8192;
    const TIMEOUT = 0.1;
    const WRITE_STRING = 'abcdefghijklmnopqrstuvwxyz';

    /**
     * @return \Icicle\Stream\StreamInterface[]
     */
    abstract public function createStreams();

    public function setUp()
    {
        Loop\loop(new SelectLoop());
    }
}

Update stream test based class

Update stream test based class


<?php

namespace EchoPush;

use CentralIdLookup;
use EchoEvent;
use JobQueueGroup;
use User;

class PushNotifier {

	/**
	 * Submits a notification derived from an Echo event to each push notifications service
	 * subscription found for a user, via a configured service handler implementation
	 * @param User $user
	 * @param EchoEvent $event
	 */
	public static function notifyWithPush( User $user, EchoEvent $event ): void {
		JobQueueGroup::singleton()->push( self::createJobForUser( $user ) );
	}

	/**
	 * @param User $user
	 * @return NotificationRequestJob
	 */
	private static function createJobForUser( User $user ): NotificationRequestJob {
		$centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user );
		$params = [ 'centralId' => $centralId ];
		return new NotificationRequestJob( 'EchoPushNotificationRequest', $params );
	}

}

<?php

namespace EchoPush;

use CentralIdLookup;
use EchoAttributeManager;
use EchoEvent;
use JobQueueGroup;
use User;

class PushNotifier {

	/**
	 * Submits a notification derived from an Echo event to each push notifications service
	 * subscription found for a user, via a configured service handler implementation
	 * @param User $user
	 * @param EchoEvent $event
	 */
	public static function notifyWithPush( User $user, EchoEvent $event ): void {
		$attributeManager = EchoAttributeManager::newFromGlobalVars();
		$userEnabledEvents = $attributeManager->getUserEnabledEvents( $user, 'push' );
		if ( in_array( $event->getType(), $userEnabledEvents ) ) {
			JobQueueGroup::singleton()->push( self::createJobForUser( $user ) );
		}
	}

	/**
	 * @param User $user
	 * @return NotificationRequestJob
	 */
	private static function createJobForUser( User $user ): NotificationRequestJob {
		$centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user );
		$params = [ 'centralId' => $centralId ];
		return new NotificationRequestJob( 'EchoPushNotificationRequest', $params );
	}

}

Push: Check that the event type is enabled before scheduling job

It is the notifier implementation's responsibility to check the user's
notification preferences before sending a notification. This adds the
check.

Change-Id: I4b7fd7ea444f5a6db6d79fadb48a440d4fdf0ac9


<?php
/**
 * Welcome to the PHP.Gt WebEngine!
 *
 * This file is the entry point to the WebEngine. The whole request-response lifecycle is
 * documented at https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
 */

/**
 * Before any code is executed, return false here if a static file is requested. When running the
 * PHP inbuilt server, this will output the static file. Other webservers should not get to this
 * point, but it's safe to prevent unnecessary execution.
 */
$uri = urldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
if(is_file($_SERVER["DOCUMENT_ROOT"] . $uri)) {
	return false;
}

/**
 * Require the Composer autoloader, so the rest of the script can locate classes by their namespace,
 * rather than having to know where on disk the files exist.
 * @see https://getcomposer.org/doc/00-intro.md
 */
require(__DIR__ . "/vendor/autoload.php");

/**
 * That's all we need to start the request-response lifecycle. Buckle up and enjoy the ride!
 * @see https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
 */
Gt\WebEngine\Lifecycle::Start();

<?php
/**
 * Welcome to the PHP.Gt WebEngine!
 *
 * This file is the entry point to the WebEngine. The whole request-response lifecycle is
 * documented at https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
 */

/**
 * Before any code is executed, return false here if a static file is requested. When running the
 * PHP inbuilt server, this will output the static file. Other webservers should not get to this
 * point, but it's safe to prevent unnecessary execution.
 */
$uri = urldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
if(is_file($_SERVER["DOCUMENT_ROOT"] . $uri)) {
	return false;
}

/**
 * Require the Composer autoloader, so the rest of the script can locate classes by their namespace,
 * rather than having to know where on disk the files exist.
 * @see https://getcomposer.org/doc/00-intro.md
 */
require(__DIR__ . "/vendor/autoload.php");

/**
 * That's all we need to start the request-response lifecycle. Buckle up and enjoy the ride!
 * @see https://github.com/PhpGt/WebEngine/wiki/From-request-to-response
 */
Gt\WebEngine\Lifecycle::start();

Fix case on start function

Fix case on start function


<?php namespace App\Http\Controllers;

use App\Models\Category as Category;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class CategoriesController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return \Response::json(array("data" => array("categories" => Category::categoryAsc()->get())));
    }

    /**
     * Get the category JSON by a given category_id
     * route: api/categories/<category_id>
     * @param  int $category_id
     * @return json {"success": true or false, "data": {"category": category}};
     */
    public function show($categoryd)
    {
        $category = Category::find($categoryId);
        if ($category == NULL) {
            return \Response::json(array("success" => false));
        }
        return \Response::json(["success" => true, "data" => array("category" => $category)]);
    }

}

<?php namespace App\Http\Controllers;

use App\Models\Category as Category;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class CategoriesController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $json = \Cache::rememberForever('categories_json', function()
        {
            return ['data' => ['categories' => Category::categoryAsc()->get()]];
        });
        return \Response::json($json);
    }

    /**
     * Get the category JSON by a given category_id
     * route: api/categories/<category_id>
     * @param  int $category_id
     * @return json {"success": true or false, "data": {"category": category}};
     */
    public function show($categoryd)
    {
        $category = Category::find($categoryId);
        if ($category == NULL) {
            return \Response::json(array("success" => false));
        }
        return \Response::json(["success" => true, "data" => array("category" => $category)]);
    }

}

Test caching with categories API callback (we aren't updating categories anyway).


 <?php Options::out('title'); _e(' is powered by'); ?> Habari <?php _e('and a huge amount of'); ?>
 <a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?>" rel="nofollow">C8H10N4O2

 <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e('Atom Entries'); ?> <?php _e('and'); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e('Atom Comments'); ?>

<?php $theme->footer(); ?>

<?php
// Uncomment this to view your DB profiling info
// include 'db_profiling.php';
?>

 <?php Options::out('title'); _e(' is powered by'); ?> Habari <?php _e('and a huge amount of'); ?>
 <a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?>" rel="nofollow">C8H10N4O2

 <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e('Atom Entries'); ?> <?php _e('and'); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e('Atom Comments'); ?>

<?php $theme->footer(); ?>

<?php
/* In order to see DB profiling information:
 1. Insert this line in your config file: define( 'DEBUG', TRUE );
 2.Uncomment the followng line
 */
// include 'db_profiling.php';
?>

Clarify that debugging has to be turned on for DB profiling to work.

git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@2619 653ae4dd-d31e-0410-96ef-6bf7bf53c507


<?php
/**
 * User: stonedz
 * Date: 2/2/15
 * Time: 12:29 PM
 */

namespace pff\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateDatabase extends Command {

    protected function configure() {
        $this
            ->setName('db:updateDb')
            ->setDescription('Backups and then updates the db using doctrine orm:schema-tool:update --force');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        exec('vendor/bin/doctrine',$res);
        foreach ($res as $r) echo $r."\n";
    }
}

<?php
/**
 * User: stonedz
 * Date: 2/2/15
 * Time: 12:29 PM
 */

namespace pff\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateDatabase extends Command {

    protected function configure() {
        $this
            ->setName('db:updateDb')
            ->setDescription('Backups and then updates the db using doctrine orm:schema-tool:update --force')
            ->addOption(
                'no-backup',
                null,
                InputOption::VALUE_NONE
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        if(!$input->getOption('no-backup')) {

            $command   = $this->getApplication()->find('db:backupDb');
            $arguments = array('command' => 'db:backupDb');
            $inputa    = new ArrayInput($arguments);
            $ret       = $command->run($inputa, $output);

        }

        exec('vendor/bin/doctrine orm:schema-tool:update --force',$res);
        foreach ($res as $r) echo $r."\n";
    }
}

Update Db command for doctrine

Update Db command for doctrine


<?php
/**
 * Nexmo Client Library for PHP
 *
 * @copyright Copyright (c) 2016 Nexmo, Inc. (http://nexmo.com)
 * @license   https://github.com/Nexmo/nexmo-php/blob/master/LICENSE.txt MIT License
 */

namespace Nexmo\Calls\Call;
use Nexmo\Entity\CollectionAwareInterface;
use Nexmo\Entity\CollectionAwareTrait;
use Nexmo\Entity\JsonSerializableInterface;

/**
 * Lightweight resource, only has put / delete.
 */
class Stream implements JsonSerializableInterface, CollectionAwareInterface
{
    use CollectionAwareTrait;

    protected $id;

    protected $data = [];

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

    public function getId()
    {
        return $this->id;
    }

    public function setUrl($url)
    {
        $this->data['stream_url'] = (string) $url;
    }

    public function setLoop($times)
    {
        $this->data['loop'] = (int) $times;
    }

    public function put($stream = null)
    {
        if(!$stream){
            $stream = $this;
        }

        return $this->getCollection()->put($stream, $this->getId(), 'stream');
    }

    public function delete()
    {
        return $this->getCollection()->delete($this, 'stream');
    }

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

}

<?php
/**
 * Nexmo Client Library for PHP
 *
 * @copyright Copyright (c) 2016 Nexmo, Inc. (http://nexmo.com)
 * @license   https://github.com/Nexmo/nexmo-php/blob/master/LICENSE.txt MIT License
 */

namespace Nexmo\Calls\Call;
use Nexmo\Entity\CollectionAwareInterface;
use Nexmo\Entity\CollectionAwareTrait;
use Nexmo\Entity\JsonSerializableInterface;

/**
 * Lightweight resource, only has put / delete.
 */
class Stream implements JsonSerializableInterface, CollectionAwareInterface
{
    use CollectionAwareTrait;

    protected $id;

    protected $data = [];

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

    public function getId()
    {
        return $this->id;
    }

    public function setUrl($url)
    {
        if(!is_array($url)){
            $url = array($url);
        }

        $this->data['stream_url'] = $url;
    }

    public function setLoop($times)
    {
        $this->data['loop'] = (int) $times;
    }

    public function put($stream = null)
    {
        if(!$stream){
            $stream = $this;
        }

        return $this->getCollection()->put($stream, $this->getId(), 'stream');
    }

    public function delete()
    {
        return $this->getCollection()->delete($this, 'stream');
    }

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

}

Fix for stream wanting arrays.

Fix for stream wanting arrays.


<?php

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

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

<?php

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

Remove useless call to composer autoloader.


<?php

namespace RIPS\Connector\Entities;

use Psr\Http\Message\ResponseInterface;

class Response
{
    /** @var ResponseInterface */
    private $response;

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

    /**
     * Get original Guzzle response.
     * @return ResponseInterface
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * @return \Psr\Http\Message\StreamInterface
     */
    public function getRawData()
    {
        return $this->response->getBody();
    }

    /**
     * @return \stdClass[]|\stdClass
     */
    public function getDecodedData()
    {
        return json_decode($this->response->getBody());
    }
}

<?php

namespace RIPS\Connector\Entities;

use Psr\Http\Message\ResponseInterface;

class Response
{
    /** @var ResponseInterface */
    private $response;

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

    /**
     * Get original Guzzle response.
     * @return ResponseInterface
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * @return \Psr\Http\Message\StreamInterface
     */
    public function getRawData()
    {
        return $this->response->getBody();
    }

    /**
     * @return mixed
     */
    public function getDecodedData()
    {
        return json_decode($this->response->getBody());
    }
}

Change type-hint of getDecodedData to mixed


<?php echo $copyright; ?>

    <?php make_scripts($script); ?>

Remove redundant blank line

Remove redundant blank line [ci skip]


<?php namespace Octommerce\Octommerce\Models;

use Model;

/**
 * City Model
 */
class City extends Model
{

    /**
     * @var string The database table used by the model.
     */
    public $table = 'octommerce_octommerce_cities';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [
        'state' => 'RainLab\Location\Models\State',
    ];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}

<?php namespace Octommerce\Octommerce\Models;

use Model;

/**
 * City Model
 */
class City extends Model
{

    /**
     * @var string The database table used by the model.
     */
    public $table = 'octommerce_octommerce_cities';

    public $timestamps = false;
    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [
        'state' => 'RainLab\Location\Models\State',
    ];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}

Disable timestamps on city model

Disable timestamps on city model


<?php

use Illuminate\Console\Command;

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		SSH::run([
			"cd " . @$_ENV["SSH_ROOT"],
			"php artisan down",
			"git pull origin develop",
			"composer update",
			"php artisan up",
		]);
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}
}

<?php

use Illuminate\Console\Command;

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		SSH::run([
			"cd " . @$_ENV["SSH_ROOT"],
			"php artisan down",
			"git pull origin develop",
			"composer update",
			"php artisan up",
			"aglio -i API.md -o public/docs/index.html",
		]);
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}
}

Add documentation generation to the deploy step


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
        'major',
        'semester'
    ];

    protected $visible = [
        'id',
        'first_name',
        'last_name',
        'email',
        'password',
        'major',
        'semester',
        'teams'
    ];

    protected static function boot()
    {
        // TODO send email with randomly generated password
        Student::created(function($student) {
            $student->university->user()->create([
                'name' => $student->first_name . ' ' . $student->last_name,
                'email' => $student->email,
                'password' => bcrypt('1234'),
                'role' => 'professor'
            ]);
        });
    }

    /**
     * A student is enrolled in an university.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function university()
    {
        return $this->belongsTo('App\University');
    }

    /**
     * A student belongs to many groups.
     *
     * @return $this
     */
    public function teams()
    {
        return $this->belongsToMany('App\Team')
                    ->withPivot('role');
    }

    /**
     * Get the user instance of the student.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
        'major',
        'semester'
    ];

    protected $visible = [
        'id',
        'first_name',
        'last_name',
        'email',
        'password',
        'major',
        'semester',
        'teams'
    ];

    protected static function boot()
    {
        // TODO send email with randomly generated password
        Student::created(function($student) {
            $student->university->user()->create([
                'name' => $student->first_name . ' ' . $student->last_name,
                'email' => $student->email,
                'password' => bcrypt('1234'),
                'role' => 'student'
            ]);
        });
    }

    /**
     * A student is enrolled in an university.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function university()
    {
        return $this->belongsTo('App\University');
    }

    /**
     * A student belongs to many groups.
     *
     * @return $this
     */
    public function teams()
    {
        return $this->belongsToMany('App\Team')
                    ->withPivot('role');
    }

    /**
     * Get the user instance of the student.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Fix role in student model boot up

Fix role in student model boot up


<?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade {

	public static function getFacadeAccessor() {
        return class_exists('Imagick') ? 'image/imagick' : 'image/gd';
    }

}

<?php
namespace Concrete\Core\Support\Facade;

class Image extends Facade
{

    public static function getFacadeAccessor()
    {

        if (class_exists('Imagick')) {
            $imagick = new \Imagick();
            $v = $imagick->getVersion();
            list($version, $year, $month, $day, $q, $website) = sscanf(
                $v['versionString'],
                'ImageMagick %s %04d-%02d-%02d %s %s');

            if (version_compare($version, '6.2.9') < 1) {
                return 'image/gd';
            } else {
                return 'image/imagick';
            }
        }

        return 'image/gd';
    }

}

Adjust image facade to detect imagemagick version.


<?php
/**
 * Eadrax application/classes/view/layout.php
 *
 * @package   View
 * @author    Dion Moult <dion@thinkmoult.com>
 * @copyright (c) 2012 Dion Moult
 * @license   ISC http://opensource.org/licenses/isc-license.txt
 * @link      http://wipup.org/
 */

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

/**
 * Sets up partials, essentially a core file for KOstache.
 *
 * @package View
 */
abstract class View_Layout extends Kostache_Layout
{
    /**
     * Mustache partials like headers, footers, sidebars
     * @var array
     */
    protected $_partials = array(
        'header' => 'partial/header',
        'footer' => 'partial/footer'
    );

    /**
     * Returns core partials.
     *
     * @return array
     */
    public function get_partials()
    {
        return $this->_partials;
    }
}

<?php
/**
 * Eadrax application/classes/view/layout.php
 *
 * @package   View
 * @author    Dion Moult <dion@thinkmoult.com>
 * @copyright (c) 2012 Dion Moult
 * @license   ISC http://opensource.org/licenses/isc-license.txt
 * @link      http://wipup.org/
 */

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

/**
 * Sets up partials, essentially a core file for KOstache.
 *
 * @package View
 */
abstract class View_Layout extends Kostache_Layout
{
    /**
     * Mustache partials like headers, footers, sidebars
     * @var array
     */
    protected $_partials = array(
        'header' => 'partial/header',
        'footer' => 'partial/footer'
    );

    /**
     * Base url of website.
     * @var string
     */
    public $baseurl;

    /**
     * Sets up useful sitewide variables.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->baseurl = URL::base();
    }

    /**
     * Returns core partials.
     *
     * @return array
     */
    public function get_partials()
    {
        return $this->_partials;
    }
}

Allow all template files to use {{baseurl}}


<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs;

use Symfony\Component\ClassLoader\ClassLoader;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;

class TestKernel extends Kernel
{
    public function __construct()
    {
        parent::__construct('test_stub_env', true);
    }

    public function init()
    {
    }

    public function getRootDir()
    {
        return sys_get_temp_dir() . '/translation-test-stub-cache';
    }

    public function registerBundles()
    {
        $loader = new ClassLoader();

        $loader->addPrefix('SomeProject\\', array(__DIR__));
        $loader->addPrefix('SomeAnotherProject\\', array(__DIR__));
        $loader->register();

        return array(
            new \SomeProject\Bundle\SomeBundle\SomeBundle(),
            new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle()
        );
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs;

use Symfony\Component\ClassLoader\UniversalClassLoader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class TestKernel extends Kernel
{
    public function __construct()
    {
        parent::__construct('test_stub_env', true);
    }

    public function init()
    {
    }

    public function getRootDir()
    {
        return sys_get_temp_dir() . '/translation-test-stub-cache';
    }

    public function registerBundles()
    {
        $loader = new UniversalClassLoader();

        $loader->registerNamespace('SomeProject\\', array(__DIR__));
        $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__));
        $loader->register();

        return array(
            new \SomeProject\Bundle\SomeBundle\SomeBundle(),
            new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle()
        );
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}

BAP-16497: Change ClassLoader component
- test failing tests


<?php
/**
 * Represents a registration to an event.
 *
 * @package silverstripe-eventmanagement
 */
class EventRegistration extends DataObject {

	public static $db = array(
		'Name'      => 'Varchar(255)',
		'Email'     => 'Varchar(255)',
		'Places'    => 'Int',
		'Confirmed' => 'Boolean',
		'Token'     => 'Varchar(48)'
	);

	public static $has_one = array(
		'Time'   => 'RegisterableDateTime',
		'Ticket' => 'EventTicket',
		'Member' => 'Member'
	);

	public static $summary_fields = array(
		'Name'         => 'Name',
		'Email'        => 'Email',
		'Event.Title'  => 'Event',
		'Places'       => 'Places',
		'DatesSummary' => 'Date(s)',
		'TimesSummary' => 'Time(s)'
	);

	protected function onBeforeWrite() {
		if (!$this->isInDB()) {
			$generator = new RandomGenerator();
			$this->Token = $generator->generateHash('sha1');
		}

		parent::onBeforeWrite();
	}

	/**
	 * @return string
	 */
	public function DatesSummary() {
		return $this->Time()->_Dates();
	}

	/**
	 * @return string
	 */
	public function TimesSummary() {
		return $this->Time()->_Times();
	}

}

<?php
/**
 * Represents a registration to an event.
 *
 * @package silverstripe-eventmanagement
 */
class EventRegistration extends DataObject {

	public static $db = array(
		'Name'      => 'Varchar(255)',
		'Email'     => 'Varchar(255)',
		'Confirmed' => 'Boolean',
		'Token'     => 'Varchar(48)'
	);

	public static $has_one = array(
		'Time'   => 'RegisterableDateTime',
		'Member' => 'Member'
	);

	public static $many_many = array(
		'Tickets' => 'EventTicket'
	);

	public static $many_many_extraFields = array(
		'Tickets' => array('Quantity' => 'Int')
	);

	public static $summary_fields = array(
		'Name'         => 'Name',
		'Email'        => 'Email',
		'Event.Title'  => 'Event',
		'Places'       => 'Places',
		'DatesSummary' => 'Date(s)',
		'TimesSummary' => 'Time(s)'
	);

	protected function onBeforeWrite() {
		if (!$this->isInDB()) {
			$generator = new RandomGenerator();
			$this->Token = $generator->generateHash('sha1');
		}

		parent::onBeforeWrite();
	}

	/**
	 * @return string
	 */
	public function DatesSummary() {
		return $this->Time()->_Dates();
	}

	/**
	 * @return string
	 */
	public function TimesSummary() {
		return $this->Time()->_Times();
	}

}

Allow each event registration to have several ticket types attached to it, each with a different quantity.


<?php
/**
 * Application Class
 *
 * @author Gerry Demaret <gerry@tigron.be>
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author David Vandemaele <david@tigron.be>
 */

namespace Skeleton\Console;

class Application extends \Symfony\Component\Console\Application {

	/**
	 * Constructor
	 *
	 * @access public
	 */
	public function __construct() {
		parent::__construct('Skeleton Console');
	}

	/**
	 * Add commands
	 *
	 * @access public
	 */
	public function add_commands() {
		/**
		 * Search for other Skeleton packages installed
		 */
		$skeletons = \Skeleton\Core\Skeleton::get_all();

		/**
		 * Check in every Skeleton package for commands
		 */
		foreach ($skeletons as $skeleton) {

			if (!file_exists($skeleton->path . '/console')) {
				continue;
			}

			$files = scandir($skeleton->path . '/console');

			foreach ($files as $file) {
				if ($file[0] == '.') {
					continue;
				}
				require_once $skeleton->path . '/console/' . $file;

				$file = str_replace('.php', '', $file);

				$classname = '\Skeleton\Console\Command\\' . ucfirst(str_replace('skeleton-', '', $skeleton->name)) . '_' . ucfirst($file);
				$this->add(new $classname);
			}
		}
	}

}

<?php
/**
 * Application Class
 *
 * @author Gerry Demaret <gerry@tigron.be>
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author David Vandemaele <david@tigron.be>
 */

namespace Skeleton\Console;

class Application extends \Symfony\Component\Console\Application {

	/**
	 * Constructor
	 *
	 * @access public
	 */
	public function __construct() {
		parent::__construct('Skeleton Console');
	}

	/**
	 * Add commands
	 *
	 * @access public
	 */
	public function add_commands() {
		/**
		 * Search for other Skeleton packages installed
		 */
		$skeletons = \Skeleton\Core\Skeleton::get_all();

		/**
		 * Check in every Skeleton package for commands
		 */
		foreach ($skeletons as $skeleton) {

			if (!file_exists($skeleton->path . '/console')) {
				continue;
			}

			$files = scandir($skeleton->path . '/console');

			foreach ($files as $file) {
				if ($file[0] == '.') {
					continue;
				}
				require_once $skeleton->path . '/console/' . $file;

				$file = str_replace('.php', '', $file);

				$classname = '\Skeleton\Console\Command\\' . ucfirst(str_replace('-', '_', str_replace('skeleton-', '', $skeleton->name))) . '_' . ucfirst($file);
				$this->add(new $classname);
			}
		}
	}

}

Deal with dash in package name

Deal with dash in package name


<?php

class Item_lib
{
	var $CI;

  	function __construct()
	{
		$this->CI =& get_instance();
	}

	function get_item_location()
    {
        if(!$this->CI->session->userdata('item_location'))
        {
             $stock_locations = $this->CI->Stock_locations->get_undeleted_all()->result_array();
             $location_name = $stock_locations[0]['location_id'];
             $this->set_item_location($location_name);
        }
        return $this->CI->session->userdata('item_location');
    }

    function set_item_location($location)
    {
        $this->CI->session->set_userdata('item_location',$location);
    }

    function clear_item_location()
    {
    	$this->CI->session->unset_userdata('item_location');
    }
}

?>

<?php

class Item_lib
{
	var $CI;

  	function __construct()
	{
		$this->CI =& get_instance();
	}

	function get_item_location()
    {
        if(!$this->CI->session->userdata('item_location'))
        {
             $stock_locations = $this->CI->Stock_locations->get_allowed_locations();
			 $key=current(array_keys($stock_locations));
             $location_name = $stock_locations[$key]['location_id'];
             $this->set_item_location($location_name);
        }
        return $this->CI->session->userdata('item_location');
    }

    function set_item_location($location)
    {
        $this->CI->session->set_userdata('item_location',$location);
    }

    function clear_item_location()
    {
    	$this->CI->session->unset_userdata('item_location');
    }
}

?>

Fix default location selected (now uses allowed locations only)


<?php

// http://core.trac.wordpress.org/browser/tags/3.3.2/wp-includes/general-template.php
function selected( $selected, $current = true, $echo = true ) {
	return __checked_selected_helper( $selected, $current, $echo, 'selected' );
}

// http://core.trac.wordpress.org/browser/tags/3.3.2/wp-includes/general-template.php
function __checked_selected_helper( $helper, $current, $echo, $type ) {
	if ( (string) $helper === (string) $current )
		$result = " $type='$type'";
	else
		$result = '';

	if ( $echo )
		echo $result;

	return $result;
}

<?php

function selected($selected, $current) {
    if ($selected === $current) {
        return 'selected';
    }

    return '';
}

Remove GPL code from WordPress 3.3.2

Remove GPL code from WordPress 3.3.2


<?php

/**
 * Created by PhpStorm.
 * User: Conrad
 * Date: 9/11/2015
 * Time: 5:28 PM
 */
class ContentModuleSiteTreeTranslatableExtension extends DataExtension
{
    public function onTranslatableCreate($saveTranslation)
    {
        if ($saveTranslation) {
            //create new modules
            if ($original = $this->owner->getTranslation(Translatable::default_locale())) {
                foreach ($original->ContentModules() as $module) {
                    //create new module
                    $newModule = Object::create(get_class($module));
                    $newModule->Title = $module->Title . ' - ' . Translatable::get_current_locale();
                    $newModule->Locale = Translatable::get_current_locale();
                    $newModule->OriginalID = $original->ID;
                    $newModule->write();
                    $this->owner->ContentModules()->add($newModule);
                }
            }
        }
    }
}

<?php

/**
 * Created by PhpStorm.
 * User: Conrad
 * Date: 9/11/2015
 * Time: 5:28 PM
 */
class ContentModuleSiteTreeTranslatableExtension extends DataExtension
{
    public function onTranslatableCreate($saveTranslation)
    {
        if ($saveTranslation) {
            //create new modules
            $manyManys = array_reverse($page->manyMany());

            if (!empty($manyManys)) {
                foreach ($manyManys as $relationship => $class) {
                    if ($class === 'ContentModule' || ($class instanceof ContentModule)) {
                        if ($original = $this->owner->getTranslation(Translatable::default_locale())) {
                            foreach ($original->$relationship() as $module) {
                                //create new module
                                $newModule = Object::create(get_class($module));
                                $newModule->Title = $module->Title . ' - ' . Translatable::get_current_locale();
                                $newModule->Locale = Translatable::get_current_locale();
                                $newModule->OriginalID = $original->ID;
                                $newModule->write();
                                $this->owner->$relationship()->add($newModule);
                            }
                        }
                    }
                }
        }
    }
}

Handle multiple module relationships when creating a translation


<?php
namespace Phonect\SOAP;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
class SoapStream implements StreamInterface
{
  use StreamDecoratorTrait;
  public function soapSerialize()
  {
  	//fseek($this->getContents(), 0);
  	$this->seek(0);
	$contents = (string) $this->getContents();

	if ($contents === '') {
		return null;
	}

	try {
		$xml = simplexml_load_string($contents);
		$match = $xml->xpath('//return');

		if (empty($match)) {
		  return null;
		}
		$json = json_encode($match[0]);

		if (empty($json)) {
		  return null;
		}
		$return = json_decode($json,true);

		if (empty($return)) {
		  return null;
		}
		if (!empty($return[0])) {
		  $return = $return[0];
		}

		return (object) ['return' => $return];
	} catch (\Exception $e) {
		throw new RuntimeException(
			'Error trying to decode response: ' .
			$e->getMessage(),
			500,
			$e
		);
	}
	return $decodedContents;
  }
}

<?php
namespace Phonect\SOAP;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
class SoapStream implements StreamInterface
{
  use StreamDecoratorTrait;
  public function soapSerialize()
  {
  	//fseek($this->getContents(), 0);
  	$this->seek(0);
	$contents = (string) $this->getContents();

	if ($contents === '') {
		return null;
	}

	try {
		$xml = simplexml_load_string($contents);
		$match = $xml->xpath('//return');
		if (empty($match)) {
		  return null;
		}
		$data = [];
		foreach ($match as $item) {
			$data[] = $item;
		}
		$json = json_encode($data);
		if (empty($json)) {
		  return null;
		}
		$return = json_decode($json,true);
		if (empty($return)) {
		  return null;
		}
		if (count($return) == 1) {
		  $return = $return[0];
		}
		$response = (object) ['return' => $return];
		return $response;
	} catch (\Exception $e) {
		throw new RuntimeException(
			'Error trying to decode response: ' .
			$e->getMessage(),
			500,
			$e
		);
	}
	return $decodedContents;
  }
}

Make sure the handler can handle collections. Pun not intended.


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

if (class_exists('Tideways\Profiler')) {
    \Tideways\Profiler::start(array('api_key' => trim(file_get_contents(__DIR__.'/tideways.key'))));
}

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

if (!isset($env) || $env !== 'dev') {
    // force ssl
    $app->before(function (Request $request) {
        // skip SSL & non-GET/HEAD requests
        if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
            return;
        }

        return new RedirectResponse('https://'.substr($request->getUri(), 7));
    });

    $app->after(function (Request $request, Response $response) {
        if (!$response->headers->has('Strict-Transport-Security')) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31104000');
        }
    });
}

Revert "Add tideways config to getcomposer.org"

This reverts commit 134f749534d8ecabd8c42e1e2cf10df9a7057edf.