<?php

namespace Isolate\Symfony\IsolateBundle\Command;

use Isolate\LazyObjects\Proxy\Adapter\OcramiusProxyManager\Factory\LazyObjectsFactory;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\Symfony\IsolateBundle\LazyObject\DefinitionCollection;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateLazyObjectProxyCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('isolate:lazy-objects:generate:proxies')
            ->setDescription('Generate proxy classes for Isolate lazy objects.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /* @var DefinitionCollection $lazyObjectDefinitions */
        /* @var LazyObjectsFactory $factory */
        /* @var Definition $definition */

        $lazyObjectDefinitions = $this->getContainer()->get('isolate.lazy_objects.definition.collection');
        $factory = $this->getContainer()->get('isolate.lazy_objects.wrapper.proxy.adapter.factory');

        foreach ($lazyObjectDefinitions as $definition) {
            $factory->createProxyClass((string) $definition->getClassName());

            $output->writeln(PHP_EOL . sprintf('<fg=green>Proxy class generated for "%s"</fg=green>', (string) $definition->getClassName()));
        }
    }
}

<?php

namespace Isolate\Symfony\IsolateBundle\Command;

use Isolate\LazyObjects\Proxy\Adapter\OcramiusProxyManager\Factory\LazyObjectsFactory;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\Symfony\IsolateBundle\LazyObject\DefinitionCollection;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

class GenerateLazyObjectProxyCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('isolate:lazy-objects:generate:proxies')
            ->setDescription('Generate proxy classes for Isolate lazy objects.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /* @var DefinitionCollection $lazyObjectDefinitions */
        /* @var LazyObjectsFactory $factory */
        /* @var Definition $definition */
        $lazyObjectDefinitions = $this->getContainer()->get('isolate.lazy_objects.definition.collection');
        $factory = $this->getContainer()->get('isolate.lazy_objects.wrapper.proxy.adapter.factory');
        $proxyDir = $this->getContainer()->getParameter('isolate.lazy_objects.proxy_dir');
        $fs = new Filesystem();
        $fs->remove($proxyDir);
        $fs->mkdir($proxyDir);

        foreach ($lazyObjectDefinitions as $definition) {
            $factory->createProxyClass((string) $definition->getClassName());

            $output->writeln(PHP_EOL . sprintf('<fg=green>Proxy class generated for "%s"</fg=green>', (string) $definition->getClassName()));
        }
    }
}

Clear proxy dir before generating new proxies


<?php

namespace Funstaff\RefLibRis\Tests;

use Funstaff\RefLibRis\RisFieldsMapping;

/**
 * RisFieldsMappingTest
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
class RisFieldsMappingTest extends \PHPUnit_Framework_TestCase
{
    /**
     * testFindField
     */
    public function testFindField()
    {
        $fieldMapping = new RisFieldsMapping($this->getMapping());
        $this->assertEquals('CN', $fieldMapping->findTagByField('isbn'));
        $this->assertNull($fieldMapping->findTagByField('ZZ'));
    }

    private function getMapping()
    {
        return [
            'TY' => ['type'],
            'CN' => ['isbn', 'issn'],
            'LA' => ['language'],
        ];
    }
}

<?php

namespace Funstaff\RefLibRis\Tests;

use Funstaff\RefLibRis\RisFieldsMapping;

/**
 * RisFieldsMappingTest
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
class RisFieldsMappingTest extends \PHPUnit_Framework_TestCase
{
    /**
     * testFindField
     */
    public function testFindField()
    {
        $fieldMapping = new RisFieldsMapping($this->getMapping());
        $this->assertEquals('CN', $fieldMapping->findRisFieldByFieldName('isbn'));
        $this->assertNull($fieldMapping->findRisFieldByFieldName('ZZ'));
    }

    private function getMapping()
    {
        return [
            'TY' => ['type'],
            'CN' => ['isbn', 'issn'],
            'LA' => ['language'],
        ];
    }
}

Modify the test for the new function name on RisFieldsMapping


<?php
?>

<form action="#" role="form" id="finishSettingsForm">

Setup Complete!

        Looks like you're almost done! As a final step, run the following commands from the terminal:

sudo service airtime-playout start

sudo service airtime-liquidsoap start

sudo service airtime-media-monitor start

        Click "Done!" to bring up the Airtime configuration checklist; if your configuration is all green,
        you're ready to get started with your personal Airtime station!

        If you need to re-run the web installer, just remove /etc/airtime/airtime.conf.

        <input type="submit" formtarget="finishSettingsForm" class="btn btn-primary btn-next" value="Done!"/>

</form>

Add preventDefault call to final setup page


<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Factory;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('felixkiss/uniquewith-validator');

        // Registering the validator extension with the validator factory
        $this->app['validator']->resolver(function($translator, $data, $rules, $messages)
        {
            // Set custom validation error messages
            $messages['unique_with'] = $translator->get('uniquewith-validator::validation.unique_with');

            return new ValidatorExtension($translator, $data, $rules, $messages);
        });
    }

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

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array();
    }
}

<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Factory;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('felixkiss/uniquewith-validator');

        // Registering the validator extension with the validator factory
        $this->app['validator']->resolver(function($translator, $data, $rules, $messages)
        {
            // Set custom validation error messages
            $messages['unique_with'] = $translator->get('uniquewith-validator::validation.unique_with');

            return new ValidatorExtension($translator, $data, $rules, $messages);
        });
    }

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

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array();
    }
}

Set ServiceProvider to be eagerly loaded (not deferred)


<?php

namespace Jaybizzle;

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

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

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

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

<?php

namespace Jaybizzle;

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

    /**
     * Month/Season map
     *
     * @var array
     */
    public $monthRange = [
        0 => [12, 1, 2],
        1 => [3, 4, 5],
        2 => [6, 7, 8],
        3 => [9, 10, 11],
    ];

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

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

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

    /**
     * Get months numbers that belong to the season.
     *
     * @param  string $season
     * @return array
     */
    public function monthRange($season)
    {
        if(!in_array($season, $this->seasons)) {
            throw new \Exception($season . ' is not a season.');
        }
        return $this->monthRange[array_search($seasons, $this->seasons)];
    }
}

Return month numbers in the season

Return month numbers in the season


<?php
/**
 *
 *
 * This file is centrally included from `wp-content/mu-plugins/wpcom-theme-compat.php`.
 *
 * @package podium
 */

function podium_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'podium' ),
		'id'            => 'sidebar-1',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
		));
}
add_action( 'widgets_init', 'podium_widgets_init' );

<?php
/**
 *
 *
 * This file is centrally included from `wp-content/mu-plugins/wpcom-theme-compat.php`.
 *
 * @package podium
 */

function podium_register_sidebars() {
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'podium' ),
		'id'            => 'sidebar-1',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
		));
}
add_action( 'widgets_init', 'podium_widgets_init' );

Update register sidebar function name

Update register sidebar function name


<?php

namespace thinkerg\IshtarGate\controllers;

use Yii;
use thinkerg\IshtarGate\models\LoginForm;

/**
 *
 * @author Thinker_g
 *
 * @property $module \thinkerg\IshtarGate\Module;
 *
 */
class GateController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionSignin()
    {
        $model = new LoginForm();
        $model->hashCallable = $this->module->hashCallable;

        if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) {
            if (array_key_exists($model->username, $this->module->credentials)
                && ($model->password == $this->module->credentials[$model->username])) {
                Yii::$app->getSession()->set($this->module->sessKey, $model->username);
                $this->goHome();
            } else {
                $model->addError('password', 'Invalid username or password.');
            }
        }

        return $this->render('signin', ['model' => $model]);

    }

    public function actionSignout()
    {
        Yii::$app->getSession()->remove($this->module->sessKey);
        $this->goHome();
    }
}

<?php

namespace thinkerg\IshtarGate\controllers;

use Yii;
use thinkerg\IshtarGate\models\LoginForm;
use yii\web\HttpException;

/**
 *
 * @author Thinker_g
 *
 * @property $module \thinkerg\IshtarGate\Module;
 *
 */
class GateController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionSignin()
    {
        if (! $this->module->enabled) {
            throw new HttpException(403, 'The module must be ENABLED to access this action.');
        }
        $model = new LoginForm();
        $model->hashCallable = $this->module->hashCallable;

        if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) {
            if (array_key_exists($model->username, $this->module->credentials)
                && ($model->password == $this->module->credentials[$model->username])) {
                Yii::$app->getSession()->set($this->module->sessKey, $model->username);
                $this->goHome();
            } else {
                $model->addError('password', 'Invalid username or password.');
            }
        }

        return $this->render('signin', ['model' => $model]);

    }

    public function actionSignout()
    {
        Yii::$app->getSession()->remove($this->module->sessKey);
        $this->goHome();
    }
}

Throw exception when access login action and module is not enabled.


<?php

namespace App\Http\Controllers\Opwifi\System;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;

use App\Models\OwSystem;

class ConfigController extends Controller {

	protected $viewData = array(
	);

    public function __construct()
    {
    }

    private $config_items = ['site_url', 'fn_sta_status'];

    private function loadConfigs() {
    	$this->viewData['configs'] = OwSystem::getValue($this->config_items);
    }

	public function getIndex() {
		$this->loadConfigs();
		return view("opwifi.system.config", $this->viewData);
	}

	public function postIndex(Request $request) {
        OwSystem::saveValues($request->only($this->config_items));
        return $this->getIndex();
	}

}

<?php

namespace App\Http\Controllers\Opwifi\System;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;

use Auth;

use App\Models\OwSystem;

class ConfigController extends Controller {

	protected $viewData = array(
	);

    public function __construct()
    {
    }

    private $config_items = ['site_url', 'fn_sta_status'];

    private function loadConfigs() {
    	$this->viewData['configs'] = OwSystem::getValue($this->config_items);
    }

	public function getIndex() {
		$this->loadConfigs();
		return view("opwifi.system.config", $this->viewData);
	}

	public function postIndex(Request $request) {
        if (Auth::User()['right'] == 'admin')
            OwSystem::saveValues($request->only($this->config_items));
        return $this->getIndex();
	}

}

Fix admin level in system config.

Fix admin level in system config.


<?php

class Product
{
    private $_name;
    private $_price;
    private $_url;

    public function __construct($data)
    {
        $this->_parseData($data);
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getPrice()
    {
        return $this->_price;
    }

    public function getUrl()
    {
        return $this->_url;
    }

    private function _parseData($data)
    {
        if (isset($data['product'])) {
            if (isset($data['product']['name'])) {
                $this->_name = $data['product']['name'];
            }
            if (isset($data['product']['price'])) {
                $this->_price =  $data['product']['price'];
            }
            if (isset($data['product']['url'])) {
                $this->_url = $data['product']['url'];
            }
        }
    }
}

<?php

class Product
{
    private $_name;
    private $_price;
    private $_url;

    public function __construct($data)
    {
        $this->_parseData($data);
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getPrice()
    {
        return $this->_price;
    }

    public function getUrl()
    {
        return $this->_url;
    }

    private function _parseData($data)
    {
        if (isset($data['product'])) {
            if (isset($data['product']['name'])) {
                $this->_name = $data['product']['name'];
            }
            if (isset($data['product']['formattedPrice'])) {
                $this->_price =  $data['product']['formattedPrice'];
            }
            if (isset($data['product']['url'])) {
                $this->_url = $data['product']['url'];
            }
        }
    }
}

Use formatted price instead of price

Use formatted price instead of price


<?php

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

namespace Sylius\Bundle\MoneyBundle\Converter;

use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface;

class CurrencyConverter implements CurrencyConverterInterface
{
    protected $exchangeRateRepository;
    private $cache;

    public function __construct(RepositoryInterface $exchangeRateRepository)
    {
        $this->exchangeRateRepository = $exchangeRateRepository;
    }

    public function convert($value, $currency)
    {
        $exchangeRate = $this->getExchangeRate($currency);

        if (null === $exchangeRate) {
            return $value;
        }

        return $value / $exchangeRate->getRate();
    }

    private function getExchangeRate($currency)
    {
        if (isset($this->cache[$currency])) {
            return $this->cache[$currency];
        }

        return $this->cache[$currency] = $this->exchangeRateRepository->findOneBy(array('currency' => $currency));
    }
}

<?php

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

namespace Sylius\Bundle\MoneyBundle\Converter;

use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface;

class CurrencyConverter implements CurrencyConverterInterface
{
    protected $exchangeRateRepository;
    private $cache;

    public function __construct(RepositoryInterface $exchangeRateRepository)
    {
        $this->exchangeRateRepository = $exchangeRateRepository;
    }

    public function convert($value, $currency)
    {
        $exchangeRate = $this->getExchangeRate($currency);

        if (null === $exchangeRate) {
            return $value;
        }

        return $value * $exchangeRate->getRate();
    }

    private function getExchangeRate($currency)
    {
        if (isset($this->cache[$currency])) {
            return $this->cache[$currency];
        }

        return $this->cache[$currency] = $this->exchangeRateRepository->findOneBy(array('currency' => $currency));
    }
}

Fix currency converter. Use multiply.

Fix currency converter. Use multiply.


<?php
// @codeCoverageIgnoreStart
ob_start();
require './autoload.inc';
require './block-exit.inc';
require './stubs.inc';

$_SERVER['SERVER_NAME'] = 'example.com';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['SERVER_PORT'] = 80;
// @codeCoverageIgnoreEnd

<?php
// @codeCoverageIgnoreStart
ob_start();
require './autoload.inc';
require './block-exit.inc';
require './stubs.inc';

$_SERVER['SERVER_NAME'] = 'example.com';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['SERVER_PORT'] = 80;

date_default_timezone_set('America/Chicago');
// @codeCoverageIgnoreEnd

Set default timezone before tests

Set default timezone before tests


<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfig;
use CdliTwoStageSignupTest\Framework\TestCase;
use CdliTwoStageSignupTest\Framework\TestCaseOptions;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfig(@$configuration['service_manager'] ?: array()));
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->get('ModuleManager')->loadModules();

TestCase::setServiceLocator($serviceManager);

$config = $serviceManager->get('Configuration');
TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));

<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfig;
use CdliTwoStageSignupTest\Framework\TestCase;
use CdliTwoStageSignupTest\Framework\TestCaseOptions;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfig(@$configuration['service_manager'] ?: array()));
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->setFactory('ServiceListener', 'Zend\Mvc\Service\ServiceListenerFactory');
$serviceManager->get('ModuleManager')->loadModules();

TestCase::setServiceLocator($serviceManager);

$config = $serviceManager->get('Configuration');
TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));

Add ServiceListener factory to tests bootstrap


<?php
namespace Czim\CmsModels\Repositories;

use Czim\CmsModels\Contracts\Repositories\ModelRepositoryInterface;
use Czim\Repository\ExtendedRepository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Collection;

class ModelRepository extends ExtendedRepository implements ModelRepositoryInterface
{

    /**
     * @var string
     */
    protected $modelClass;

    /**
     * @param string $modelClass
     */
    public function __construct($modelClass = null)
    {
        $this->modelClass = $modelClass;

        parent::__construct(app(Application::class), new Collection);
    }

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

}

<?php
namespace Czim\CmsModels\Repositories;

use Czim\CmsModels\Contracts\Repositories\ModelRepositoryInterface;
use Czim\Repository\ExtendedRepository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

class ModelRepository extends ExtendedRepository implements ModelRepositoryInterface
{

    /**
     * @var string
     */
    protected $modelClass;

    /**
     * @param string $modelClass
     */
    public function __construct($modelClass = null)
    {
        $this->modelClass = $modelClass;

        parent::__construct(app(Application::class), new Collection);
    }

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

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        $query = parent::query();

        if ($query instanceof Model) {
            $query = $query->query();
        }

        return $query;
    }

}

Fix for repository query() response returning model class


<?php

namespace LaravelTrailingSlash;

use Illuminate\Routing\RoutingServiceProvider as BaseRoutingServiceProvider;
use LaravelTrailingSlash\UrlGenerator;

class RoutingServiceProvider extends BaseRoutingServiceProvider
{
    /**
     * Register the URL generator service.
     *
     * @return void
     */
    protected function register()
    {
		$this->app['url'] = $this->app->share(function($app) {
			$routes = $app['router']->getRoutes();

			// The URL generator needs the route collection that exists on the router.
            // Keep in mind this is an object, so we're passing by references here
            // and all the registered routes will be available to the generator.
			$app->instance('routes', $routes);

			$url = new UrlGenerator(
				$routes, $app->rebinding('request', $this->requestRebinder())
			);

			$url->setSessionResolver(function ($app) {
				return $app['session'];
			});

			// If the route collection is "rebound", for example, when the routes stay
            // cached for the application, we will need to rebind the routes on the
            // URL generator instance so it has the latest version of the routes.
			$app->rebinding('routes', function ($app, $routes) {
                $app['url']->setRoutes($routes);
            });

			return $url;
		});
    }
}

<?php

namespace LaravelTrailingSlash;

use Illuminate\Routing\RoutingServiceProvider as BaseRoutingServiceProvider;
use LaravelTrailingSlash\UrlGenerator;

class RoutingServiceProvider extends BaseRoutingServiceProvider
{
    /**
     * Register the URL generator service.
     *
     * @return void
     */
    public function register()
    {
		$this->app['url'] = $this->app->share(function($app) {
			$routes = $app['router']->getRoutes();

			// The URL generator needs the route collection that exists on the router.
            // Keep in mind this is an object, so we're passing by references here
            // and all the registered routes will be available to the generator.
			$app->instance('routes', $routes);

			$url = new UrlGenerator(
				$routes, $app->rebinding('request', $this->requestRebinder())
			);

			$url->setSessionResolver(function ($app) {
				return $app['session'];
			});

			// If the route collection is "rebound", for example, when the routes stay
            // cached for the application, we will need to rebind the routes on the
            // URL generator instance so it has the latest version of the routes.
			$app->rebinding('routes', function ($app, $routes) {
                $app['url']->setRoutes($routes);
            });

			return $url;
		});
    }
}

Fix register() method visibility in service provider


<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('class.TicketAdminPage.php');
require_once('class.FlipsideTicketDB.php');
$page = new TicketAdminPage('Burning Flipside - Tickets');

$page->add_js(JS_DATATABLE);
$page->add_css(CSS_DATATABLE);
$page->add_js_from_src('js/sold_tickets.js');

$page->body .= '

Sold Tickets

                        Short Code
                        First Name
                        Last Name
                        Type

';

$page->print_page();
// vim: set tabstop=4 shiftwidth=4 expandtab:
?>

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('class.TicketAdminPage.php');
$page = new TicketAdminPage('Burning Flipside - Tickets');

$page->add_js(JS_DATATABLE, false);
$page->add_css(CSS_DATATABLE);
$page->add_js_from_src('js/sold_tickets.js');

$page->body .= '

Sold Tickets

                        Short Code
                        First Name
                        Last Name
                        Type

';

$page->print_page();
// vim: set tabstop=4 shiftwidth=4 expandtab:
?>

Remove reference to deprecated TicketDB class


<?php

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class Header
{
    protected $sections = [
        [
            'routeKey' => 'developers',
            'title' => 'Entwickler',
        ],

        [
            'routeKey' => 'specification',
            'title'    => 'Spezifikation',
        ],

        [
            'routeKey' => 'api.v1.system.show',
            'params'   => [1],
            'title'    => 'Demo',
        ],

        [
            'title' => 'Kontakt',
            'url'   => 'https://oparl.org/kontakt/',
        ],
    ];

    public function compose(View $view)
    {
        return $view->with('sections', $this->getSections());
    }

    protected function getSections()
    {
        $sections = $this->sections;
        $currentRouteName = \Route::currentRouteName();

        foreach ($sections as $key => $section) {
            if (isset($section['routeKey']) && starts_with($currentRouteName, $section['routeKey'])) {
                $sections[$key]['current'] = true;
                break;
            }
        }

        if (\Auth::check()) {
            array_unshift($sections, [
                'routeKey' => 'admin.dashboard',
                'title'    => '',
            ]);
        }

        return $sections;
    }
}

<?php

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class Header
{
    protected $sections = [
        [
            'routeKey' => 'developers',
            'title' => 'Entwickler',
        ],

        [
            'routeKey' => 'specification',
            'title'    => 'Spezifikation',
        ],

        [
            'routeKey' => 'api.v1.system.show',
            'params'   => [1, 'format' => 'html'],
            'title'    => 'Demo',
        ],

        [
            'title' => 'Kontakt',
            'url'   => 'https://oparl.org/kontakt/',
        ],
    ];

    public function compose(View $view)
    {
        return $view->with('sections', $this->getSections());
    }

    protected function getSections()
    {
        $sections = $this->sections;
        $currentRouteName = \Route::currentRouteName();

        foreach ($sections as $key => $section) {
            if (isset($section['routeKey']) && starts_with($currentRouteName, $section['routeKey'])) {
                $sections[$key]['current'] = true;
                break;
            }
        }

        if (\Auth::check()) {
            array_unshift($sections, [
                'routeKey' => 'admin.dashboard',
                'title'    => '',
            ]);
        }

        return $sections;
    }
}

Fix api demo link to link to html version


<?php

    // Be sure your webserver is configured to never display the contents of this file under any circumstances.
    // The secret_key value below should be protected and never shared with anyone.

    $amazonpay_config = array(
        'merchant_id'   => '', // Merchant/SellerID
        'access_key'    => '', // MWS Access Key
        'secret_key'    => '', // MWS Secret Key
        'client_id'     => '', // Login With Amazon Client ID
        'region'        => 'us',  // us, de, uk, jp
        'currency_code' => 'USD', // USD, EUR, GBP, JPY
        'sandbox'       => true); // Use sandbox test mode

function getWidgetsJsURL($config)
{
    if ($config['sandbox'])
        $sandbox = "sandbox/";
    else
        $sandbox = "";

    switch (strtolower($config['region'])) {
        case "us":
            return "https://static-na.payments-amazon.com/OffAmazonPayments/us/" . $sandbox . "js/Widgets.js";
            break;
        case "uk":
            return "https://static-eu.payments-amazon.com/OffAmazonPayments/uk/" . $sandbox . "lpa/js/Widgets.js";
            break;
        case "jp":
            return "https://static-fe.payments-amazon.com/OffAmazonPayments/jp/" . $sandbox . "lpa/js/Widgets.js";
            break;
        default:
            return "https://static-eu.payments-amazon.com/OffAmazonPayments/de/" . $sandbox . "lpa/js/Widgets.js";
            break;
    }
}

?>

<?php

    // Be sure your webserver is configured to never display the contents of this file under any circumstances.
    // The secret_key value below should be protected and never shared with anyone.

    $amazonpay_config = array(
        'merchant_id'   => '', // Merchant/SellerID
        'access_key'    => '', // MWS Access Key
        'secret_key'    => '', // MWS Secret Key
        'client_id'     => '', // Login With Amazon Client ID
        'region'        => 'us',  // us, de, uk, jp
        'currency_code' => 'USD', // USD, EUR, GBP, JPY
        'sandbox'       => true); // Use sandbox test mode

function getWidgetsJsURL($config)
{
    if ($config['sandbox'])
        $sandbox = "sandbox/";
    else
        $sandbox = "";

    switch (strtolower($config['region'])) {
        case "us":
            return "https://static-na.payments-amazon.com/OffAmazonPayments/us/" . $sandbox . "js/Widgets.js";
            break;
        case "uk":
            return "https://static-eu.payments-amazon.com/OffAmazonPayments/gbp/" . $sandbox . "lpa/js/Widgets.js";
            break;
        case "jp":
            return "https://static-fe.payments-amazon.com/OffAmazonPayments/jp/" . $sandbox . "lpa/js/Widgets.js";
            break;
        default:
            return "https://static-eu.payments-amazon.com/OffAmazonPayments/eur/" . $sandbox . "lpa/js/Widgets.js";
            break;
    }
}

?>

Correct UK and EU Widgets.js URLs

Correct UK and EU Widgets.js URLs


<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
collctionInterval();

while (true){
	collectionInfoStart();
	sleep($config['updateinterval']);
}
?>

<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
debug_collctionInterval($config['debug'], $config['updateinterval']);

while (true){
	debug_collectionInfoStart($config['debug']);
	sleep($config['updateinterval']);
}
?>

Use new function names. Pass required data rather than debug file reading values directly.


<?php

use app\core\router\Router;
use josegonzalez\Dotenv\Loader;
use app\core\logging\Logger;

define('APP_ROOT_DIR', realpath('..'));
define('APP_LIB_DIR', APP_ROOT_DIR . '/app/lib');

if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != "guest" || $_SERVER['PHP_AUTH_PW'] != "please") {
    header('WWW-Authenticate: Basic realm="Site is under construction"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Sorry, you haven't access to this resource.";
    exit;
}

$used_before = memory_get_usage();

require_once "../app/loader.php";
require_once "../vendor/autoload.php";

if (file_exists(APP_ROOT_DIR . '/.env')) {
    $loader = new Loader(APP_ROOT_DIR . '/.env');
    $loader->parse();
    $loader->toEnv(true);
}

$router = Router::getInstance();

$router->run();

$used_after = memory_get_usage();

Logger::printf("Memory used: %d", $used_after - $used_before);

<?php

use app\core\router\Router;
use josegonzalez\Dotenv\Loader;
use app\core\logging\Logger;

define('APP_ROOT_DIR', realpath('..'));
define('APP_LIB_DIR', APP_ROOT_DIR . '/app/lib');

if (!file_exists(APP_ROOT_DIR . '/vendor/autoload.php')) {
    http_response_code(500);
    echo '<h1>"vendor" directory not found!</h1>';
    exit();
}

if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != "guest" || $_SERVER['PHP_AUTH_PW'] != "please") {
    header('WWW-Authenticate: Basic realm="Site is under construction"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Sorry, you haven't access to this resource.";
    exit;
}

$used_before = memory_get_usage();

require_once "../app/loader.php";
require_once "../vendor/autoload.php";

if (file_exists(APP_ROOT_DIR . '/.env')) {
    $loader = new Loader(APP_ROOT_DIR . '/.env');
    $loader->parse();
    $loader->toEnv(true);
}

$router = Router::getInstance();

$router->run();

$used_after = memory_get_usage();

Logger::printf("Memory used: %d", $used_after - $used_before);

Fix startup error message when vendor directory not found


<?php
/**
 * A single navigtion menu
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package foundation
 * @subpackage navigation
 */
class Navigation_Menu {
  /**
   * The title for this menu
   * @var string
   */
  public $title;

  /**
   * holds the links
   * @var array
   */
  private $_links = array();

  /**
   * Create a new link object
   * @param array $attributes
   * @return Navigation_Link
   */
  public function newLink($attributes = array()){
    $link = new Navigation_Link;
    foreach($attributes as $key=>$value){
      $link->$key = $value;
    }
    $this->_links[] = $link;
    return $link;
  }

  /**
   * Get the links
   * return array
   */
  public function getLinks(){
    return $this->_links;
  }

  /**
   * Does the menu have links
   * @return bool true if there are any links false if not
   */
  public function hasLink(){
    return (bool)count($this->_links);
  }
}
?>

<?php
/**
 * A single navigtion menu
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package foundation
 * @subpackage navigation
 */
class Navigation_Menu {
  /**
   * The title for this menu
   * @var string
   */
  public $title;

  /**
   * holds the links
   * @var array
   */
  private $_links = array();

  /**
   * Create a new link object
   * @param array $attributes
   * @return Navigation_Link
   */
  public function newLink($attributes = array()){
    $link = new Navigation_Link;
    foreach($attributes as $key=>$value){
      $link->$key = $value;
    }
    $this->_links[] = $link;
    return $link;
  }

  /**
   * Get the links
   * return array
   */
  public function getLinks(){
    return $this->_links;
  }

  /**
   * Sort the links by title
   */
  public function sortLinks(){
    usort($this->_links, function($a, $b){
      return strcmp($a->text, $b->text);
    });
  }

  /**
   * Does the menu have links
   * @return bool true if there are any links false if not
   */
  public function hasLink(){
    return (bool)count($this->_links);
  }
}
?>

Add sorting by link title to NavigationMenu.


<?php

	session_start();

	if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == true)
	{
		echo "you're an admin";
	}
	else{

		header("Location: static_homepage.php", true, 301);
		die();
	}
?>

<!DOCTYPE html>

		<link rel="stylesheet" href="css/normalize.css">
		<link rel="stylesheet" href="css/skeleton.css">
		<link rel="stylesheet" href="css/custom.css">
		<link rel="stylesheet" href="css/font.css">
		<title>Welcome to the admin page</title>

		  <?php

			  include 'nav_bar.php';

  		?>

 Admin Page

Welcome to the Administrator Page!

			<form action="admin_logout.php">
	  		<input type="submit" value="Logout" />
			</form>

<?php

	include 'nav_bar.php';

?>

<?php

	session_start();

	if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == true)
	{
		echo "you're an admin";

	}
	else{

		header("Location: static_homepage.php", true, 301);
		die();
	}
?>

<!DOCTYPE html>

		<title>Welcome to the admin page</title>

Admin page

	<form align="center"action="admin_logout.php">
	  		<input type="submit" value="Logout" />
	  </form>

Create the nav bar div before anything else


<?php
include_once('phpviddler.php');

class Php5viddler extends Phpviddler {
  function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) {
    $result = parent::sendRequest($method, $args, $postmethod);

    if($tryagain && is_null($result)) {
      $result = parent::sendRequest($method, $args, $postmethod, false);
    } elseif(is_null($result)) {
      throw new ViddlerException("No response", $method, 8888, 'n/a');
    }

    if(is_array($result) && $result['error']) {
      throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']);
    }

		return $result;
  }

}

class ViddlerException extends Exception {
  var $details;
  var $method;

  public function __construct($message, $method, $code=0, $details='') {
    $this->details = $details;
    $this->method = $method;
    parent::__construct($message, $code);
  }

  public function getDetails() {
    return $this->details;
  }

  public function __toString() {
    return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n";
  }
}

?>

<?php
include_once('phpviddler.php');

class Php5viddler extends Phpviddler {
  function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) {
    $result = parent::sendRequest($method, $args, $postmethod);

    if($tryagain && is_null($result)) {
      $result = parent::sendRequest($method, $args, $postmethod, false);
    } elseif(is_null($result)) {
      throw new ViddlerException("No response", $method, 8888, 'n/a');
    }

    if(is_array($result) && isset($result['error'])) {
      throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']);
    }

		return $result;
  }

}

class ViddlerException extends Exception {
  var $details;
  var $method;

  public function __construct($message, $method, $code=0, $details='') {
    $this->details = $details;
    $this->method = $method;
    parent::__construct($message, $code);
  }

  public function getDetails() {
    return $this->details;
  }

  public function __toString() {
    return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n";
  }
}

?>

Check if a key exists in an array, so it doesn't raise an error


@extends('layouts.master')

@section('title')
    {{ $collection->name }}
    @parent
@stop

@section('main-navigation')

@stop

@section('content')

            Výber diel z Webu  umenia.

            Inšpirované výstavou Sedmičky v SNG.

    <x-user-collections.share-form
        :collection="$collection"
        :items="$items"
        disabled
    />

            Vytvor a zdieľaj vlastný výber výtvarných diel na Webe umenia.

            Tematické výbery kurátoriek a kurátorov Slovenskej národnej galérie nájdeš na výstave Sedmičky.

@endsection

Fix links in public view

Fix links in public view


<?php
class SparkTest extends PHPUnit_Framework_TestCase
{
   private $_spark;

   protected function setUp() {
      $this->_spark = new Spark\Core\Spark();
   }

   public function testLoadingTags() {
      $this->assertEquals(1, count($this->_spark->getTags()));

		$this->_spark->addTag("Test", function($html, $inner) { return "Test"; });

      $this->assertEquals(2, count($this->_spark->getTags()));

		$this->_spark->addTag("Test", function($html, $inner) { return "Test 2"; });

      $this->assertEquals(2, count($this->_spark->getTags()));
   }
}

<?php
class SparkTest extends PHPUnit_Framework_TestCase
{
   private $_spark;

   protected function setUp() {
      $this->_spark = new Spark\Core\Spark();
   }

   public function testLoadingTags() {
      $this->assertEquals(1, count($this->_spark->getTags()));

		$this->_spark->addTag("Test", function($html, $inner) { return "Test"; });

      $this->assertEquals(2, count($this->_spark->getTags()));

		$this->_spark->addTag("Test", function($html, $inner) { return "Test 2"; });

      $this->assertEquals(2, count($this->_spark->getTags()));
   }

   public function testSimpleRender() {

		$this->_spark->addTag("Test", function($html, $inner) { return "Example"; });

   	$html = '<title>Test</title><SparkTest></SparkTest>';
   	$expected_html = '<title>Test</title>Example';

      $this->assertEquals($expected_html, $this->_spark->render($html));
   }
}

Add test for a basic render

Add test for a basic render


<?php

namespace App\Bootstrap\Test;

use App\Bootstrap\DispatcherBootstrap;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;

class DispatcherBootstrapTest extends TestCase
{
    private $env;

    public function __construct()
    {
        $this->env = [
            'site' => [
                'url' => '/'
            ],
            'router' => [
                'namespace' => '',
                '/' => function()  {
                    echo 'index';
                }
            ],
            'viewEngine' => [],
            'viewResolver' => [
                'App\ViewResolver\DummyResolver'
            ],
            'viewPrefix' => [
                'applyView' => []
            ]
        ];
    }

    public function testDispatch()
    {
        $this->env['dispatcher'] = [
            'request' => new ServerRequest([], [], '/', 'GET')
        ];

        $bootstrap = new DispatcherBootstrap();

        $this->expectOutputString('index');
        $bootstrap->boot($this->env);
    }
}

<?php

namespace App\Bootstrap\Test;

use App\Bootstrap\DispatcherBootstrap;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;

class DispatcherBootstrapTest extends TestCase
{
    private $env;

    public function __construct()
    {
        $this->env = [
            'site' => [
                'url' => '/'
            ],
            'router' => [
                'namespace' => '',
                '/' => function()  {
                    echo 'index';
                },
                '/test' => function() {
                    echo 'test';
                }
            ],
            'viewEngine' => [],
            'viewResolver' => [
                'App\ViewResolver\DummyResolver'
            ],
            'viewPrefix' => [
                'applyView' => []
            ]
        ];
    }

    public function testDispatch1()
    {
        $this->env['dispatcher'] = [
            'request' => new ServerRequest([], [], '/', 'GET')
        ];

        $bootstrap = new DispatcherBootstrap();

        $this->expectOutputString('index');
        $bootstrap->boot($this->env);
    }

    public function testDispatch2()
    {
        $this->env['dispatcher'] = [
            'request' => new ServerRequest([], [], '/test', 'GET')
        ];

        $bootstrap = new DispatcherBootstrap();

        $this->expectOutputString('test');
        $bootstrap->boot($this->env);
    }
}

Add a test case of DispatcherBootstrap with other request


<?php

namespace Tests\Unit\Pages\Help;

use Tests\TestCase;
use Tests\CreatesUser;
use Tests\InteractsWithDatabase;

class HelpIndexPageTest extends TestCase
{
    use InteractsWithDatabase, CreatesUser;

    /** @test */
    public function it_can_refresh_the_user_page()
    {
        Auth::guard('canvas')->login($this->user);
        $this->actingAs($this->user)
            ->visit(route('canvas.admin.help'))
            ->click('Refresh Help');
        $this->assertSessionMissing('errors');
        $this->seePageIs(route('canvas.admin.help'));
    }
}

<?php

namespace Tests\Unit\Pages\Help;

use Tests\TestCase;
use Tests\CreatesUser;
use Illuminate\Foundation\Testing\RefreshDatabase;

class HelpIndexPageTest extends TestCase
{
    use RefreshDatabase, CreatesUser;

    /** @test */
    public function it_can_refresh_the_user_page()
    {
        Auth::guard('canvas')->login($this->user);
        $this->actingAs($this->user)
            ->visit(route('canvas.admin.help'))
            ->click('Refresh Help');
        $this->assertSessionMissing('errors');
        $this->seePageIs(route('canvas.admin.help'));
    }
}

Refresh the database on tests

Refresh the database on tests


<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Validates and saves the data from the databases form
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class DatabaseHandler
{
    public function process(Form $form, Request $request)
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            return $this->processValidForm($form, $request);
        }

        return false;
    }

    public function processValidForm(Form $form, $request)
    {
        var_dump('ok', $form->getData());exit;
        /*$session = $request->getSession();
        $data = $form->getData();

        $session->set('modules', $data['modules']);
        $session->set('example_data', $data['example_data']);
        $session->set('example_data', $data['different_debug_email']);
        $session->set('debug_email', $data['debug_email']);*/

        return true;
    }
}

<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Validates and saves the data from the databases form
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class DatabaseHandler
{
    public function process(Form $form, Request $request)
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            return $this->processValidForm($form, $request);
        }

        return false;
    }

    public function processValidForm(Form $form, $request)
    {
        $session = $request->getSession();
        $data = $form->getData();

        $session->set('db_hostname', $data['hostname']);
        $session->set('db_username', $data['username']);
        $session->set('db_database', $data['database']);
        $session->set('db_port', $data['port']);
        $session->set('db_password', $data['password']);

        return true;
    }
}

Save the settings from the database step.


<?php

namespace j0k3r\FeedBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validate a XML feed.
 * Wait 3s before timeout
 */
class ContainsRssValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://validator.w3.org/feed/check.cgi?url='.$value);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'f43.me');
        // wait 3s before time out
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $content = curl_exec($ch);
        curl_close($ch);

        if (0 === preg_match('/This is a valid/', $content)) {
            $this->context->addViolation($constraint->message, array('%string%' => $value));
        }
    }
}

<?php

namespace j0k3r\FeedBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validate a XML feed.
 * Wait 3s before timeout
 */
class ContainsRssValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://validator.w3.org/feed/check.cgi?url='.$value);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'f43.me');
        // wait 3s before time out
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $content = curl_exec($ch);
        curl_close($ch);

        // if content is false, it means the request timeout, let's try with an alternative
        if (false === $content) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'http://feedvalidator.org/check.cgi?url='.$value);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT, 'f43.me');
            // wait 3s before time out
            curl_setopt($ch, CURLOPT_TIMEOUT, 3);
            $content = curl_exec($ch);
            curl_close($ch);
        }

        // if content is still false, we won't invalidate the feed, it means both alternative to check are unavailable
        if (false !== $content && 0 === preg_match('/This is a valid/', $content)) {
            $this->context->addViolation($constraint->message, array('%string%' => $value));
        }
    }
}

Add one alternative to feed validator

Add one alternative to feed validator

This evening, it seems that validator.w3.org is down. Using feedvalidator.org, it adds one alternative.


<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;
}

<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;
}

Add case for `null|...` type

TASK: Add case for `null|...` type


<?php

namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

abstract class Listener
{
    //
}

<?php

namespace Begin\Listeners;

use Begin\Events\PodcastWasPurchased;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class EmailPurchaseConfirmation
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  PodcastWasPurchased  $event
     * @return void
     */
    public function handle(PodcastWasPurchased $event)
    {
        // Access the podcast using $event->podcast...
    }
}

Add the sample class for the base event listener


<?php

namespace SoapBox\SignedRequests;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Publishes our ability to add a configuration file during boot.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishConfigurations();
    }

    /**
     * Adds our configuration file to the publishes array.
     *
     * @return void
     */
    protected function publishConfigurations()
    {
        $this->publishes([
            __DIR__.'../resources/config/signed-requests.php' => config_path('signed-requests.php'),
        ]);
    }
}

<?php

namespace SoapBox\SignedRequests;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Publishes our ability to add a configuration file during boot.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishConfigurations();
    }

    /**
     * Adds our configuration file to the publishes array.
     *
     * @return void
     */
    protected function publishConfigurations()
    {
        $this->publishes([
            __DIR__.'/../resources/config/signed-requests.php' => config_path('signed-requests.php'),
        ]);
    }
}

Fix path for publishes array

Fix path for publishes array


<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

use Doctrine\Common\Annotations\AnnotationRegistry;

include '../src/Go/Core/AspectKernel.php';
include 'DemoAspectKernel.php';

// Initialize demo aspect container
DemoAspectKernel::getInstance()->init(array(
    // Configuration for autoload namespaces
    'autoload' => array(
        'Go'               => realpath(__DIR__ . '/../src'),
        'TokenReflection'  => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'),
        'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/')
    ),
    // Default application directory
    'appDir' => __DIR__ . '/../demos',
    // Cache directory for Go! generated classes
    'cacheDir' => __DIR__ . '/cache',
    // Include paths for aspect weaving
    'includePaths' => array(),
    'debug' => true
));

AnnotationRegistry::registerFile('./Annotation/Cacheable.php');

$class = new Example('test');
$class->publicHello();
for ($i=10; $i--; ) {
    $class->cacheMe(1);
}

<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

use Doctrine\Common\Annotations\AnnotationRegistry;

include '../src/Go/Core/AspectKernel.php';
include 'DemoAspectKernel.php';

// Initialize demo aspect container
DemoAspectKernel::getInstance()->init(array(
    // Configuration for autoload namespaces
    'autoload' => array(
        'Go'               => realpath(__DIR__ . '/../src'),
        'TokenReflection'  => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'),
        'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/')
    ),
    // Default application directory
    'appDir' => __DIR__ . '/../demos',
    // Cache directory for Go! generated classes
    'cacheDir' => __DIR__ . '/cache',
    // Include paths for aspect weaving
    'includePaths' => array(),
    'debug' => true
));

AnnotationRegistry::registerFile('./Annotation/Cacheable.php');

$class = new Example('test');
if ($class instanceof Serializable) {
    echo "Yeah, Example is serializable!", "
", PHP_EOL;
    $ref = new ReflectionClass('Example');
    var_dump($ref->getTraitNames(), $ref->getInterfaceNames());
} else {
    echo "Ooops, Example isn't serializable!", "
", PHP_EOL;
}
$class->publicHello();
for ($i=10; $i--; ) {
    $class->cacheMe(1);
}

Update demo to show interfaces and traits for Example class


<?php
class Controller{

	protected $tpl;
	protected $path;
	protected $content = 'index.html';

	function __construct($path) {
		$this->path = $path;
    	$this->tpl = new Tpl(LAYOUT_PATH);
    }

	function index(){
	}

	function run(){
		$controller = $this->path[0];
		$config = require(APP_PATH.'config.php');
		foreach($config as $key=>$val){
			$this->tpl->assign_var($key,$val);
		}
		$contentPath = TPL_PATH.$controller.DS.$this->content;
		if(file_exists($contentPath)){
			$this->tpl->assign_var('content',$contentPath);
		} else {
			$this->tpl->assign_var('content',ERROR_PATH);
		}

		$this->tpl->display();
	}
}

<?php
class Controller{

	protected $tpl;
	protected $path;
	protected $content = 'index.html';

	function __construct($path) {
		$this->path = $path;
    	$this->tpl = new Tpl(LAYOUT_PATH);
    }

	function index(){
	}

	function run(){
		$controller = $this->path[0];
		if($controller == "code"){ //for the test code
			include(CODE_PATH.$this->path[1]);
		} else{
			$config = require(APP_PATH.'config.php');
			foreach($config as $key=>$val){
				$this->tpl->assign_var($key,$val);
			}
			$contentPath = TPL_PATH.$controller.DS.$this->content;
			if(file_exists($contentPath)){
				$this->tpl->assign_var('content',$contentPath);
			} else {
				$this->tpl->assign_var('content',ERROR_PATH);
			}

			$this->tpl->display();
		}
	}
}

Add function for run code source

Add function for run code source


<?php

namespace Northstar\Console\Commands;

use Northstar\Models\User;
use MongoDB\BSON\UTCDateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class RemoveOldBirthdates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'northstar:olds';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove birthdates that are way too old.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Get any users where 'birthdate' is before 1900... a.k.a way too old:
        $query = User::whereRaw([
            'birthdate' => [
                '$lt' => new UTCDateTime(strtotime('1900-01-01 00:00:00')),
            ],
        ]);

        $progressBar = $this->output->createProgressBar($query->count());
        $query->chunkById(200, function (Collection $users) use ($progressBar) {
            foreach ($users as $user) {
                $birthdate = $user->birthdate;
                $user->birthdate = null;
                $user->save();

                $progressBar->advance();

                info('Removed invalid birthdate.', [
                    'id' => $user->id,
                    'birthdate' => $birthdate,
                ]);
            }
        });

        $progressBar->finish();
    }
}

<?php

namespace Northstar\Console\Commands;

use Northstar\Models\User;
use MongoDB\BSON\UTCDateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class RemoveOldBirthdates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'northstar:olds';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove birthdates that are way too old.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Get any users where 'birthdate' is before 1900. Note that strtotime gives
        // us a traditional UNIX timestamp (in seconds), but UTCDateTime wants a
        // JavaScript-style timestamp (in milliseconds).
        $query = User::whereRaw([
            'birthdate' => [
                '$lt' => new UTCDateTime(strtotime('1900-01-01 00:00:00') * 1000),
            ],
        ]);

        $progressBar = $this->output->createProgressBar($query->count());
        $query->chunkById(200, function (Collection $users) use ($progressBar) {
            foreach ($users as $user) {
                $birthdate = $user->birthdate;
                $user->birthdate = null;
                $user->save();

                $progressBar->advance();

                info('Removed invalid birthdate.', [
                    'id' => $user->id,
                    'birthdate' => $birthdate,
                ]);
            }
        });

        $progressBar->finish();
    }
}

Fix issue with UTCDateTime constructor.

Fix issue with UTCDateTime constructor.


<?php

namespace R\Hive\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class AssembleCommand extends Command
{
    protected $name = 'hive:assemble';

    protected $description = 'Create a new Hive resource collection for an instance.';

    public function fire()
    {
        $name = $this->argument('name');

        $this->call('hive:instance', ['name' => $name, '-e' => 'bar', '-m' => 'bar']);
        $this->call('hive:factory', ['name' => $name, '-i' => 'bar']);
        $this->call('hive:repo', ['name' => $name, '-o' => 'bar']);
        $this->call('hive:controller', ['name' => $name]);
    }

    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'The name of the instance.'],
        ];
    }
}

<?php

namespace R\Hive\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class AssembleCommand extends Command
{
    protected $name = 'hive:assemble';

    protected $description = 'Create a new Hive resource collection for an instance.';

    public function fire()
    {
        $name = $this->argument('name');

        $this->call('hive:instance', ['name' => $name, '-e' => 'bar', '-m' => 'bar']);
        $this->call('hive:factory', ['name' => $name, '-i' => 'bar']);
        $this->call('hive:repo', ['name' => $name, '-o' => 'bar']);
        $this->call('hive:mutator', ['name' => $name.'Request', '-r' => 'bar']);
        $this->call('hive:controller', ['name' => $name]);
    }

    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'The name of the instance.'],
        ];
    }
}

Add mutator generation to assemble command.


<?php

namespace Orchestra\Testbench\Traits;

use Illuminate\Contracts\Console\Kernel as ConsoleKernel;

trait WithLaravelMigrations
{
    /**
     * Migrate Laravel's default migrations.
     *
     * @param  array|string  $database
     *
     * @return void
     */
    protected function loadLaravelMigrations($database)
    {
        $options = is_array($database) ? $database : ['--database' => $database];

        $options['--path'] = 'migrations';

        $this->artisan('migrate', $options);

        $this->app[ConsoleKernel::class]->setArtisan(null);

        $this->beforeApplicationDestroyed(function () use ($options) {
            $this->artisan('migrate:rollback', $options);
        });
    }
}

<?php

namespace Orchestra\Testbench\Traits;

use Illuminate\Contracts\Console\Kernel as ConsoleKernel;

trait WithLaravelMigrations
{
    /**
     * Migrate Laravel's default migrations.
     *
     * @param  array|string  $database
     *
     * @return void
     */
    protected function loadLaravelMigrations($database = [])
    {
        $options = is_array($database) ? $database : ['--database' => $database];

        $options['--path'] = 'migrations';

        $this->artisan('migrate', $options);

        $this->app[ConsoleKernel::class]->setArtisan(null);

        $this->beforeApplicationDestroyed(function () use ($options) {
            $this->artisan('migrate:rollback', $options);
        });
    }
}

Add default parameter value as [].

Add default parameter value as [].

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

    include("/secure/data_db_settings.php");

    # Read GET variables
    $stime = $_POST['stime'];
    $etime = $_POST['etime'];
    $moves = $_POST['moves'];

    $conn = mysql_connect('localhost:3036', $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    unset($dbuser, $dbpass);

    mysql_select_db('c0smic_maze-game');

    $sql= "INSERT INTO data (stime, etime, moves)
    VALUES
    ('$stime','$etime','$moves')";

    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
        die('Could not enter data: ' . mysql_error());
    }

    mysql_close($conn);
    echo $str;

?>

<?php

    include("/home/c0smic/secure/data_db_settings.php");

    # Read GET variables
    $stime = $_POST['stime'];
    $etime = $_POST['etime'];
    $moves = $_POST['moves'];

    $conn = mysql_connect('localhost:3036', $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    unset($dbuser, $dbpass);

    mysql_select_db('c0smic_maze-game');

    $sql= "INSERT INTO data (stime, etime, moves)
    VALUES
    ('$stime','$etime','$moves')";

    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
        die('Could not enter data: ' . mysql_error());
    }

    mysql_close($conn);
    echo $str;

?>

Update full directory for PHP include file


<?php

class ShippingEasy_Object
{
  public function request($meth, $path, $params=null, $payload = null)
  {
    $requestor = new ShippingEasy_ApiRequestor();
    return $requestor->request($meth, $path, $params, $payload);
  }

}

<?php

class ShippingEasy_Object
{
  public function request($meth, $path, $params=null, $payload = null, $apiKey = null, $apiSecret = null)
  {
    $requestor = new ShippingEasy_ApiRequestor();
    return $requestor->request($meth, $path, $params, $payload, $apiKey, $apiSecret);
  }

}

Update to accept partner credentials.

Update to accept partner credentials.


<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
    }
}

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            UserSeeder::class,
            default_lookup_values::class,
        ]);
    }
}

Add general seeder to artisan

Add general seeder to artisan


<?php
class commands_CompileAll extends c_ChangescriptCommand
{
	/**
	 * @return String
	 */
	function getUsage()
	{
		return "";
	}

	function getAlias()
	{
		return "ca";
	}

	/**
	 * @return String
	 */
	function getDescription()
	{
		return "compile all files that need to be compiled";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	function _execute($params, $options)
	{
		$this->message("== Compile all ==");

		$parent = $this->getParent();
		$parent->executeCommand("compileConfig");
		$parent->executeCommand("compileDocuments");
		$parent->executeCommand("compileDocumentFilters");
		$parent->executeCommand("compileRoles");
		$parent->executeCommand("compilePermissions");
		$parent->executeCommand("compileLocales");
		$parent->executeCommand("compileTags");
		$parent->executeCommand("compileListeners");
		$parent->executeCommand("compileJsDependencies");
		$parent->executeCommand("compilePhptal");
		$parent->executeCommand("compileDbSchema");
		$parent->executeCommand("compileAop");

		$this->quitOk("All files were compiled");
	}
}

<?php
class commands_CompileAll extends c_ChangescriptCommand
{
	/**
	 * @return String
	 */
	function getUsage()
	{
		return "";
	}

	function getAlias()
	{
		return "ca";
	}

	/**
	 * @return String
	 */
	function getDescription()
	{
		return "compile all files that need to be compiled";
	}

	/**
	 * @param String[] $params
	 * @param array<String, String> $options where the option array key is the option name, the potential option value or true
	 * @see c_ChangescriptCommand::parseArgs($args)
	 */
	function _execute($params, $options)
	{
		$this->message("== Compile all ==");

		$parent = $this->getParent();
		$parent->executeCommand("compileConfig");
		$parent->executeCommand("compileDocuments");
		$parent->executeCommand("compileAop");
		$parent->executeCommand("compileDocumentFilters");
		$parent->executeCommand("compileRoles");
		$parent->executeCommand("compilePermissions");
		$parent->executeCommand("compileLocales");
		$parent->executeCommand("compileTags");
		$parent->executeCommand("compileListeners");
		$parent->executeCommand("compileJsDependencies");
		$parent->executeCommand("compilePhptal");
		$parent->executeCommand("compileDbSchema");

		$this->quitOk("All files were compiled");
	}
}

[FIX] Update sequence of compile-all change command


<?php

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

class CreateDesignerTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('designer', function (Blueprint $table) {
            $table->increments('id');

            // Non-translated content
            $table->integer('image_id')->unsigned()->nullable(); // ID of image
            $table->integer('user_id')->unsigned()->nullable(); // Who own designer page

            // Timestamps
            $table->timestamps();
            $table->softDeletes();
        });
        Schema::create('designer_translation', function (Blueprint $table) {
            $table->integer('designer_id')->unsigned();
            $table->string('locale')->index();
            $table->boolean('complete');

            // Translated content
            $table->string('name');
            $table->text('content');

            $table->timestamps();

            // Unique and foreign key
            // When deleting designer model, also delete all translation models
            $table->unique(['designer_id','locale']);
            $table->foreign('designer_id')->references('id')->on('designer')->onDelete('cascade');
        });
    }

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

<?php

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

class CreateDesignerTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('designer', function (Blueprint $table) {
            $table->increments('id');

            // Non-translated content
            $table->integer('image_id')->unsigned()->nullable(); // ID of image
            $table->integer('user_id')->unsigned()->nullable(); // Who own designer page

            // Timestamps
            $table->timestamps();
            $table->softDeletes();
        });
        Schema::create('designer_translation', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('designer_id')->unsigned();
            $table->string('locale')->index();
            $table->boolean('complete');

            // Translated content
            $table->string('name');
            $table->text('content');

            $table->timestamps();

            // Unique and foreign key
            // When deleting designer model, also delete all translation models
            $table->unique(['designer_id','locale']);
            $table->foreign('designer_id')->references('id')->on('designer')->onDelete('cascade');
        });
    }

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

Add id to translation of designer.

Add id to translation of designer.


<?php

use Silex\Provider\MonologServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;

error_reporting(E_ALL ^ E_STRICT);
ini_set('display_errors', 1);

// enable the debug mode
$app['debug'] = true;

$app['twig.options'] = ['debug' => true, 'cache' => false];

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__.'/../var/log/silex_dev.log',
    'monolog.name' => 'estaty'
));

$app->register(new WebProfilerServiceProvider(), array(
    'profiler.cache_dir' => __DIR__.'/../var/cache/profiler',
));

<?php

use Silex\Provider\MonologServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;

error_reporting(E_ALL ^ E_STRICT);
ini_set('display_errors', 1);

// enable the debug mode
$app['debug'] = true;

$app['twig.options'] = ['debug' => true, 'cache' => false];

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__.'/../var/log/silex_dev.log',
    'monolog.name' => 'estaty'
));

if ('cli' !== PHP_SAPI) {
    $app->register(new WebProfilerServiceProvider(), array(
        'profiler.cache_dir' => __DIR__.'/../var/cache/profiler',
    ));
}

Disable Web Profiler for CLI SAPI

Disable Web Profiler for CLI SAPI


<?php

class CRM_Speakcivi_Logic_Consent {
  public $publicId;
  public $version;
  public $language;
  public $date;
  public $createDate;
  public $level;
  public $method;
  public $methodOption;

  /**
   * @param $param
   *
   * @return array
   */
  public static function prepareFields($param) {
    $consents = [];
    if (property_exists($param, 'consents')) {
      foreach ($param->consents as $consent) {
        list($consentVersion, $consentLanguage) = explode('-', $consent->public_id);
        $cd = new DateTime(substr($param->create_dt, 0, 10));
        $c = new self();
        $c->publicId = $consent->public_id;
        $c->version = $consentVersion;
        $c->language = $consentLanguage;
        $c->date = $cd->format('Y-m-d');
        $c->createDate = $cd->format('Y-m-d H:i:s');
        $c->level = $consent->consent_level;
        $c->method = $consent->consent_method;
        $c->methodOption = $consent->consent_method_option;
        $consents[] = $c;
      }
    }
    return $consents;
  }

}

<?php

class CRM_Speakcivi_Logic_Consent {
  public $publicId;
  public $version;
  public $language;
  public $date;
  public $createDate;
  public $level;
  public $method;
  public $methodOption;

  /**
   * @param $param
   *
   * @return array
   */
  public static function prepareFields($param) {
    $consents = [];
    if (property_exists($param, 'consents')) {
      foreach ($param->consents as $consent) {
        list($consentVersion, $consentLanguage) = explode('-', $consent->public_id);
        $cd = new DateTime(substr($param->create_dt, 0, 10));
        $c = new self();
        $c->publicId = $consent->public_id;
        $c->version = $consentVersion;
        $c->language = $consentLanguage;
        $c->date = $cd->format('Y-m-d');
        $c->createDate = $param->create_dt;
        $c->level = $consent->consent_level;
        $c->method = $consent->consent_method;
        $c->methodOption = $consent->consent_method_option;
        $consents[] = $c;
      }
    }
    return $consents;
  }

}

Fix date of DPA activity properly

Fix date of DPA activity properly


<?php namespace Way\Generators\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ControllerGeneratorCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'generate:controller';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a resourceful controller';

    /**
     * Generate the controller
     */
    public function fire()
    {
        // This command is nothing more than a helper,
        // that points directly to Laravel's
        // controller:make command
        $this->call('controller:make', [
            'name' => $this->argument('controllerName'),
            '--path' => $this->option('path')
        ]);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('controllerName', InputArgument::REQUIRED, 'The name of the desired controller')
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('path', null, InputOption::VALUE_OPTIONAL, 'Where should the file be created?', app_path('controllers')),
        );
    }

}

<?php namespace Way\Generators\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ControllerGeneratorCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'generate:controller';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a resourceful controller';

    /**
     * Generate the controller
     */
    public function fire()
    {
        // This command is nothing more than a helper,
        // that points directly to Laravel's
        // controller:make command
        $this->call('controller:make', [
            'name' => $this->argument('controllerName'),
            '--path' => $this->option('path')
        ]);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('controllerName', InputArgument::REQUIRED, 'The name of the desired controller')
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('path', null, InputOption::VALUE_OPTIONAL, 'Where should the file be created?'),
        );
    }

}

Fix file not found bug

Fix file not found bug


<?php

namespace AWurth\SilexUser\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;

class UserEvent extends Event
{
    /**
     * @var null|Request
     */
    protected $request;

    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * UserEvent constructor.
     *
     * @param UserInterface $user
     * @param Request|null  $request
     */
    public function __construct(UserInterface $user, Request $request = null)
    {
        $this->user = $user;
        $this->request = $request;
    }

    /**
     * @return UserInterface
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }
}

<?php

namespace AWurth\SilexUser\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Request;
use AWurth\SilexUser\Entity\UserInterface;

class UserEvent extends Event
{
    /**
     * @var null|Request
     */
    protected $request;

    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * UserEvent constructor.
     *
     * @param UserInterface $user
     * @param Request|null  $request
     */
    public function __construct(UserInterface $user, Request $request = null)
    {
        $this->user = $user;
        $this->request = $request;
    }

    /**
     * @return UserInterface
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }
}

Use SilexUser's UserInterface instead of the Symfony Security Component one


<?php

namespace Aptoma\Silex\Provider;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Extends Guzzle service provider for Silex to provide global plugin sipport
 */
class GuzzleServiceProvider implements ServiceProviderInterface
{
    /**
     * Register Guzzle with Silex
     *
     * @param Container $app App container to register with
     */
    public function register(Container $app)
    {
        $app['guzzle.handler_stack'] = function () {
            $stack = HandlerStack::create();

            return $stack;
        };

        $app['guzzle'] = function () {
            $client = new HttpClient([
                'handler' => $app['guzzle.handler_stack']
            ]);

            return $client;
        };
    }
}

<?php

namespace Aptoma\Silex\Provider;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Extends Guzzle service provider for Silex to provide global plugin sipport
 */
class GuzzleServiceProvider implements ServiceProviderInterface
{
    /**
     * Register Guzzle with Silex
     *
     * @param Container $app App container to register with
     */
    public function register(Container $app)
    {
        $app['guzzle.handler_stack'] = function () {
            $stack = HandlerStack::create();

            return $stack;
        };

        $app['guzzle'] = function () use ($app) {
            $client = new HttpClient([
                'handler' => $app['guzzle.handler_stack']
            ]);

            return $client;
        };
    }
}

Fix issue with guzzle service provider

Fix issue with guzzle service provider


<?php

/**
 * This file is part of ReactGuzzleRing.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\React\Guzzle\HttpClient;

use Psr\Http\Message\RequestInterface;
use React\EventLoop\LoopInterface;
use React\HttpClient\Client as HttpClient;

/**
 * Class RequestFactory
 *
 * @package WyriHaximus\React\Guzzle\HttpClient
 */
class RequestFactory
{
    /**
     *
     * @param RequestInterface $request
     * @param array $options
     * @param HttpClient $httpClient
     * @param LoopInterface $loop
     * @return \React\Promise\Promise
     */
    public function create(RequestInterface $request, array $options, HttpClient $httpClient, LoopInterface $loop)
    {
        return Request::send($request, $options, $httpClient, $loop);
    }
}

<?php

/**
 * This file is part of ReactGuzzleRing.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\React\Guzzle\HttpClient;

use Clue\React\Buzz\Browser;
use Clue\React\Buzz\Io\Sender;
use Psr\Http\Message\RequestInterface;
use React\EventLoop\LoopInterface;
use React\HttpClient\Client as HttpClient;

/**
 * Class RequestFactory
 *
 * @package WyriHaximus\React\Guzzle\HttpClient
 */
class RequestFactory
{
    /**
     *
     * @param RequestInterface $request
     * @param array $options
     * @param HttpClient $httpClient
     * @param LoopInterface $loop
     * @return \React\Promise\Promise
     */
    public function create(RequestInterface $request, array $options, HttpClient $httpClient, LoopInterface $loop)
    {
        return (new Browser($loop, new Sender($httpClient)))->send($request);
    }
}

Use the browser to send the request

Use the browser to send the request


<?php
namespace Devture\Bundle\LocalizationBundle\Translation;
use Symfony\Component\Translation\Translator;

class ResourceLoader {

    private $translator;
    private $format;

    public function __construct(Translator $translator, $format) {
        $this->translator = $translator;
        $this->format = $format;
    }

    public function addResources($path) {
        $path = rtrim($path, '/');
        foreach (glob($path . '/*.' . $this->format) as $filePath) {
            $parts = explode('/', $filePath);
            list($localeKey, $_extension) = explode('.', array_pop($parts));
            $this->translator->addResource($this->format, $filePath, $localeKey);
        }
    }

}

<?php
namespace Devture\Bundle\LocalizationBundle\Translation;
use Symfony\Component\Translation\Translator;

class ResourceLoader {

    private $translator;
    private $format;

    public function __construct(Translator $translator, $format) {
        $this->translator = $translator;
        $this->format = $format;
    }

    public function addResources($path, $loaderName = null) {
        if ($loaderName === null) {
            $loaderName = $this->format;
        }
        $path = rtrim($path, '/');
        foreach (glob($path . '/*.' . $this->format) as $filePath) {
            $parts = explode('/', $filePath);
            list($localeKey, $_extension) = explode('.', array_pop($parts));
            $this->translator->addResource($loaderName, $filePath, $localeKey);
        }
    }

}

Allow custom translation loader for resources.


<?php

namespace Fenrizbes\TypographBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('fenrizbes_typograph');

        $rootNode
            ->children()
                ->arrayNode('configs')
                    ->useAttributeAsKey('name')

                    ->prototype('array')
                        ->useAttributeAsKey('name')
                        ->prototype('variable')->end()
                    ->end()

                    ->defaultValue(array(
                        'default' => array(
                            'Text.paragraphs'           => 'off',
                            'Text.breakline'            => 'off',
                            'OptAlign.oa_oquote'        => 'off',
                            'OptAlign.oa_obracket_coma' => 'off'
                        )
                    ))
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace Fenrizbes\TypographBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('fenrizbes_typograph');

        $rootNode
            ->children()
                ->arrayNode('configs')
                    ->useAttributeAsKey('name')

                    ->prototype('array')
                        ->useAttributeAsKey('name')
                        ->prototype('variable')->end()
                    ->end()

                    ->defaultValue(array(
                        'default' => array(
                            'Text.paragraphs'           => 'off',
                            'Text.breakline'            => 'off',
                            'Text.auto_links'           => 'off',
                            'Text.email'                => 'off',
                            'OptAlign.oa_oquote'        => 'off',
                            'OptAlign.oa_obracket_coma' => 'off'
                        )
                    ))
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Disable auto links by default

Disable auto links by default


<?php

namespace Nectary;

use PDO;

/**
 * Just a common class for all daos to extend
 *
 * @package Dao
 */
abstract class Dao {
	public $db;

	/**
	 * Set up the PDO
	 *
	 * @constructor
	 * @param PDO $db
	 */
	public function __construct( PDO $db ) {
		$this->set_pdo( $db );
	}

	/**
	 * Clean up
	 *
	 * @deconstructor
	 */
	public function __destruct() {
		unset( $this->db );
	}

	public function set_pdo( PDO $db ) {
		$this->db = $db;
	}

	/**
	 * Child classes need to implement get_by_criterion
	 *
	 * @abstract
	 * @param $options
	 */
	abstract public function get_by_criterion( $options );
}

<?php

namespace Nectary;

use PDO;

/**
 * Just a common class for all daos to extend
 *
 * @package Dao
 */
abstract class Dao {
	public $db;

	/**
	 * Set up the PDO
	 *
	 * @constructor
	 * @param PDO $db
	 */
	public function __construct( PDO $db ) {
		$this->set_pdo( $db );
	}

	/**
	 * Clean up
	 *
	 * @deconstructor
	 */
	public function __destruct() {
		unset( $this->db );
	}

	public function set_pdo( PDO $db ) {
		$this->db = $db;
	}

	/**
	 * Child classes need to implement get_by_criterion
	 *
	 * @abstract
	 * @param  array|null $options
	 * @return mixed
	 */
	abstract public function get_by_criterion( $options );
}

Update phpdoc notation on DAO

Update phpdoc notation on DAO


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

error_reporting(error_reporting() & ~E_USER_DEPRECATED);

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

$dotenv = new Dotenv(__DIR__ . '/../');
$dotenv->overLoad();

return $loader;

<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

error_reporting(error_reporting() & ~E_USER_DEPRECATED);

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

if (!isset($_SERVER['SYMFONY_ENV'])) {
    $dotenv = new Dotenv\Dotenv(__DIR__ . '/../');
    $dotenv->overLoad();
}
$dotenv = new Dotenv\Dotenv(__DIR__ . '/../');
$dotenv->overLoad();

return $loader;

Load the .env file only if the environment variables are not set


#!/usr/bin/env php
<?php
error_reporting(E_ALL);

function gtk_die($message) {
    $dialog = new \GtkMessageDialog(null, 0, \Gtk::MESSAGE_ERROR, \Gtk::BUTTONS_OK, $message);
    $dialog->set_markup($message);
    $dialog->run();
    $dialog->destroy();
    die($message."\n");
}

if (!extension_loaded('php-gtk')) {
    die("ERROR: PHP Gtk2 not loaded!\n");
}

if (version_compare('5.3.0', PHP_VERSION, '>')) {
    gtk_die('PHP Explorer requires PHP 5.3.0 or newer.');
}

if (!extension_loaded('phar')) {
    gtk_die('PHAR Extension not loaded! Terminating.');
}

if(!phar::canCompress()) {
    gtk_die('PHAR Extension has no compression support.');
}

ini_set('include_path', 'phar://'.__FILE__.PATH_SEPARATOR.ini_get('include_path'));

include 'stuff.php';
include 'Explorer/Controller/MainWindowController.php';
include 'Explorer/Manual/Manual.php';

$main = new Explorer\Controller\MainWindowController('phar://'.__FILE__.'/data/explorer.glade');
Gtk::Main();

__HALT_COMPILER(); ?>

#!/usr/bin/env php
<?php
error_reporting(E_ALL);

function gtk_die($message) {
    $dialog = new \GtkMessageDialog(null, 0, \Gtk::MESSAGE_ERROR, \Gtk::BUTTONS_OK, $message);
    $dialog->set_markup($message);
    $dialog->run();
    $dialog->destroy();
    die($message."\n");
}

if (!extension_loaded('php-gtk')) {
    die("ERROR: PHP Gtk2 not loaded!\n");
}

if (version_compare('5.3.0', PHP_VERSION, '>')) {
    gtk_die('PHP Explorer requires PHP 5.3.0 or newer.');
}

if (!extension_loaded('phar')) {
    gtk_die('PHAR Extension not loaded! Terminating.');
}

if(!phar::canCompress()) {
    gtk_die('PHAR Extension has no compression support.');
}

if (basename(__FILE__) == 'explorer.php') {
    ini_set('include_path', __DIR__.PATH_SEPARATOR.ini_get('include_path'));
    $gladefile = __DIR__.'/data/explorer.glade';
} else {
    ini_set('include_path', 'phar://'.__FILE__.PATH_SEPARATOR.ini_get('include_path'));
    $gladefile = 'phar://'.__FILE__.'/data/explorer.glade';
}

include 'stuff.php';
include 'Explorer/Controller/MainWindowController.php';
include 'Explorer/Manual/Manual.php';

$main = new Explorer\Controller\MainWindowController($gladefile);
Gtk::Main();

__HALT_COMPILER(); ?>

Allow running outside from a phar archive


<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		// $this->call('UserTableSeeder');
	}

}

<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$this->call('CategoriesTableSeeder');

        $this->command->info('Categories table seeded!');
	}

}

class CategoriesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('categories')->delete();

        DB::table('categories')->insert([
        	['name' => 'Aide à domicile'],
        	['name' => 'Babysitting'],
        	['name' => 'Cobaye pour expériences'],
        	['name' => 'Informatique'],
        	['name' => 'Job de bureau'],
        	['name' => 'Promotion'],
        	['name' => 'Restauration - Hôtellerie'],
        	['name' => 'Soutien scolaire'],
        	['name' => 'Autre']
        ]);
    }

}

Create seed class for Categories

Create seed class for Categories