<?php
define('ENVIRONMENT_DEVELOPMENT', 0);
define('ENVIRONMENT_HNEWS_CO', 2);

define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');

require_once(INC_PATH.'environment.php');

if(ENVIRONMENT_CURRENT === ENVIRONMENT_HNEWS_CO){
	define('BASE_URL','http://www.hnews.co/');
}
else{
	error_reporting(E_ALL);
	define('BASE_URL','/h-news/public_html/');
}

define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

define('HOME_URL', BASE_URL);
define('SHOW_URL', BASE_URL.'show/');
define('ASK_URL', BASE_URL.'ask/');
define('SETTINGS_URL', BASE_URL.'settings/');

define('COMMENTS_QUERY_URL', BASE_URL.'comments/');
define('ASK_COMMENTS_QUERY_URL', ASK_URL.'comments/');
define('SHOW_COMMENTS_QUERY_URL', SHOW_URL.'comments/');

define('PAGE_TITLE_DEFAULT', 'H News');

<?php
define('ENVIRONMENT_DEVELOPMENT', 0);
define('ENVIRONMENT_HNEWS_CO', 2);

define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');

require_once(INC_PATH.'environment.php');

define('BASE_URL','/');

define('STYLES_URL', BASE_URL.'assets/');
define('SCRIPTS_URL', BASE_URL.'assets/');

define('HOME_URL', BASE_URL);
define('SHOW_URL', BASE_URL.'show/');
define('ASK_URL', BASE_URL.'ask/');
define('SETTINGS_URL', BASE_URL.'settings/');

define('COMMENTS_QUERY_URL', BASE_URL.'comments/');
define('ASK_COMMENTS_QUERY_URL', ASK_URL.'comments/');
define('SHOW_COMMENTS_QUERY_URL', SHOW_URL.'comments/');

define('PAGE_TITLE_DEFAULT', 'H News');

Change urls for scripts and css for webpack


<?php

use app\models\settings\AntragsgruenApp;

/**
 * @var AntragsgruenApp $params
 */

define('ANTRAGSGRUEN_VERSION', '3.1.0');
define('ANTRAGSGRUEN_HISTORY_URL', 'https://github.com/CatoTH/antragsgruen/blob/master/History.md');

// For PHPExcel
define('PCLZIP_TEMPORARY_DIR', $params->tmpDir);

<?php

use app\models\settings\AntragsgruenApp;

/**
 * @var AntragsgruenApp $params
 */

define('ANTRAGSGRUEN_VERSION', '3.2.0a');
define('ANTRAGSGRUEN_HISTORY_URL', 'https://github.com/CatoTH/antragsgruen/blob/v3/History.md');

// For PHPExcel
define('PCLZIP_TEMPORARY_DIR', $params->tmpDir);

Update Version + Changelog URL

Update Version + Changelog URL


<?php

namespace Devlabs\SportifyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;

class AdminController extends Controller
{
    /**
     * @Route("/admin", name="admin_index")
     */
    public function indexAction()
    {
        // if user is not logged in, redirect to login page
        $securityContext = $this->container->get('security.authorization_checker');
        if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            return $this->redirectToRoute('fos_user_security_login');
        }

        // Load the data for the current user into an object
        $user = $this->getUser();

        if (!($user->getEmail() !== 'ceco@devlabs.bg')) {
            return $this->redirectToRoute('home');
        }

        // Get an instance of the Entity Manager
        $em = $this->getDoctrine()->getManager();

        $tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
            ->findOneById(12);

        $dataUpdatesManager = $this->get('app.data_updates.manager');
        $dataUpdatesManager->setEntityManager($em);

        $dataUpdatesManager->updateTeamsByTournament($tournament);
//        $dataUpdatesManager->updateFixtures();

        return $this->redirectToRoute('home');
    }
}

<?php

namespace Devlabs\SportifyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;

class AdminController extends Controller
{
    /**
     * @Route("/admin", name="admin_index")
     */
    public function indexAction()
    {
        // if user is not logged in, redirect to login page
        $securityContext = $this->container->get('security.authorization_checker');
        if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            return $this->redirectToRoute('fos_user_security_login');
        }

        // Load the data for the current user into an object
        $user = $this->getUser();

        // continue only if user has Admin access, else redirect to Home
        if ($user->getEmail() !== 'ceco@devlabs.bg') {
            return $this->redirectToRoute('home');
        }

        // Get an instance of the Entity Manager
        $em = $this->getDoctrine()->getManager();

        $tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
            ->findOneById(12);

        $dataUpdatesManager = $this->get('app.data_updates.manager');
        $dataUpdatesManager->setEntityManager($em);

        $dataUpdatesManager->updateTeamsByTournament($tournament);
//        $dataUpdatesManager->updateFixtures();

        return $this->redirectToRoute('home');
    }
}

Fix admin page permitted user logic

Fix admin page permitted user logic


<?php
namespace Desmond\functions\core;
use Desmond\functions\DesmondFunction;
use Desmond\functions\FileOperations;
use Desmond\data_types\ListType;

class FunctionList extends DesmondFunction
{
    public function id()
    {
        return 'function-list';
    }

    public function run(array $args)
    {
        $list = [
            'define', 'let', 'do', 'if',
            'lambda', 'load-file', 'eval',
            'try'
        ];
        foreach (FileOperations::getFunctionFiles() as $file) {
            $class = sprintf('Desmond\\functions\\core\\%s', substr($file, 0, -4));
            $function = new $class;
            $list[] = $function->id();
        }
        return new ListType($list);
    }
}

<?php
namespace Desmond\functions\core;
use Desmond\functions\DesmondFunction;
use Desmond\functions\FileOperations;

class FunctionList extends DesmondFunction
{
    use \Desmond\TypeHelper;

    public function id()
    {
        return 'function-list';
    }

    public function run(array $args)
    {
        $list = [
            'define', 'let', 'do', 'if',
            'lambda', 'load-file', 'eval',
            'try'
        ];
        foreach (FileOperations::getFunctionFiles() as $file) {
            $class = sprintf('Desmond\\functions\\core\\%s', substr($file, 0, -4));
            $function = new $class;
            $list[] = $function->id();
        }
        return self::fromPhpType($list);
    }
}

Update (function-list) to return a proper Desmond collection.


					© <?php echo date("Y"); ?> Copyright <?php bloginfo('name'); ?>. <?php _e('Powered by', 'html5blank'); ?>
					WordPress & HTML5 Blank.

		<?php wp_footer(); ?>

Update to universal Google Analytics

Update to universal Google Analytics


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

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

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('auth/login');
            }
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

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

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('auth/login');
            }
        }

        return $next($request);
    }
}

Create a new middlware instance instead of filter.

Shouldn't this be middleware?


<?php

namespace PhpPact\Standalone\Installer\Service;

use PhpPact\Standalone\Installer\Model\Scripts;

class InstallerPosixPreinstalled implements InstallerInterface
{
    /**
     * {@inheritdoc}
     */
    public function isEligible(): bool
    {
        return in_array(PHP_OS, ['Linux', 'Darwin']) && !empty($this->getBinaryPath('pact-provider-verifier'));
    }

    /**
     * {@inheritdoc}
     */
    public function install(string $destinationDir): Scripts
    {
        $scripts = new Scripts(
            'pact-mock-service',
            'pact-stub-service',
            'pact-provider-verifier',
            'pact-message',
            'pact-broker'
        );

        return $scripts;
    }

    private function getBinaryPath($binary)
    {
        return trim(shell_exec('command -v ' . escapeshellarg($binary)));
    }
}

<?php

namespace PhpPact\Standalone\Installer\Service;

use PhpPact\Standalone\Installer\Model\Scripts;

class InstallerPosixPreinstalled implements InstallerInterface
{
    /**
     * {@inheritdoc}
     */
    public function isEligible(): bool
    {
        return in_array(PHP_OS, ['Linux', 'Darwin']) && !empty($this->getBinaryPath('pact-provider-verifier'));
    }

    /**
     * {@inheritdoc}
     */
    public function install(string $destinationDir): Scripts
    {
        $scripts = new Scripts(
            'pact-mock-service',
            'pact-stub-service',
            'pact-provider-verifier',
            'pact-message',
            'pact-broker'
        );

        return $scripts;
    }

    private function getBinaryPath(string $binary): string
    {
        return trim(shell_exec('command -v ' . escapeshellarg($binary)));
    }
}

Add typehints to private function

chore: Add typehints to private function


<?php

declare(strict_types=1);

namespace Tests;

use Giuffre\Sprint\Sprint;
use PHPUnit\Framework\TestCase;

class SprintTest extends TestCase
{
    public function testSprint()
    {
        $result = Sprint::sprint(
            'Le mele sono %s[come] e di colore %s[colore]',
            ['colore' => 'verde'],
            ['come' => 'buone']
        );

        $this->assertEquals(
            'Le mele sono buone e di colore verde',
            $result
        );
    }
}

<?php

declare(strict_types=1);

namespace Tests;

use Giuffre\Sprint\Sprint;
use PHPUnit\Framework\TestCase;

class SprintTest extends TestCase
{
    public function testSprintWithNamedParameters()
    {
        $result = Sprint::sprint(
            'Le mele sono %s[come] e di colore %s[colore]',
            ['colore' => 'verde'],
            ['come' => 'buone']
        );

        $this->assertEquals(
            'Le mele sono buone e di colore verde',
            $result
        );
    }

    public function testSprintWithNamedParametersArray()
    {
        $result = Sprint::sprint(
            'Le mele sono %s[come] e di colore %s[colore]',
            ['colore' => 'verde', 'come' => 'buone']
        );

        $this->assertEquals(
            'Le mele sono buone e di colore verde',
            $result
        );
    }
}

Test parameters in an array

Test parameters in an array


<?php
date_default_timezone_set('UTC');

if (substr(phpversion(), 0, 3) != '5.2') {
  error_reporting(E_ALL ^ E_DEPRECATED ^ E_NOTICE);
}

include __DIR__ . '/../paths.php';

<?php
//Running PHPUnit 3.5.15 this is to fix bug
require_once('PHP/Token/Stream/Autoload.php');

date_default_timezone_set('UTC');

if (substr(phpversion(), 0, 3) != '5.2') {
  error_reporting(E_ALL ^ E_DEPRECATED ^ E_NOTICE);
}

include __DIR__ . '/../paths.php';

Fix bug in tests for PHPUnit 3.5.15

Fix bug in tests for PHPUnit 3.5.15


<?php

namespace Amp\Dns\Test;

use Amp\Dns;
use Amp\Loop;
use Amp\PHPUnit\TestCase;
use Amp\Promise;
use LibDNS\Messages\Message;
use LibDNS\Messages\MessageTypes;
use LibDNS\Records\QuestionFactory;

abstract class SocketTest extends TestCase {
    abstract protected function connect(): Promise;

    public function testAsk() {
        Loop::run(function () {
            $question = (new QuestionFactory)->create(Dns\Record::A);
            $question->setName("google.com");

            /** @var Dns\Internal\Socket $socket */
            $socket = yield $this->connect();

            /** @var Message $result */
            $result = yield $socket->ask($question, 5000);

            $this->assertInstanceOf(Message::class, $result);
            $this->assertSame(MessageTypes::RESPONSE, $result->getType());
        });
    }

    public function testGetLastActivity() {
        Loop::run(function () {
            $question = (new QuestionFactory)->create(Dns\Record::A);
            $question->setName("google.com");

            /** @var Dns\Internal\Socket $socket */
            $socket = yield $this->connect();

            $this->assertTrue($socket->getLastActivity() < time() + 1);
        });
    }
}

<?php

namespace Amp\Dns\Test;

use Amp\Dns;
use Amp\Loop;
use Amp\PHPUnit\TestCase;
use Amp\Promise;
use LibDNS\Messages\Message;
use LibDNS\Messages\MessageTypes;
use LibDNS\Records\QuestionFactory;

abstract class SocketTest extends TestCase {
    abstract protected function connect(): Promise;

    public function testAsk() {
        Loop::run(function () {
            $question = (new QuestionFactory)->create(Dns\Record::A);
            $question->setName("google.com");

            /** @var Dns\Internal\Socket $socket */
            $socket = yield $this->connect();

            /** @var Message $result */
            $result = yield $socket->ask($question, 5000);

            $this->assertInstanceOf(Message::class, $result);
            $this->assertSame(MessageTypes::RESPONSE, $result->getType());
        });
    }

    public function testGetLastActivity() {
        Loop::run(function () {
            $question = (new QuestionFactory)->create(Dns\Record::A);
            $question->setName("google.com");

            /** @var Dns\Internal\Socket $socket */
            $socket = yield $this->connect();

            $this->assertLessThan(time() + 1, $socket->getLastActivity());
        });
    }
}

Use assertLessThan over simple assertTrue


<?php

namespace PHPOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;

/**
 * Class MediaFolder
 *
 * @ODM\Document(
 *   repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
 * )
 */
class MediaFolder extends Folder implements MediaFolderInterface
{
    /**
     * @var Collection
     *
     * @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
     */
    protected $medias;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->medias = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getMedias()
    {
        return $this->medias;
    }

    /**
     * @param MediaInterface $media
     */
    public function addMedia(MediaInterface $media)
    {
        $this->medias->add($media);
    }

    /**
     * @param MediaInterface $media
     */
    public function removeMedia(MediaInterface $media)
    {
        $this->medias->removeElement($media);
    }
}

<?php

namespace PHPOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;

/**
 * Class MediaFolder
 *
 * @ODM\Document(
 *   repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
 * )
 */
class MediaFolder extends Folder implements MediaFolderInterface
{
    /**
     * @var Collection
     *
     * @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
     */
    protected $medias;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->medias = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getMedias()
    {
        return $this->medias;
    }

    /**
     * @param MediaInterface $media
     */
    public function addMedia(MediaInterface $media)
    {
        $this->medias->add($media);
        $media->setMedialFolder($this);
    }

    /**
     * @param MediaInterface $media
     */
    public function removeMedia(MediaInterface $media)
    {
        $this->medias->removeElement($media);
    }
}

Add crud for folder in navigation

Add crud for folder in navigation


Update registration of Twig view

Update registration of Twig view

It now maches the way the Twig-View readme suggests.


<?php

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

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

$app = new Yolo\Application();

$app->get('hello', '/', function (Request $request) {
    return new Response("Hallo welt, got swag yo!\n");
});

$app->get('error', '/error', function (Request $request) {
    throw new \Exception('Holy crap, explosion!');
});

$app->run();

<?php

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

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

$app = new Yolo\Application();

$app->get('hello', '/', function (Request $request) {
    return new Response("Hallo welt, got swag yo!\n");
});

$app->get('explosion', '/explosion', function (Request $request) {
    throw new \Exception('Holy crap, explosion!');
});

$app->run();

Rename error page to explosion

Rename error page to explosion


<?php

class PodioError extends Exception {
  public $body;
  public $status;
  public $url;
  public function __construct($body, $status, $url) {
    $this->body = json_decode($body, TRUE);
    $this->status = $status;
    $this->url = $url;
  }
}
class PodioInvalidGrantError extends PodioError {}
class PodioBadRequestError extends PodioError {}
class PodioAuthorizationError extends PodioError {}
class PodioNotFoundError extends PodioError {}
class PodioConflictError extends PodioError {}
class PodioGoneError extends PodioError {}
class PodioRateLimitError extends PodioError {}
class PodioServerError extends PodioError {}
class PodioUnavailableError extends PodioError {}
class PodioMissingRelationshipError extends PodioError {}

<?php

class PodioError extends Exception {
  public $body;
  public $status;
  public $url;
  public function __construct($body, $status, $url) {
    $this->body = json_decode($body, TRUE);
    $this->status = $status;
    $this->url = $url;
    if (!empty($this->body['error_description'])) {
      $this->message = $this->body['error_description'];
    }
  }

}
class PodioInvalidGrantError extends PodioError {}
class PodioBadRequestError extends PodioError {}
class PodioAuthorizationError extends PodioError {}
class PodioNotFoundError extends PodioError {}
class PodioConflictError extends PodioError {}
class PodioGoneError extends PodioError {}
class PodioRateLimitError extends PodioError {}
class PodioServerError extends PodioError {}
class PodioUnavailableError extends PodioError {}
class PodioMissingRelationshipError extends PodioError {}

Set Exception message for easier debugging


<?php

/**
 * @file
 * Contains \Drupal\Console\Command\DrushCommand.
 */

namespace Drupal\Console\Command;

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

class DrushCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('drush')
            ->setDescription($this->trans('commands.drush.description'))
            ->addArgument('args', InputArgument::IS_ARRAY, $this->trans('commands.drush.arguments.args'))
            ->setHelp($this->trans('commands.drush.help'));
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $args = '';
        if ($arguments = $input->getArgument('args')) {
            $args .= ' '.implode(' ', $arguments);
            $c_args = preg_replace('/[^a-z0-9-= ]/i', '', $args);
        }

        if (`which drush`) {
            system('drush'.$c_args);
        } else {
            $output->write('<error>'.$this->trans('commands.drush.message.not_found').'</error>');
        }
    }
}

<?php

/**
 * @file
 * Contains \Drupal\Console\Command\DrushCommand.
 */

namespace Drupal\Console\Command;

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

class DrushCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('drush')
            ->setDescription($this->trans('commands.drush.description'))
            ->addArgument(
                'args',
                InputArgument::IS_ARRAY,
                $this->trans('commands.drush.arguments.args')
            )
            ->setHelp($this->trans('commands.drush.help'));
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $args = '';
        if ($arguments = $input->getArgument('args')) {
            $args .= ' '.implode(' ', $arguments);
            $c_args = preg_replace('/[^a-z0-9-= ]/i', '', $args);
        }

        if (`which drush`) {
            system('drush'.$c_args);
        } else {
            $this->getMessageHelper()->addErrorMessage(
                $this->trans('commands.drush.message.not_found')
            );
        }
    }
}

[drush] Improve drush command, make stand alone command


<?php

/**
 * Base model for Quill
 */
class BaseModel extends Eloquent {

	protected $guarded = ['id'];

	public $errors;

	public function validate()
	{
		$v = Validator::make($this->attributes, static::$rules);
		if ($v->passes()) return true;
		$this->errors = $v->messages();
		return false;
	}

}

<?php

/**
 * Base model for Quill
 */
class BaseModel extends Eloquent {

	protected $guarded = ['id'];

	public $errors;

	public static $messages = array();

	public function validate()
	{
		$v = Validator::make($this->attributes, static::$rules, static::$messages);
		if ($v->passes()) return true;
		$this->errors = $v->messages();
		return false;
	}

}

Allow custom validation error messages to be set on models


<?php
class CustomTplHelper extends SpotTemplateHelper {

	function cat2color($spot) {
		switch( (int) $spot['category']) {
			case 0: return 'blue'; break;
			case 1: return 'orange'; break;
			case 2: return 'green'; break;
			case 3: return 'red'; break;
		} # switch

		return '-';
	} # cat2color

	function getSitePath() {
		$site = $_SERVER['SERVER_NAME'];
		$source = $_SERVER['REQUEST_URI'];
		$getpath = explode('/',$source);
		$setpath = $site . "/" . $getpath[1] . "/";

		return $setpath;
	} # getSitePath

} # class CustomTplHelper

<?php
class CustomTplHelper extends SpotTemplateHelper {

	function cat2color($spot) {
		if (is_array($spot)) {
			(int) $cat = $spot['category'];
		} else {
			$cat = (int) $spot;
		} # else

		switch( $cat ) {
			case 0: return 'blue'; break;
			case 1: return 'orange'; break;
			case 2: return 'green'; break;
			case 3: return 'red'; break;
		} # switch

		return '-';
	} # cat2color

	function filter2cat($s) {
		$cat = 0;
		if (stripos($s, 'cat0') !== false) {
			return "blue";
		} elseif (stripos($s, 'cat1') !== false) {
			return "orange";
		} elseif (stripos($s, 'cat1') !== false) {
			return "green";
		} elseif (stripos($s, 'cat1') !== false) {
			return "red";
		} # else
	} # filter2cat

	function getSitePath() {
		$site = $_SERVER['SERVER_NAME'];
		$source = $_SERVER['REQUEST_URI'];
		$getpath = explode('/',$source);
		$setpath = $site . "/" . $getpath[1] . "/";

		return $setpath;
	} # getSitePath

} # class CustomTplHelper

Fix voor color selectie in filterlist

Fix voor color selectie in filterlist


<?php

/**
 * CwsDumpHelper.
 *
 * A simple helper for CwsDump
 *
 * @author Cr@zy
 * @copyright 2013-2016, Cr@zy
 * @license GNU LESSER GENERAL PUBLIC LICENSE
 *
 * @link https://github.com/crazy-max/CwsDump
 */
use Cws\CwsDump;

function cwsDump($var, $echo = true)
{
    $result = call_user_func([new CwsDump(), 'dump'], $var);
    if ($echo) {
        echo $result;

        return;
    }

    return $result;
}

<?php

/**
 * CwsDumpHelper.
 *
 * A simple helper for CwsDump
 *
 * @author Cr@zy
 * @copyright 2013-2016, Cr@zy
 * @license GNU LESSER GENERAL PUBLIC LICENSE
 *
 * @link https://github.com/crazy-max/CwsDump
 */
use Cws\CwsDump;

function cwsDump($var, $echo = true)
{
    $result = call_user_func(array(new CwsDump(), 'dump'), $var);
    if ($echo) {
        echo $result;

        return;
    }

    return $result;
}

Fix short syntax for arrays

Fix short syntax for arrays


<?php
/*
 * This file is part of sebastian/phpunit-framework-constraint.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;

class DirectoryExistsTest extends TestCase
{
    public function testConstraintDirectoryExists()
    {
        $constraint = new DirectoryExists();

        $this->assertFalse($constraint->evaluate('foo', '', true));
        $this->assertEquals('directory exists', $constraint->toString());
        $this->assertCount(1, $constraint);

        try {
            $constraint->evaluate('foo');
        } catch (ExpectationFailedException $e) {
            $this->assertEquals(
                <<<EOF
Failed asserting that directory "foo" exists.

EOF
                ,
                TestFailure::exceptionToString($e)
            );

            return;
        }

        $this->fail();
    }
}

<?php
/*
 * This file is part of sebastian/phpunit-framework-constraint.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;

class DirectoryExistsTest extends TestCase
{
    public function testDefaults()
    {
        $constraint = new DirectoryExists();

        $this->assertCount(1, $constraint);
        $this->assertEquals('directory exists', $constraint->toString());
    }

    public function testEvaluateReturnsFalseWhenDirectoryDoesNotExist()
    {
        $directory = __DIR__ . '/NonExistentDirectory';

        $constraint = new DirectoryExists();

        $this->assertFalse($constraint->evaluate($directory, '', true));
    }

    public function testEvaluateReturnsTrueWhenDirectoryExists()
    {
        $directory = __DIR__;

        $constraint = new DirectoryExists();

        $this->assertTrue($constraint->evaluate($directory, '', true));
    }

    public function testEvaluateThrowsExpectationFailedExceptionWhenDirectoryDoesNotExist()
    {
        $directory = __DIR__ . '/NonExistentDirectory';

        $constraint = new DirectoryExists();

        try {
            $constraint->evaluate($directory);
        } catch (ExpectationFailedException $e) {
            $this->assertEquals(
                <<<PHP
Failed asserting that directory "$directory" exists.

PHP
                ,
                TestFailure::exceptionToString($e)
            );

            return;
        }

        $this->fail();
    }
}

Fix: Split test cases and add test for DirectoryExists


<?php

class StaffAdmin extends ModelAdmin
{

    private static $managed_models = array(
    'Staff',
    'StaffCategory'
  );
    private static $url_segment = 'staff';
    private static $menu_title = 'Staff';
    private static $menu_icon = 'staff/images/staffadmin-file.png';

    public function canCreate($Member = null)
    {
        return true;
    }
    public function canEdit($Member = null)
    {
        return true;
    }
    public function canView($Member = null)
    {
        return true;
    }
    public function canDelete($Member = null)
    {
        return true;
    }

    public function getEditForm($id = null, $fields = null)
    {
        $form=parent::getEditForm($id, $fields);
        if ($this->modelClass=='Staff' && $gridField=$form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) {
        }
        return $form;
    }
}

<?php

class StaffAdmin extends ModelAdmin
{

    private static $managed_models = array(
    'Staff',
    'StaffCategory'
  );
    private static $url_segment = 'staff';
    private static $menu_title = 'Staff';
    private static $menu_icon = 'staff/images/staffadmin-file.png';

    public function canCreate($Member = null)
    {
        return true;
    }
    public function canEdit($Member = null)
    {
        return true;
    }
    public function canView($Member = null)
    {
        return true;
    }
    public function canDelete($Member = null)
    {
        return true;
    }

    public function getEditForm($id = null, $fields = null)
    {
        $form=parent::getEditForm($id, $fields);
        if ($this->modelClass=='Staff' && $gridField=$form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) {
        }
        if($gridField instanceof GridField) {
            $gridField->getConfig()->addComponent(new GridFieldSortableRows('SortOrder'));
        }
        return $form;
    }
}

Add sorting for gridfield in modeladmin

Add sorting for gridfield in modeladmin


<?php

namespace Backend;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

/**
 * This class will initiate the backend-application
 */
class Init extends \Common\Core\Init
{
    /**
     * {@inheritdoc}
     */
    protected $allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console');

    /**
     * {@inheritdoc}
     */
    public function initialize($type)
    {
        parent::initialize($type);

        \SpoonFilter::disableMagicQuotes();
    }
}

<?php

namespace Backend;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use SpoonFilter;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * This class will initiate the backend-application
 */
class Init extends \Common\Core\Init
{
    /**
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        $this->allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console');

        parent::__construct($kernel);
    }

    /**
     * {@inheritdoc}
     */
    public function initialize($type)
    {
        parent::initialize($type);

        SpoonFilter::disableMagicQuotes();
    }
}

Set the allowed types in the constructor for backend init


<?php

error_reporting(E_ALL);

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->addPsr4('Estaty\\Test\\', __DIR__);

<?php

error_reporting(E_ALL);

date_default_timezone_set('UTC');

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->addPsr4('Estaty\\Test\\', __DIR__);

Set timezone to UTC in tests

Set timezone to UTC in tests


<?php
#setup metrodb
include_once('dataitem.php');
include_once('connector.php');

Metrodb_Connector::setDsn('default', 'mysqli://root:mysql@localhost/metrodb_test');
Metrodb_Connector::setDsn('sqlite3', 'sqlite3://localhost/metrodb_test');

<?php
#setup metrodb
include_once('dataitem.php');
include_once('connector.php');

$sqliteDsn = 'sqlite3:/:memory:';
$mysqlDsn  = 'mysqli://root:mysql@localhost/metrodb_test_001?ansiQuotes';

Metrodb_Connector::setDsn('sqlite3', $sqliteDsn);
Metrodb_Connector::setDsn('default', $sqliteDsn);

if (function_exists('mysqli_select_db')) {
	Metrodb_Connector::setDsn('mysqli', $mysqlDsn);

	$x  = Metrodb_Connector::getHandleRef('mysqli');
	$y  = $x->exec('create database "metrodb_test_001"');
	if (mysqli_select_db($x->driverId, $x->database) ) {
		$x->isSelected = true;
	}
	//clean up?
	#register_shutdown_function(function(){
	#	$x  = Metrodb_Connector::getHandle('mysqli');
	#	$x->exec('drop database "metrodb_test_001"');
	#});
}

Make test DSNs more customizable

Make test DSNs more customizable

mysql is only tested if the mysqli extension exists.


<?php

$file = __DIR__.'/../vendor/autoload.php';
if (file_exists($file)) {
    $autoload = require $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

$files = array_filter(array(
    __DIR__.'/../vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/bootstrap.php',
    __DIR__.'/../vendor/symfony/phpunit-bridge/bootstrap.php',
), 'file_exists');
if ($files) {
    require_once current($files);
}

use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerLoader(array($autoload, 'loadClass'));
//AnnotationRegistry::registerFile(__DIR__.'/../lib/Doctrine/ODM/PHPCR/Mapping/Annotations/DoctrineAnnotations.php');

// tests are not autoloaded the composer.json
$autoload->add('Doctrine\Tests', __DIR__);

<?php

$file = __DIR__.'/../vendor/autoload.php';
if (file_exists($file)) {
    $autoload = require $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

$files = array_filter(array(
    __DIR__.'/../vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/bootstrap.php',
    __DIR__.'/../vendor/symfony/phpunit-bridge/bootstrap.php',
), 'file_exists');
if ($files) {
    require_once current($files);
}

use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerLoader(array($autoload, 'loadClass'));

// tests are not autoloaded the composer.json
$autoload->add('Doctrine\Tests', __DIR__);

Remove autoloading the annotatino file

Remove autoloading the annotatino file


<?php
$user       = "<user>";         // The user id
$publicKey  = "<public key>";   // The public key of the user
$privateKey = "<secret value>"; // The private key of the user
$image      = "<image>";        // The image identifier

// Image transformations
$query = [
    "t[]=thumbnail:width=40,height=40,fit=outbound",
    "t[]=border:width=3,height=3,color=000",
    "t[]=canvas:width=100,height=100,mode=center"
];

// Add a query parameter for public key if it differs from the user
if ($user != $publicKey) {
    $query[] = 'publicKey=' . $publicKey;
}

// The URI
$uri = sprintf("http://imbo/users/%s/images/%s?%s", $user, $publicKey, $image, implode('&', $query));

// Generate the token
$accessToken = hash_hmac("sha256", $uri, $privateKey);

// Output the URI with the access token
echo sprintf("%s&accessToken=%s", $uri, $accessToken);

<?php
$user       = "<user>";         // The user id
$publicKey  = "<public key>";   // The public key of the user
$privateKey = "<secret value>"; // The private key of the user
$image      = "<image>";        // The image identifier

// Image transformations
$query = [
    "t[]=thumbnail:width=40,height=40,fit=outbound",
    "t[]=border:width=3,height=3,color=000",
    "t[]=canvas:width=100,height=100,mode=center"
];

// Add a query parameter for public key if it differs from the user
if ($user != $publicKey) {
    $query[] = 'publicKey=' . $publicKey;
}

// The URI
$uri = sprintf("http://imbo/users/%s/images/%s?%s", $user, $image, implode('&', $query));

// Generate the token
$accessToken = hash_hmac("sha256", $uri, $privateKey);

// Output the URI with the access token
echo sprintf("%s&accessToken=%s", $uri, $accessToken) . PHP_EOL;

Fix incorrect access token generation example


<?php namespace Forma;

class Helpers
{

    public static function url($string)
    {
        if (static::isLaravel())
        {
            return \URL::to($string);
        }

        return $string;
    }

    public static function hasLang($string)
    {
        if (static::isLaravel())
        {
            return \Lang::has($string);
        }

        return false;
    }

    public static function lang($string)
    {
        if (static::isLaravel())
        {
            return \Lang::get($string);
        }

        return $string;
    }

    public static function input($string)
    {
        if (static::isLaravel())
        {
            return \Input::get($string);
        }

        return isset($_REQUEST[$string]) ? $_REQUEST[$string] : false;
    }

    public static function inputOld($string)
    {
        if (static::isLaravel())
        {
            return \Input::old($string);
        }

        return false;
    }

    public static function isLaravel()
    {
        return class_exists('Illuminate\Foundation\Application');
    }
}

<?php namespace Forma;

class Helpers
{

    public static function url($string)
    {
        if (static::isLaravel())
        {
            return \URL::to($string);
        }

        return $string;
    }

    public static function hasLang($string)
    {
        if (static::isLaravel())
        {
            return \Lang::has($string);
        }

        return false;
    }

    public static function lang($string)
    {
        if (static::isLaravel())
        {
            return \Lang::get($string);
        }

        return $string;
    }

    public static function input($string)
    {
        if (static::isLaravel())
        {
            return \Request::get($string);
        }

        return isset($_REQUEST[$string]) ? $_REQUEST[$string] : false;
    }

    public static function inputOld($string)
    {
        if (static::isLaravel())
        {
            return \Request::old($string);
        }

        return false;
    }

    public static function isLaravel()
    {
        return class_exists('Illuminate\Foundation\Application');
    }
}

Remove Input in favour of Request

Remove Input in favour of Request


<?php

namespace Koara\Io;

class FileReader implements Reader
{

	private $fileName;
	private $index;

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

    public function read(&$buffer, $offset, $length) {
    	$filecontent = @file_get_contents($this->fileName, false, null, $this->index, $length * 4);
    	if ($filecontent !== false && mb_strlen($filecontent) > 0) {
    		$charactersRead=0;
    		for($i=0; $i < $length; $i++) {
    			$c = mb_substr($filecontent, $i, 1);
    			if($c != NULL) {
	    			$buffer[$offset + $i] = $c;
	    			$this->index += strlen($c);
	    			$charactersRead++;
    			}
    		}
    		return $charactersRead;
    	}
    	return -1;
    }

}

<?php

namespace Koara\Io;

class FileReader implements Reader
{

	private $fileName;
	private $index;

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

    public function read(&$buffer, $offset, $length) {
    	$filecontent = @file_get_contents($this->fileName, false, null, $this->index, $length * 4);

    	if ($filecontent !== false && mb_strlen($filecontent) > 0) {
    		$charactersRead=0;
    		for($i=0; $i < $length; $i++) {
    			$c = mb_substr($filecontent, $i, 1, 'utf-8');
    			if($c != NULL) {
	    			$buffer[$offset + $i] = $c;
	    			$this->index += strlen($c);
	    			$charactersRead++;
    			}
    		}
    		return $charactersRead;
    	}
    	return -1;
    }

}

Fix encoding issue PHP 5.4

Fix encoding issue PHP 5.4


<?php
namespace Nayjest\Grids;

use Exception;
use RuntimeException;

class ObjectDataRow extends DataRow
{
    /**
     * @param string $fieldName
     * @return mixed
     * @throws Exception
     */
    protected function extractCellValue($fieldName)
    {

        if (strpos($fieldName, '.') !== false) {
            $parts = explode('.', $fieldName);
            $res = $this->src;
            foreach ($parts as $part) {
                $res = $res->{$part};
                if ($res === null) {
                    return $res;
                }
            }
            return $res;
        } else {
            try {
                return $this->src->{$fieldName};
            } catch(Exception $e) {
                throw new RuntimeException(
                    "Can't read '$fieldName' property from DataRow"
                );
            }

        }
    }
}

<?php
namespace Nayjest\Grids;

use Exception;
use RuntimeException;

class ObjectDataRow extends DataRow
{
    /**
     * @param string $fieldName
     * @return mixed
     * @throws Exception
     */
    protected function extractCellValue($fieldName)
    {

        if (strpos($fieldName, '.') !== false) {
            $parts = explode('.', $fieldName);
            $res = $this->src;
            foreach ($parts as $part) {
                $res = is_object($res) ? $res->{$part} : $res[$part];
                if ($res === null) {
                    return $res;
                }
            }
            return $res;
        } else {
            try {
                return $this->src->{$fieldName};
            } catch(Exception $e) {
                throw new RuntimeException(
                    "Can't read '$fieldName' property from DataRow"
                );
            }

        }
    }
}

Add support for array properties rendering


<?php
namespace Exercise\GoogleTranslateBundle;

class ParametersEscaper
{
    /** @var \ArrayObject */
    protected $parametersArray;

    /** @var  \ArrayIterator */
    protected $iterator;

    public function escapeParameters($string)
    {
        $this->parametersArray = new \ArrayObject();

        return preg_replace_callback(
            "|%[\S]*%|",
            array($this, 'escapeParametersCallback'),
            $string);
    }

    public function unEscapeParameters($string)
    {
        if (!$this->parametersArray) {
            throw new \Exception('You try unescape string that not be escaped');
        }

        $this->iterator = $this->parametersArray->getIterator();

        return preg_replace_callback(
            "|%[\S]*%|",
            array($this, 'unEscapeParametersCallback'),
            $string);
    }

    private function escapeParametersCallback($matches)
    {
        $this->parametersArray->append($matches['0']);

        return '%%%%';
    }

    private function unEscapeParametersCallback($matches)
    {
        $value = $this->iterator->current();
        $this->iterator->next();

        return $value;
    }
}

<?php
namespace Exercise\GoogleTranslateBundle;

class ParametersEscaper
{
    /** @var \ArrayObject */
    protected $parametersArray;

    /** @var  \ArrayIterator */
    protected $iterator;

    public function escapeParameters($string)
    {
        $this->parametersArray = new \ArrayObject();

        return preg_replace_callback(
            "|%[\S]*%|",
            array($this, 'escapeParametersCallback'),
            $string);
    }

    public function unEscapeParameters($string)
    {
        if (!$this->parametersArray) {
            throw new \Exception('You try unescape string that not be escaped');
        }

        $this->iterator = $this->parametersArray->getIterator();

        return preg_replace_callback(
            "|NotTranslatedString|",
            array($this, 'unEscapeParametersCallback'),
            $string);
    }

    private function escapeParametersCallback($matches)
    {
        $this->parametersArray->append($matches['0']);

        return 'NotTranslatedString';
    }

    private function unEscapeParametersCallback($matches)
    {
        $value = $this->iterator->current();
        $this->iterator->next();

        return $value;
    }
}

Upgrade ParameterEscaper. Fix some issues by translate.


<?php namespace Lio\Github;

class GistEmbedFormatter
{
    protected $pattern = '/(https:\/\/gist.github.com\/\w+\/\w+)/';

    public function format($html)
    {
        return preg_replace($this->pattern, '$0', $html);
    }
}

<?php namespace Lio\Github;

class GistEmbedFormatter
{
    protected $pattern = '/(https:\/\/gist.github.com\/\w+\/\w+)/';

    public function format($html)
    {
        return preg_replace($this->pattern, '<script src="$0.js"></script>', $html);
    }
}

Remove URL from Gist embeds

Remove URL from Gist embeds

Reverts the commit from 30f1aa3 and removes the Github Gist URL from
appearing above the embedded gist.

The URLs are redundant as one could click the filename of the gist and
be taken to its page if they want.


<?php

namespace Rudolf\Modules\Plugins\Roll\Admin;

use Rudolf\Component\Plugins\Manager as PluginsManager;
use Rudolf\Framework\Model\BaseModel;

class Model extends BaseModel
{
    /**
     * Returns total number of modules items.
     *
     * @param array|string $where
     *
     * @return int
     */
    public function getTotalNumber()
    {
        return count($modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll()) - 1;
    }

    /**
     * Returns array with modules list.
     *
     * @return array
     */
    public function getList()
    {
        $modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll();

        $i = 1;
        foreach ($modules as $key => $value) {
            $array[] = [
                'id' => $i++,
                'name' => $value->getName(),
                'status' => $value->getStatus(),
            ];
        }

        return $array;
    }
}

<?php

namespace Rudolf\Modules\Plugins\Roll\Admin;

use Rudolf\Component\Plugins\Manager as PluginsManager;
use Rudolf\Framework\Model\BaseModel;

class Model extends BaseModel
{
    /**
     * Returns total number of modules items.
     *
     * @param array|string $where
     *
     * @return int
     */
    public function getTotalNumber()
    {
        return count($modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll());
    }

    /**
     * Returns array with modules list.
     *
     * @return array
     */
    public function getList()
    {
        $modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll();

        if (empty($modules)) {
            return false;
        }

        $i = 1;
        foreach ($modules as $key => $value) {
            $array[] = [
                'id' => $i++,
                'name' => $value->getName(),
                'status' => $value->getStatus(),
            ];
        }

        return $array;
    }
}

Fix erors when no plugins

Fix erors when no plugins


<?php
declare(strict_types=1);

namespace LotGD\Crate\GraphQL\AppBundle\Controller;

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

class GraphiQLController extends Controller {
    /**
     * Main controller action.$
     *
     * This method either displays a landing page informing the user that this is
     * a graphql interface or submits the query to the real controller that manages
     * graphql queries.
     * @Route("/")
     * @param Request $request
     * @return type
     */
    public function indexAction()
    {
        return $this->render(
            $this->getParameter('overblog_graphql.graphiql_template'),
            [
                'endpoint' => $this->generateUrl('lotgd_crate_www_app_graph_endpoint'),
                'versions' => [
                    'graphiql' => $this->getParameter('overblog_graphql.versions.graphiql'),
                    'react' => $this->getParameter('overblog_graphql.versions.react'),
                ],
            ]
        );
    }
}

<?php
declare(strict_types=1);

namespace LotGD\Crate\GraphQL\AppBundle\Controller;

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

class GraphiQLController extends Controller {
    /**
     * Main controller action.$
     *
     * This method either displays a landing page informing the user that this is
     * a graphql interface or submits the query to the real controller that manages
     * graphql queries.
     * @Route("/")
     * @param Request $request
     * @return type
     */
    public function indexAction()
    {
        return $this->render(
            $this->getParameter('overblog_graphql.graphiql_template'),
            [
                'endpoint' => $this->generateUrl('lotgd_crate_graphql_app_graph_endpoint'),
                'versions' => [
                    'graphiql' => $this->getParameter('overblog_graphql.versions.graphiql'),
                    'react' => $this->getParameter('overblog_graphql.versions.react'),
                ],
            ]
        );
    }
}

Fix endpoint url generation for graphiql


<?php namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;

class UpCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'up';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = "Bring the application out of maintenace mode";

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		@unlink($this->laravel['path.storage'].'/meta/down');

		$this->info('Application is now live.');
	}

}

<?php namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;

class UpCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'up';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = "Bring the application out of maintenance mode";

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		@unlink($this->laravel['path.storage'].'/meta/down');

		$this->info('Application is now live.');
	}

}

Fix a typo in Artisan command description.


<?php

	Configure::write('predictionIO', array(
		'appkey' => 'your-key',
		'userModel' => 'User',
		'engine' => ''
	));

	$files = array(
		App::pluginPath('PredictionIO') . 'vendor' . DS . 'autoload.php',
		APP . 'Vendor' . DS . 'autoload.php',
		APP . 'vendor' . DS . 'autoload.php',
	);

	foreach ($files as $file) {
		if (file_exists($file)) {
			require_once $file;
			break;
		}
	}

<?php

	Configure::write('predictionIO', array(
		'appkey' => 'your-key',
		'host' => 'localhost:8000',
		'userModel' => 'User',
		'engine' => ''
	));

	$files = array(
		App::pluginPath('PredictionIO') . 'vendor' . DS . 'autoload.php',
		APP . 'Vendor' . DS . 'autoload.php',
		APP . 'vendor' . DS . 'autoload.php',
	);

	foreach ($files as $file) {
		if (file_exists($file)) {
			require_once $file;
			break;
		}
	}

Add predictionIO api url to Config

Add predictionIO api url to Config


<?php

require "twilio-php-master/Services/Twilio.php";
require_once "config.php";

$mysqli = new mysqli($HOST, $USER, $PASSWORD, $DATABASE);
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);

$target = "ryan"; // temp set static target
if($_REQUEST['To'] == $US_NUMBER) {
    $outboundNumber = $FRENCH_NUMBER;
    $targetPhone = "french_phone";
} else if($_REQUEST['To'] == $FRENCH_NUMBER) {
    $outboundNumber = $US_NUMBER;
    $targetPhone = "us_phone";
} else {
    error_log("MSG received on unknown phone number. Number: ".$_REQUEST['To']);
    exit(1); //Kill the program if source can't be reliably confirmed
}

if($result = $mysqli->query("SELECT ".$targetPhone." FROM users WHERE handle=".$target)) {
    $obj = $result->fetch_object();
    $targetPhoneNumber = $obj[$targetPhone];
} else {
    echo $mysqli->error;
    error_log($mysqli->error);
}

try {
    $message = $client->account->messages->create(array(
        "From" => $outboundNumber,
        "To" => "+16785173393",
        "Body" => $_REQUEST['Body'],
    ));
} catch (Services_Twilio_RestException $e) {
    echo $e->getMessage();
    error_log($e->getMessage());
}

<?php

require "twilio-php-master/Services/Twilio.php";
require_once "config.php";

$mysqli = new mysqli($HOST, $USER, $PASSWORD, $DATABASE);
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);

$target = "ryan"; // temp set static target
if($_REQUEST['To'] == $US_NUMBER) {
    $outboundNumber = $FRENCH_NUMBER;
    $targetPhone = "french_phone";
} else if($_REQUEST['To'] == $FRENCH_NUMBER) {
    $outboundNumber = $US_NUMBER;
    $targetPhone = "us_phone";
} else {
    error_log("MSG received on unknown phone number. Number: ".$_REQUEST['To']. " Expected: ".$FRENCH_NUMBER );
    $mysqli->close();
    exit(1); //Kill the program if source can't be reliably confirmed
}

if($result = $mysqli->query("SELECT ".$targetPhone." FROM users WHERE handle=".$target)) {
    $obj = $result->fetch_object();
    $targetPhoneNumber = $obj[$targetPhone];
} else {
    echo $mysqli->error;
    error_log($mysqli->error);
}

$mysqli->close();

try {
    $message = $client->account->messages->create(array(
        "From" => $outboundNumber,
        "To" => "+16785173393",
        "Body" => $_REQUEST['Body'],
    ));
} catch (Services_Twilio_RestException $e) {
    echo $e->getMessage();
    error_log($e->getMessage());
}

Edit error message for better debugging

Edit error message for better debugging


<?php

namespace PhpParser\Node\Expr;

use PhpParser\Node\Expr;

/**
 * @property Expr $left  The left hand side expression
 * @property Expr $right The right hand side expression
 */
class BinaryOp extends Expr
{
    /**
     * Constructs a bitwise and node.
     *
     * @param Expr  $left       The left hand side expression
     * @param Expr  $right      The right hand side expression
     * @param array $attributes Additional attributes
     */
    public function __construct(Expr $left, Expr $right, array $attributes = array()) {
        parent::__construct(
            array(
                'left'  => $left,
                'right' => $right
            ),
            $attributes
        );
    }
}

<?php

namespace PhpParser\Node\Expr;

use PhpParser\Node\Expr;

/**
 * @property Expr $left  The left hand side expression
 * @property Expr $right The right hand side expression
 */
abstract class BinaryOp extends Expr
{
    /**
     * Constructs a bitwise and node.
     *
     * @param Expr  $left       The left hand side expression
     * @param Expr  $right      The right hand side expression
     * @param array $attributes Additional attributes
     */
    public function __construct(Expr $left, Expr $right, array $attributes = array()) {
        parent::__construct(
            array(
                'left'  => $left,
                'right' => $right
            ),
            $attributes
        );
    }
}

Make Node\Expr\BinOp an abstract class

Make Node\Expr\BinOp an abstract class

Only the children should be used ...


<?php

namespace Bolt\Nut;

use Bolt\Translation\Translator as Trans;
use Bolt\Version;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Nut command to output phpinfo().
 */
class Init extends BaseCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('init')
            ->setDescription('Greet the user (and perform initial setup tasks).')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $message = sprintf(
            "<info>%s</info> - %s <comment>%s</comment>.\n",
            Trans::__('nut.greeting'),
            Trans::__('nut.version'),
            Version::VERSION
        );
        $this->io->text($message);

        return 0;
    }
}

<?php

namespace Bolt\Nut;

use Bolt\Translation\Translator as Trans;
use Bolt\Version;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Nut command to perform initial setup tasks.
 */
class Init extends BaseCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('init')
            ->setDescription('Greet the user (and perform initial setup tasks).')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $this->updateDistBundles();
        } catch (\Exception $e) {
            if ($output instanceof Output && $output->isDebug()) {
                throw $e;
            }
            $this->io->error(sprintf('There was an exception when updating the distribution bundle: %s', $e->getMessage()));
        }

        $message = sprintf(
            "<info>%s</info> - %s <comment>%s</comment>.\n",
            Trans::__('nut.greeting'),
            Trans::__('nut.version'),
            Version::VERSION
        );
        $this->io->text($message);

        return 0;
    }

    /**
     * Archive distributions have the site bundle files installed as .dist
     * files to prevent the real files being overridden. If the .dist file
     * exists, but the original doesn't then we should rename them.
     */
    private function updateDistBundles()
    {
        $fs = $this->app['filesystem']->getFilesystem('root');
        $files = [
            'composer.json',
            'composer.lock',
            'src/Site/CustomisationExtension.php'
        ];
        foreach ($files as $file) {
            $dist = $fs->getFile($file . '.dist');
            if (!$fs->has($file) && $dist->exists()) {
                $dist->rename($file);
            }
        }
    }
}

Update `nut init` for archive distributions have the site bundle files installed as .dist


<?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class StorageCompilerPass
 * @package Tbbc\MoneyBundle\DependencyInjection\Compiler
 */
class StorageCompilerPass implements CompilerPassInterface
{
    /**
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        $storage = $container->getParameter('tbbc_money.pair.storage');

        //Determine if DoctrineBundle is defined
        if ('doctrine' === $storage) {
            if (!isset($bundles['DoctrineBundle'])) {
                throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
            }

            $storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
                new Reference('doctrine.orm.entity_manager'),
                $container->getParameter('tbbc_money.reference_currency'),
            ));

            $container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
            $container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
        }
    }
}

<?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class StorageCompilerPass
 * @package Tbbc\MoneyBundle\DependencyInjection\Compiler
 */
class StorageCompilerPass implements CompilerPassInterface
{
    /**
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        $storage = $container->getParameter('tbbc_money.pair.storage');

        //Determine if DoctrineBundle is defined
        if ('doctrine' === $storage) {
            if (!isset($bundles['DoctrineBundle'])) {
                throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
            }

            //Add doctrine schema mappings
            $modelDir = realpath(__DIR__.'/../../Resources/config/doctrine/ratios');
            $path = DoctrineOrmMappingsPass::createXmlMappingDriver(array(
                $modelDir => 'Tbbc\MoneyBundle\Entity',
            ));
            $path->process($container);

            $storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
                new Reference('doctrine.orm.entity_manager'),
                $container->getParameter('tbbc_money.reference_currency'),
            ));

            $container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
            $container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
        }
    }
}

Initialize doctrine models when storage is doctrine


@extends('templates.master')

@section('content')
    <form action="/login" method="POST">
        <input type="text" name="username" placeholder="Username">

        <input type="password" name="password" placeholder="Password">

        {{ csrf_field() }}
        <input type="submit" value="Login">
    </form>

    @if (count($errors) > 0)

                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach

    @endif
@stop

@extends('templates.master')

@section('content')
    <form action="/login" method="POST">
        <input type="text" name="username" placeholder="Username">

        <input type="password" name="password" placeholder="Password">

        <input type="text" name="2fa" placeholder="2 Factor Authen">

        {{ csrf_field() }}
        <input type="submit" value="Login">
    </form>

    @if (count($errors) > 0)

                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach

    @endif
@stop

Test add 2 Factor Token. (We should move this to a modal instead)


<?php

namespace GusApi\Util;

use GusApi\Type\Response\SearchDataResponse;
use GusApi\Type\Response\SearchResponseCompanyData;
use GusApi\Type\Response\SearchResponseRaw;

class DataSearchDecoder
{
    /**
     * @param SearchResponseRaw $searchResponseRaw
     *
     * @return SearchDataResponse
     */
    public static function decode(SearchResponseRaw $searchResponseRaw): SearchDataResponse
    {
        $elements = [];

        if (empty($searchResponseRaw->getDaneSzukajResult())) {
            return new SearchDataResponse($elements);
        }
        try {
            $xmlElementsResponse = new \SimpleXMLElement($searchResponseRaw->getDaneSzukajResult());

            foreach ($xmlElementsResponse->dane as $resultData) {
                $element = new SearchResponseCompanyData();
                foreach ($resultData as $key => $item) {
                    $element->$key = (string) $item;
                }
                $elements[] = $element;
            }
        } catch (\Exception $e) {
        }

        return new SearchDataResponse($elements);
    }
}

<?php

namespace GusApi\Util;

use GusApi\Type\Response\SearchDataResponse;
use GusApi\Type\Response\SearchResponseCompanyData;
use GusApi\Type\Response\SearchResponseRaw;

class DataSearchDecoder
{
    /**
     * @param SearchResponseRaw $searchResponseRaw
     *
     * @return SearchDataResponse
     */
    public static function decode(SearchResponseRaw $searchResponseRaw): SearchDataResponse
    {
        $elements = [];

        try {
            $xmlElementsResponse = new \SimpleXMLElement($searchResponseRaw->getDaneSzukajResult());

            foreach ($xmlElementsResponse->dane as $resultData) {
                $element = new SearchResponseCompanyData();
                foreach ($resultData as $key => $item) {
                    $element->$key = (string) $item;
                }
                $elements[] = $element;
            }
        } catch (\Exception $e) {
        }

        return new SearchDataResponse($elements);
    }
}

Change fixed value in to const

Change fixed value in to const


<?php

declare(strict_types=1);

namespace Rector\Core\Testing\ValueObject;

final class SplitLine
{
    /**
     * @var string
     */
    public const SPLIT_LINE = '#-----' . PHP_EOL . '#';
}

<?php

declare(strict_types=1);

namespace Rector\Core\Testing\ValueObject;

final class SplitLine
{
    /**
     * @var string
     */
    public const SPLIT_LINE = "#-----\r?\n#";
}

Fix regex to account for windows.

Fix regex to account for windows.

The fixtures files are all \n, so when the tests were run from windows none matched with PHP_EOL.
The new regex will match line endings of either OS.


<?php

namespace PhpAbac\Manager;

class DataManager {
    /** @var \PDO **/
    protected $connection;

    /**
     * @param \PDO $connection
     */
    public function __construct($connection) {
        $this->connection = $connection;
    }

    public function fetchQuery($query, $params) {
        $statement = $this->connection->prepare($query);
        $statement->execute($params);
        return $statement;
    }
}

<?php

namespace PhpAbac\Manager;

class DataManager {
    /** @var \PDO **/
    protected $connection;

    /**
     * @param \PDO $connection
     */
    public function __construct($connection) {
        $this->connection = $connection;
    }

    /**
     * @param string $query
     * @param array $params
     * @return \PDOStatement
     */
    public function fetchQuery($query, $params) {
        $statement = $this->connection->prepare($query);
        $statement->execute($params);
        return $statement;
    }

    /**
     * @param string $query
     * @param array $params
     * @return boolean
     */
    public function insertQuery($query, $params) {
        $statement = $this->connection->prepare($query);
        return $statement->execute($params);
    }
}

Add insert method to the data manager

Add insert method to the data manager


<?php

namespace Farmatholin\SegmentIoBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('segment_io');

        $rootNode
            ->children()
                ->scalarNode('write_key')
                    ->cannotBeEmpty()
                    ->isRequired()
                ->end()
                ->arrayNode('options')
                    ->children()
                        ->scalarNode('consumer')
                            ->defaultValue('socket')
                        ->end()
                        ->booleanNode('debug')
                            ->defaultFalse()
                        ->end()
                        ->booleanNode('ssl')
                            ->defaultFalse()
                        ->end()
                        ->integerNode('max_queue_size')
                            ->defaultValue(10000)
                        ->end()
                        ->integerNode('batch_size')
                            ->defaultValue(100)
                        ->end()
                        ->floatNode('timeout')
                            ->defaultValue(0.5)
                        ->end()
                    ->end()
                ->end()
            ->end()
            ;
        return $treeBuilder;
    }
}

<?php

namespace Farmatholin\SegmentIoBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('segment_io');

        $rootNode
            ->children()
                ->scalarNode('write_key')
                    ->cannotBeEmpty()
                    ->isRequired()
                ->end()
                ->arrayNode('options')
                    ->children()
                        ->scalarNode('consumer')
                            ->defaultValue('socket')
                        ->end()
                        ->booleanNode('debug')
                            ->defaultFalse()
                        ->end()
                        ->booleanNode('ssl')
                            ->defaultFalse()
                        ->end()
                        ->integerNode('max_queue_size')
                            ->defaultValue(10000)
                        ->end()
                        ->integerNode('batch_size')
                            ->defaultValue(100)
                        ->end()
                        ->floatNode('timeout')
                            ->defaultValue(0.5)
                        ->end()
                        ->scalarNode('filename')
                            ->defaultValue(null)
                        ->end()
                    ->end()
                ->end()
            ->end()
            ;
        return $treeBuilder;
    }
}

Add `filename` option to configuration tree


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */
namespace DocHeader\Filter;

/**
 * @author  Jefersson Nathan <malukenho@phpse.net>
 * @license MIT
 */
final class Filter
{
    /**
     * @var string
     */
    private $docheader;

    private $defaultFilters = [
        CurrentYear::class,
    ];

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

    /**
     * @return string
     */
    public function applyFilters()
    {
        array_map(
            function ($filterName) {
                $this->docheader = (new $filterName)->__invoke($this->docheader);
            },
            $this->defaultFilters
        );

        return $this->docheader;
    }
}

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */
namespace DocHeader\Filter;

/**
 * @author  Jefersson Nathan <malukenho@phpse.net>
 * @license MIT
 */
final class Filter
{
    /**
     * @var string
     */
    private $docheader;

    private $defaultFilters = [
        CurrentYear::class,
    ];

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

    /**
     * @return string
     */
    public function applyFilters()
    {
        $docheader = $this->docheader;

        foreach ($this->defaultFilters as $filterName) {
            $docheader = (new $filterName)->__invoke($docheader);
        }

        return $docheader;
    }
}

Change weird `array_map` by `foreach`

Change weird `array_map` by `foreach`


<?php

namespace tomzx\ProjectEuler;

use LogicException;

class Series
{
	/**
	 * @param int   $n  number of terms
	 * @param float $a1 first term value
	 * @param float $a2 last term value
	 * @return float
	 */
	public static function arithmetic($n, $a1, $a2)
	{
		if ($n < 0) {
			new LogicException('n cannot be negative.');
		}
		return $n * ($a1 * $a2) / 2;
	}

	/**
	 * @param float $r common ratio
	 * @param int   $n number of terms
	 * @param int   $a scale factor
	 * @return float
	 */
	public static function geometric($r, $n, $a = 1)
	{
		if ($r === 1) {
			new LogicException('r cannot be equal to 1.');
		}
		if ($n < 0) {
			new LogicException('n cannot be negative.');
		}
		return $a * (1 - pow($r, $n)) / (1 - $r);
	}
}

<?php

namespace tomzx\ProjectEuler;

use LogicException;

class Series
{
	/**
	 * @param int   $n  number of terms
	 * @param float $a1 first term value
	 * @param float $a2 last term value
	 * @return float
	 */
	public static function arithmetic($n, $a1, $a2)
	{
		if ($n < 0) {
			new LogicException('n cannot be negative.');
		}
		return $n * ($a1 + $a2) / 2;
	}

	/**
	 * @param float $r common ratio
	 * @param int   $n number of terms
	 * @param int   $a scale factor
	 * @return float
	 */
	public static function geometric($r, $n, $a = 1)
	{
		if ($r === 1) {
			new LogicException('r cannot be equal to 1.');
		}
		if ($n < 0) {
			new LogicException('n cannot be negative.');
		}
		return $a * (1 - pow($r, $n)) / (1 - $r);
	}
}

Fix an error in the formula used to calculate an arithmetic series.


<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

$error = NULL;
try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

openid: Fix notice about unititialized variable.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@3027 44740490-163a-0410-bde0-09ae8108e29a


<?php

/*
 * This file is part of Octower.
 *
 * (c) William Pottier <developer@william-pottier.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Octower\Command;

use Octower\Metadata\Project;
use Octower\Packager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class PackageCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('package:generate')
            ->setDescription('Create package to deploy')
            ->addOption('version', 'v', InputOption::VALUE_OPTIONAL)
            ->setHelp(<<<EOT
<info>php octower.phar package:generate</info>
EOT
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $octower = $this->getOctower();
        $io = $this->getIO();

        if ($input->hasOption('version')) {
            $context = $octower->getContext();
            if ($context instanceof Project) {
                $context->setVersion($input->getOption('version'));
            }
        }

        $packager = Packager::create($io, $octower);
        $packager->run();
    }
}

<?php

/*
 * This file is part of Octower.
 *
 * (c) William Pottier <developer@william-pottier.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Octower\Command;

use Octower\Metadata\Project;
use Octower\Packager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class PackageCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('package:generate')
            ->setDescription('Create package to deploy')
            ->addOption('version', null, InputOption::VALUE_OPTIONAL)
            ->setHelp(<<<EOT
<info>php octower.phar package:generate</info>
EOT
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $octower = $this->getOctower();
        $io = $this->getIO();

        if ($input->hasOption('version')) {
            $context = $octower->getContext();
            if ($context instanceof Project) {
                $context->setVersion($input->getOption('version'));
            }
        }

        $packager = Packager::create($io, $octower);
        $packager->run();
    }
}

Remove "v" shortcut (allready use for verbosity)


@extends('crudapi::layouts.master')

@section('content')

{{ $model }}<button class="btn btn-sm btn-success pull-right">Insert {{ $model }}</button>

        @foreach($fields as $f)
            {{ ucfirst($f) }}
        @endforeach
        Created At
        Updated At
        Actions

        @if(isset($items))
            @foreach($items as $item)

                @foreach($fields as $f)
                    {{ $item->$f }}
                @endforeach
                    {{ $item->created_at }}
                    {{ $item->updated_at }}
                    <button class="btn btn-xs btn-info">Edit</button> <button class="btn btn-xs btn-danger">Delete</button>

            @endforeach
        @endif

@stop

@extends('crudapi::layouts.master')

@section('content')

{{ $model }}<button class="btn btn-sm btn-success pull-right"> Insert {{ $model }}</button>

        @foreach($fields as $f)
            {{ ucfirst($f) }}
        @endforeach
        Created At
        Updated At
        Actions

        @if(isset($items))
            @foreach($items as $item)

                @foreach($fields as $f)
                    {{ $item->$f }}
                @endforeach
                    {{ $item->created_at }}
                    {{ $item->updated_at }}
                    <button class="btn btn-xs btn-info"> Edit</button> <button class="btn btn-xs btn-danger"> Delete</button>

            @endforeach
        @endif

@stop

Add FA icons to buttons

Add FA icons to buttons


<?php

add_action( 'init', 'create_project_posttype' );

function create_project_posttype() {
  register_post_type( 'project',
    array(
      'labels' => array(
        'name' => __( 'Projects' ),
        'singular_name' => __( 'Project' )
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'projects'),
    )
  );
}

<?php

add_action( 'init', 'create_project_posttype' );

function create_project_posttype() {
  register_post_type( 'project',
    array(
      'labels' => array(
        'name' => __( 'Projects' ),
        'singular_name' => __( 'Project' )
      ),
      'public' => true,
      'has_archive' => false,
      'rewrite' => array('slug' => 'projects'),
    )
  );
}

Fix project single view page

Fix project single view page


<?php
namespace Neos\Eel\Helper;

/*
 * This file is part of the Neos.Eel 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;
use Neos\Eel\ProtectedContextAwareInterface;

/**
 * JSON helpers for Eel contexts
 *
 * @Flow\Proxy(false)
 */
class JsonHelper implements ProtectedContextAwareInterface
{
    /**
     * JSON encode the given value
     *
     * @param mixed $value
     * @return string
     */
    public function stringify($value)
    {
        return json_encode($value);
    }

    /**
     * JSON decode the given string
     *
     * @param string $json
     * @param boolean $associativeArrays
     * @return mixed
     */
    public function parse($json, $associativeArrays = true)
    {
        return json_decode($json, $associativeArrays);
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}

<?php
namespace Neos\Eel\Helper;

/*
 * This file is part of the Neos.Eel 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;
use Neos\Eel\ProtectedContextAwareInterface;

/**
 * JSON helpers for Eel contexts
 *
 * @Flow\Proxy(false)
 */
class JsonHelper implements ProtectedContextAwareInterface
{
    /**
     * JSON encode the given value
     *
     * @param mixed $value
     * @param array $options Array of option constant names as strings
     * @return string
     */
    public function stringify($value, array $options = []): string
    {
        $optionSum = array_sum(array_map('constant', $options));
        return json_encode($value, $optionSum);
    }

    /**
     * JSON decode the given string
     *
     * @param string $json
     * @param boolean $associativeArrays
     * @return mixed
     */
    public function parse($json, $associativeArrays = true)
    {
        return json_decode($json, $associativeArrays);
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}

FEATURE: Add PHPs json_encode options to stringify eel helper


<?php

Requests::$transport = 'Requests_Transport_fsockopen';

class RequestsTest_Auth_Basic extends PHPUnit_Framework_TestCase {
	public static function transportProvider() {
		$transports = array(
			array('Requests_Transport_fsockopen'),
			array('Requests_Transport_cURL'),
		);
		return $transports;
	}

	/**
	 * @dataProvider transportProvider
	 */
	public function testUsingArray($transport) {
		$options = array(
			'auth' => array('user', 'passwd'),
			'transport' => $transport,
		);
		$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
		$this->assertEquals(200, $request->status_code);

		$result = json_decode($request->body);
		$this->assertEquals(true, $result->authenticated);
		$this->assertEquals('user', $result->user);
	}

	/**
	 * @dataProvider transportProvider
	 */
	public function testUsingInstantiation($transport) {
		$options = array(
			'auth' => new Requests_Auth_Basic(array('user', 'passwd')),
			'transport' => $transport,
		);
		$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
		$this->assertEquals(200, $request->status_code);

		$result = json_decode($request->body);
		$this->assertEquals(true, $result->authenticated);
		$this->assertEquals('user', $result->user);
	}
}

<?php

class RequestsTest_Auth_Basic extends PHPUnit_Framework_TestCase {
	public static function transportProvider() {
		$transports = array(
			array('Requests_Transport_fsockopen'),
			array('Requests_Transport_cURL'),
		);
		return $transports;
	}

	/**
	 * @dataProvider transportProvider
	 */
	public function testUsingArray($transport) {
		$options = array(
			'auth' => array('user', 'passwd'),
			'transport' => $transport,
		);
		$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
		$this->assertEquals(200, $request->status_code);

		$result = json_decode($request->body);
		$this->assertEquals(true, $result->authenticated);
		$this->assertEquals('user', $result->user);
	}

	/**
	 * @dataProvider transportProvider
	 */
	public function testUsingInstantiation($transport) {
		$options = array(
			'auth' => new Requests_Auth_Basic(array('user', 'passwd')),
			'transport' => $transport,
		);
		$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
		$this->assertEquals(200, $request->status_code);

		$result = json_decode($request->body);
		$this->assertEquals(true, $result->authenticated);
		$this->assertEquals('user', $result->user);
	}
}

Remove old transport forcing code from the basic auth test


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nos Bonbons</title>
  </head>
  <body>

<?php

 ?>

  </body>
</html>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nos Bonbons</title>
  </head>
  <body>

<?php include('header.php'): ?>
<?php include('footer.php'): ?>

  </body>
</html>

Add include for header and php

Add include for header and php


<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

/**
 * Class Kernel
 * @package App\Console
 */
class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {

        $schedule->command('eve:update-server-status')
            ->everyFiveMinutes()->withoutOverlapping();

        $schedule->command('eve:update-eve')
            ->daily()->withoutOverlapping();

        $schedule->command('eve:update-map')
            ->daily()->withoutOverlapping();
    }
}

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Seat\Services\Models\Schedule as DBSchedule;

/**
 * Class Kernel
 * @package App\Console
 */
class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {

        // Load the schedule from the database
        foreach (DBSchedule::all() as $job) {

            $command = $schedule->command($job['command'])
                ->cron($job['expression']);

            // Check if overlapping is allowed
            if (!$job['allow_overlap'])
                $command = $command->withoutOverlapping();

            // Check if maintenance mode is allowed
            if ($job['allow_maintenance'])
                $command = $command->evenInMaintenanceMode();

            if ($job['ping_before'])
                $command = $command->pingBefore($job['ping_before']);

            if ($job['ping_after'])
                $command->thenPing($job['ping_after']);

        }
    }
}

Load command schedules from the DB

Load command schedules from the DB


<?php
/**
 * Copyright (c) 2016 RhubarbPHP.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Rhubarb\Leaf\Controls\Common\Text;

class NumericTextBoxModel extends TextBoxModel
{
    /**
     * The number of decimal places to display
     * @var int
     */
    public $decimalPlaces = 2;
}

<?php
/**
 * Copyright (c) 2016 RhubarbPHP.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Rhubarb\Leaf\Controls\Common\Text;

class NumericTextBoxModel extends TextBoxModel
{
    public $inputType = 'tel';

    /**
     * The number of decimal places to display
     * @var int
     */
    public $decimalPlaces = 2;
}

Set numeric textbox to use "tel" type so it gives a numeric textpad on mobile without showing up/down arrows in chrome


<?php
$userMap = true;

Configure::write('Session', Hash::merge(
	Configure::read('Session'),
	array(
		'defaults' => 'php',
		'handler' => array(
			'engine' => 'RedisSession.RedisSession',
			'userMap' => $userMap,
			//'userMapPrefix' => 'USERS',
			//'userMapField' => 'id',
			//'prefix' => 'PHPREDIS_SESSION',
			//'host' => 'localhost',
			//'port' => '6379',
			//'db' => 0,
		),
	)
));

if ($userMap) {
	if (extension_loaded('wddx')) {
		ini_set('session.serialize_handler', 'wddx');
	} else {
		CakeLog::critical('wddx not available. user map not enabled');
	}
}

<?php

$handlerConfig = Hash::merge(array(
	'engine' => 'RedisSession.RedisSession',
	'userMap' => true,
), Configure::consume('RedisSession.handler'));

Configure::write('Session', Hash::merge(
	Configure::read('Session'),
	array(
		'defaults' => 'php',
		'handler' => $handlerConfig,
	)
));

if (isset($handlerConfig['userMap'])) {
	if (extension_loaded('wddx')) {
		ini_set('session.serialize_handler', 'wddx');
	} else {
		CakeLog::critical('wddx not available. user map not enabled');
	}
}

Make it easier to load config set by app/other plugin


<?php declare(strict_types = 1);

namespace Contributte\ReCaptcha\Forms;

use Contributte\ReCaptcha\ReCaptchaProvider;
use Nette\Forms\Container;

final class InvisibleReCaptchaBinding
{

	public static function bind(ReCaptchaProvider $provider, string $name = 'addInvisibleReCaptcha'): void
	{
		// Bind to form container

		Container::extensionMethod($name, function (Container $container, string $name = 'recaptcha', bool $required = true) use ($provider): InvisibleReCaptchaField {
			$field = new InvisibleReCaptchaField($provider);
			$field->setRequired($required);
			$container[$name] = $field;

			return $field;
		});
	}

}

<?php declare(strict_types = 1);

namespace Contributte\ReCaptcha\Forms;

use Contributte\ReCaptcha\ReCaptchaProvider;
use Nette\Forms\Container;

final class InvisibleReCaptchaBinding
{

	public static function bind(ReCaptchaProvider $provider, string $name = 'addInvisibleReCaptcha'): void
	{
		// Bind to form container
		Container::extensionMethod($name, function (Container $container, string $name = 'recaptcha', bool $required = true, ?string $message = null) use ($provider): InvisibleReCaptchaField {
			$field = new InvisibleReCaptchaField($provider, $message);
			$field->setRequired($required);
			$container[$name] = $field;

			return $field;
		});
	}

}

Fix setting of message via field's constructor


<?php

declare(strict_types=1);

namespace Arcanedev\Localization\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Class     LocaleCookieRedirect
 *
 * @package  Arcanedev\Localization\Middleware
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class LocaleCookieRedirect extends Middleware
{
    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure                  $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // If the request URL is ignored from localization.
        if ($this->shouldIgnore($request) || class_basename($next($request)) === 'StreamedResponse') return $next($request);

        $segment = $request->segment(1, null);

        if ($this->localization->isLocaleSupported($segment))
            return $next($request)->withCookie(cookie()->forever('locale', $segment));

        $locale  = $request->cookie('locale', null);

        if ($locale !== null && ! $this->isDefaultLocaleHidden($locale)) {
            if ( ! is_null($redirect = $this->getLocalizedRedirect($locale)))
                return $redirect->withCookie(cookie()->forever('locale', $segment));
        }

        return $next($request);
    }
}

<?php

declare(strict_types=1);

namespace Arcanedev\Localization\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Class     LocaleCookieRedirect
 *
 * @package  Arcanedev\Localization\Middleware
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class LocaleCookieRedirect extends Middleware
{
    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure                  $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // If the request URL is ignored from localization.
        if ($this->shouldIgnore($request) || $next($request) instanceof StreamedResponse) return $next($request);

        $segment = $request->segment(1, null);

        if ($this->localization->isLocaleSupported($segment))
            return $next($request)->withCookie(cookie()->forever('locale', $segment));

        $locale  = $request->cookie('locale', null);

        if ($locale !== null && ! $this->isDefaultLocaleHidden($locale)) {
            if ( ! is_null($redirect = $this->getLocalizedRedirect($locale)))
                return $redirect->withCookie(cookie()->forever('locale', $segment));
        }

        return $next($request);
    }
}

Use instanceof instead of class_basename