#!/usr/local/bin/php -f
<?php
	/* upgrade embedded users serial console */
	require_once("globals.inc");
	require_once("functions.inc");
	require_once("config.inc");
	if($g['platform'] == "embedded") {
		$config['system']['enableserial'] = true;
		write_config();
	}
	setup_serial_port();
	if(file_exists("/usr/local/www/index.html"))
		unlink("/usr/local/www/index.html");
	if(file_exists("/usr/local/www/fred.png"))
		unlink("/usr/local/www/fred.png");
	if(file_exists("/usr/local/www/dfuife.cgi"))
		unlink("/usr/local/www/dfuife.cgi");

	if($g['platform'] == "pfSense")
		touch("/conf/needs_package_sync");

?>

#!/usr/local/bin/php -f
<?php
	/* upgrade embedded users serial console */
	require_once("globals.inc");
	require_once("functions.inc");
	require_once("config.inc");
	if($g['platform'] == "embedded") {
		$config['system']['enableserial'] = true;
		write_config();
	}
	setup_serial_port();
	if(file_exists("/usr/local/www/index.html"))
		unlink("/usr/local/www/index.html");
	if(file_exists("/usr/local/www/fred.png"))
		unlink("/usr/local/www/fred.png");
	if(file_exists("/usr/local/www/dfuife.cgi"))
		unlink("/usr/local/www/dfuife.cgi");

	if($g['platform'] == "pfSense")
		touch("/conf/needs_package_sync");

	$files_to_process = split("\n", file_get_contents("/etc/pfSense.obsoletedfiles"));
	foreach($files_to_process as $filename)
		if(file_exists($filename))
			exec("rm $filename");

?>

Remove obsoleted files after upgrade

Remove obsoleted files after upgrade


<?php

namespace Mdd\QueryBuilder\Conditions;

use Mdd\QueryBuilder\Condition;

abstract class AbstractCondition implements Condition
{
    public function _and(Condition $condition)
    {
        return new Binaries\AndCondition($this, $condition);
    }

    public function _or(Condition $condition)
    {
        return new Binaries\OrCondition($this, $condition);
    }

    public function __call($methodName, $arguments)
    {
        $method = '_' . $methodName;

        if(method_exists($this, $method))
        {
            if(array_key_exists(0, $arguments))
            {
                return $this->$method($arguments[0]);
            }
        }

        throw new \RuntimeException(sprintf("Unkown method %s", $method));
    }
}

<?php

namespace Mdd\QueryBuilder\Conditions;

use Mdd\QueryBuilder\Condition;

abstract class AbstractCondition implements Condition
{
    public function _and(Condition $condition)
    {
        return new Binaries\AndCondition($this, $condition);
    }

    public function _or(Condition $condition)
    {
        return new Binaries\OrCondition($this, $condition);
    }

    public function __call($methodName, $arguments)
    {
        $method = '_' . $methodName;

        if(method_exists($this, $method))
        {
            if(array_key_exists(0, $arguments))
            {
                return $this->$method($arguments[0]);
            }
        }

        throw new \LogicException(sprintf("Unkown method %s", $method));
    }
}

Change exception thrown for calling unsupported helper method


<?php

namespace jorenvanhocht\Blogify\Controllers\Admin;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class Controller extends BaseController {

    use DispatchesCommands, ValidatesRequests;

}

<?php

namespace jorenvanhocht\Blogify\Controllers\Admin;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

class Controller extends BaseController
{
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

Update base controller to laravel 5.2

Update base controller to laravel 5.2


<?php

namespace Sellsy\Models\Catalogue;

/**
 * Class Item
 * @package Sellsy\Models\Catalogue
 */
class Item
{
    /**
     * @var int
     * @copy
     */
    public $id;

    /**
     * @var boolean
     * @copy actif
     * @convert boolean
     */
    public $isActive;

    /**
     * @var boolean
     * @copy
     * @convert boolean
     */
    public $isEnabled;

    /**
     * @var string
     * @copy
     */
    public $name;

    /**
     * @var string
     * @copy
     */
    public $tradename;
}

<?php

namespace Sellsy\Models\Catalogue;

use Sellsy\Models\CustomFields\CustomFieldTrait;

/**
 * Class Item
 * @package Sellsy\Models\Catalogue
 */
class Item
{
    use CustomFieldTrait;

    /**
     * @var int
     * @copy
     */
    public $id;

    /**
     * @var boolean
     * @copy actif
     * @convert boolean
     */
    public $isActive;

    /**
     * @var boolean
     * @copy
     * @convert boolean
     */
    public $isEnabled;

    /**
     * @var string
     * @copy
     */
    public $name;

    /**
     * @var string
     * @copy
     */
    public $tradename;
}

Add custom fields to catalogue item

Add custom fields to catalogue item


<?php
namespace gilek\gtreetable;

use yii\web\AssetBundle;

class GTreeTableAsset extends AssetBundle {
    /**
     * @inheritdoc
     */
    public $sourcePath = '@gilek/gtreetable/gtreetable';

    /**
     * @inheritdoc
     */
    public $jsOptions = [
        'position' => \yii\web\View::POS_HEAD
    ];

    /**
     * @inheritdoc
     */
    public $depends = [
        'yii\web\JqueryAsset',
        'yii\jui\JuiAsset.php',
    ];

    public $publishOptions = [
        'forceCopy' => YII_ENV_DEV
    ];

    public $language;

    public $draggable = false;

    public $minSuffix = '.min';

    public function registerAssetFiles($view)
    {
        if ($this->draggable === true) {
            $this->js[] = 'jquery.browser.js';
        }

        $this->js[] = 'bootstrap-gtreetable'.(YII_ENV_DEV ? '' : $this->minSuffix).'.js';
        $this->css[] = 'gtreetable'.(YII_ENV_DEV ? '' : $this->minSuffix).'.css';

        if ($this->language !== null) {
            $this->js[] = 'languages/bootstrap-gtreetable.'.$this->language. (YII_ENV_DEV ? '' : '.'.$this->minSuffix). '.js';
        }

        parent::registerAssetFiles($view);
    }
}

<?php
namespace gilek\gtreetable;

use yii\web\AssetBundle;

class GTreeTableAsset extends AssetBundle {
    /**
     * @inheritdoc
     */
    public $sourcePath = '@gilek/gtreetable/gtreetable';

    /**
     * @inheritdoc
     */
    public $jsOptions = [
        'position' => \yii\web\View::POS_HEAD
    ];

    /**
     * @inheritdoc
     */
    public $depends = [
        'yii\web\JqueryAsset',
        'yii\jui\JuiAsset',
    ];

    public $publishOptions = [
        'forceCopy' => YII_ENV_DEV
    ];

    public $language;

    public $draggable = false;

    public $minSuffix = '.min';

    public function registerAssetFiles($view)
    {
        if ($this->draggable === true) {
            $this->js[] = 'jquery.browser.js';
        }

        $this->js[] = 'bootstrap-gtreetable'.(YII_ENV_DEV ? '' : $this->minSuffix).'.js';
        $this->css[] = 'gtreetable'.(YII_ENV_DEV ? '' : $this->minSuffix).'.css';

        if ($this->language !== null) {
            $this->js[] = 'languages/bootstrap-gtreetable.'.$this->language. (YII_ENV_DEV ? '' : '.'.$this->minSuffix). '.js';
        }

        parent::registerAssetFiles($view);
    }
}

Prepare for Yii2 2.0 RC

Prepare for Yii2 2.0 RC


<?php
namespace Avatar;
class UploadLogFormatter extends \LogFormatter {

	public function getActionLinks() {
		$user = $this->entry->getPerformer();
		$view = \Linker::linkKnown(
			\SpecialPage::getTitleFor('ViewAvatar'),
			$this->msg('logentry-avatar-action-view')->escaped(),
			array(),
			array(
				'user' => $user->getName(),
			)
		);
		return $this->msg('parentheses')->rawParams($view)->escaped();

	}

}

<?php
namespace Avatar;

use MediaWiki\MediaWikiServices;

class UploadLogFormatter extends \LogFormatter {

	public function getActionLinks() {
		$user = $this->entry->getPerformer();
		$view = MediaWikiServices::getInstance()->getLinkRenderer()
			->makeKnownLink(\SpecialPage::getTitleFor('ViewAvatar'),
				$this->msg('logentry-avatar-action-view')->escaped(),
				[],
				['user' => $user->getName()]
			);
		return $this->msg('parentheses')->rawParams($view)->escaped();

	}

}

Use LinkRenderer::getLinkRenderer() instead of Linker::linkKnown()

Linker::linkKnown() has deprecated since 1.28.


<?php
class RelatedFileForm extends BaseForm
{
  public function configure()
  {
    $this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
    $this->widgetSchema['filenames']->setLabel("Add File") ;
    $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
    $this->validatorSchema['filenames'] = new sfValidatorFile(
      array(
          'required' => false,
          //'mime_type_guessers' => array('guessFromFileinfo'),
          'validated_file_class' => 'myValidatedFile'
      ));
    $this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
    array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
    array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
    array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
  ));
  }

}

<?php
class RelatedFileForm extends BaseForm
{
  public function configure()
  {
    $this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
    $this->widgetSchema['filenames']->setLabel("Add File") ;
    $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
    $this->validatorSchema['filenames'] = new sfValidatorFile(
      array(
          'required' => true,
          //'mime_type_guessers' => array('guessFromFileinfo'),
          'validated_file_class' => 'myValidatedFile'
      ));
    $this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
    array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
    array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
    array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
  ));
  }

}

Set required in files related

Set required in files related


<?php

// -----------------------------------------------------------------------------------------------------------
// Pokemons datas
// Total pokemon available
// -----------------------------------------------------------------------------------------------------------

// This file is used to rank by rarity

// Load the pokemons array
// will load english one because language is not set
############################

include_once($filePath.'/../process/locales.loader.php');

$pokemon_stats['timestamp'] = $timestamp;

$req 		= "SELECT COUNT(*) as total FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result 	= $mysqli->query($req);
$data 		= $result->fetch_object();

$pokemon_stats['pokemon_now'] 	= $data->total;

$req 		= "SELECT pokemon_id FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result 	= $mysqli->query($req);

$rarityarray = array();
while ($data = $result->fetch_object()) {
	$poke_id 	= $data->pokemon_id;
	$rarity 	= $pokemons->pokemon->$poke_id->rarity;

	isset($rarityarray[$rarity]) ? $rarityarray[$rarity]++ : $rarityarray[$rarity] = 1;
}
$pokemon_stats['rarity_spawn'] = $rarityarray;

// Add the datas in file

$pokedatas[] 	= $pokemon_stats;
$json 		= json_encode($pokedatas);

file_put_contents($pokemonstats_file, $json);

<?php

// -----------------------------------------------------------------------------------------------------------
// Pokemons datas
// Total pokemon available
// -----------------------------------------------------------------------------------------------------------

// This file is used to rank by rarity

// Load the pokemons array
// force english language
$config->system->forced_lang = 'en';
include_once($filePath.'/../process/locales.loader.php');

$pokemon_stats['timestamp'] = $timestamp;

$req 		= "SELECT COUNT(*) as total FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result 	= $mysqli->query($req);
$data 		= $result->fetch_object();

$pokemon_stats['pokemon_now'] 	= $data->total;

$req 		= "SELECT pokemon_id FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result 	= $mysqli->query($req);

$rarityarray = array();
while ($data = $result->fetch_object()) {
	$poke_id 	= $data->pokemon_id;
	$rarity 	= $pokemons->pokemon->$poke_id->rarity;

	isset($rarityarray[$rarity]) ? $rarityarray[$rarity]++ : $rarityarray[$rarity] = 1;
}
$pokemon_stats['rarity_spawn'] = $rarityarray;

// Add the datas in file

$pokedatas[] 	= $pokemon_stats;
$json 		= json_encode($pokedatas);

file_put_contents($pokemonstats_file, $json);

Fix stats files language issues - If you used forced_lang stats files were in this language which is bad. - Force english!


<?php

namespace Oro\Bundle\SearchBundle;

use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\FilterTypesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass;
use Oro\Component\DependencyInjection\ExtendedContainerBuilder;

class OroSearchBundle extends Bundle
{
    /** {@inheritdoc} */
    public function build(ContainerBuilder $container)
    {
        if ($container instanceof ExtendedContainerBuilder) {
            $container->addCompilerPass(new ListenerExcludeSearchConnectionPass());
            $container->moveCompilerPassBefore(
                'Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass',
                'Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\UpdateDoctrineEventHandlersPass'
            );
        }

        $container->addCompilerPass(new FilterTypesPass());
    }
}

<?php

namespace Oro\Bundle\SearchBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\FilterTypesPass;
use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass;
use Oro\Component\DependencyInjection\ExtendedContainerBuilder;

class OroSearchBundle extends Bundle
{
    /** {@inheritdoc} */
    public function build(ContainerBuilder $container)
    {
        if ($container instanceof ExtendedContainerBuilder) {
            $container->addCompilerPass(new ListenerExcludeSearchConnectionPass());
            $container->moveCompilerPassBefore(
                'Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass',
                'Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\UpdateDoctrineEventHandlersPass'
            );
        }

        $container->addCompilerPass(new FilterTypesPass());
    }
}

BB-4056: Add or adjust implementation of the SKU filters from the grid. Both use StringFilter in the ORM version
- namespace fix


<?php
error_reporting(E_ALL & ~E_NOTICE);
foreach (glob("functions/*.php") as $filename) {
  include $filename;
}

if ( isset($_GET['host']) && !empty($_GET['host'])) {
  $data = [];
  $hostname = mb_strtolower(get($_GET['host']));
  $host = parse_hostname($hostname);
  if ($host['port']) {
    $port = $host['port'];
  } else {
    $port = get($_GET['port'], '443');
  }
  $host = $host['hostname'];
  if ( !is_numeric($port) ) {
    $port = 443;
  }
  $data["data"] = check_json($host,$port);

} elseif(isset($_GET['csr']) && !empty($_GET['csr'])) {
  $data["data"]["chain"]["1"] = csr_parse_json($_GET['csr']);

} else {
  $data["error"] = ["Host is required"];

}

$data = utf8encodeNestedArray($data);

if(isset($data["data"]["error"])) {
  $data["error"] = $data["data"]["error"];
  unset($data["data"]);
}

if ($_GET["type"] == "pretty") {
  header('Content-Type: text/html');
  echo "<pre>";
  echo htmlspecialchars(json_encode($data,JSON_PRETTY_PRINT));
  echo "</pre>";
  ?>

  <?
} else {
  header('Content-Type: application/json');
  echo json_encode($data);
}

?>

<?php
error_reporting(E_ALL & ~E_NOTICE);
foreach (glob("functions/*.php") as $filename) {
  include $filename;
}

if ( isset($_GET['host']) && !empty($_GET['host'])) {
  $data = [];
  $hostname = mb_strtolower(get($_GET['host']));
  $host = parse_hostname($hostname);
  if ($host['port']) {
    $port = $host['port'];
  } else {
    $port = get($_GET['port'], '443');
  }
  $host = $host['hostname'];
  if ( !is_numeric($port) ) {
    $port = 443;
  }
  $data["data"] = check_json($host,$port);

} elseif(isset($_GET['csr']) && !empty($_GET['csr'])) {
  $data["data"]["chain"]["1"] = csr_parse_json($_GET['csr']);

} else {
  $data["error"] = ["Host is required"];

}

$data = utf8encodeNestedArray($data);

if(isset($data["data"]["error"])) {
  $data["error"] = $data["data"]["error"];
  unset($data["data"]);
}

if ($_GET["type"] == "pretty") {
  header('Content-Type: text/html');
  echo "<pre>";
  echo htmlspecialchars(json_encode($data,JSON_PRETTY_PRINT));
  echo "</pre>";
} else {
  header('Content-Type: application/json');
  echo json_encode($data);
}

?>

Remove unused php open and close tags

Remove unused php open and close tags


<?php
/**
 * @copyright Copyright © A.F.Schuurman, 2015
 * @package yii2-add-to-homescreen
 * @subpackage yii2-widget-switchinput
 * @version 1.0.0
 */

namespace AddToHomescreen;

use yii\web\AssetBundle;

/**
 * Asset bundle for Add-to-homescreen
 *
 * @author A.F.Schuurman <andre.schuurman+yii2-add-to-homescreen@gmail.com>
 * @since 1.0
 */
class AddToHomescreenAsset extends AssetBundle
{
	public $sourcePath = '@bower/add-to-homescreen';
	public $css = [
		'style/addtohomescreen.css',
	];
	public function init() {
		// In dev mode use non-minified javascripts
		$this->js = YII_DEBUG ? [
			'addtohomescreen.js',
		]:[
			'addtohomescreen.min.js',
		];

		parent::init();
	}
}

<?php
/**
 * @copyright Copyright © A.F.Schuurman, 2015
 * @package yii2-add-to-homescreen
 * @subpackage yii2-widget-switchinput
 * @version 1.0.0
 */

namespace AddToHomescreen;

use yii\web\AssetBundle;

/**
 * Asset bundle for Add-to-homescreen
 *
 * @author A.F.Schuurman <andre.schuurman+yii2-add-to-homescreen@gmail.com>
 * @since 1.0
 */
class AddToHomescreenAsset extends AssetBundle
{
	public $sourcePath = '@bower/add-to-homescreen';
	public $css = [
		'style/addtohomescreen.css',
	];
	public function init() {
		// In dev mode use non-minified javascripts
		$this->js = YII_DEBUG ? [
			'src/addtohomescreen.js',
		]:[
			'src/addtohomescreen.min.js',
		];

		parent::init();
	}
}

Fix javascript new directory location (src).


<?php

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

namespace Sylius\Component\Shipping\Model;

use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ShippingCategoryInterface extends CodeAwareInterface, TimestampableInterface, ResourceInterface
{
    /**
     * @return mixed
     */
    public function getId();

    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);
}

[TaxationBundle] Add event subscriber AddCodeFormSubscriber to TaxRateType and TaxCategoryType
[TaxationBundle] Add validation  for filed 'code' from TaxRate and TaxCategory
[Taxation] Add field 'code' to TaxCategory and TaxRate, TaxCategoryInterface and TaxRateInterface extend AwareCodeInterface
[WebBundle] Add code filed to TaxCategory views and to TaxRate views


<?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",
                    0,
                    $e
                );
            }

        }
    }
}

<?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 = data_get($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",
                    0,
                    $e
                );
            }

        }
    }
}

Handle a non-existent field in an array

Handle a non-existent field in an array

This was giving me an error, since I had several records for which a particular field was not defined.  Since I use a schema-less DB (MongoDB), this field doesn't even exist with a null value.  `data_get` performs an `array_key_exists` check before attempting to use `$part` as an index for the `$res` array.

This entire method could actually be replaced with data_get for simplicity, since this is what Laravel uses internally to retrieve values in dot notation.
```php
protected function extractCellValue($fieldName)
{
    try {
        return data_get($this->src, $fieldName);
    } catch (Exception $e) {
        throw new RuntimeException(
            "Can't read '$fieldName' property from DataRow",
            0,
            $e
        );
    }
}
```


<?php

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

// Throw an exception when E_ERRORS occur to better debug the problem
function throwExceptionOnError($severity, $message, $file, $line) {
    $errMessage = sprintf('Language error ("%s") thrown from %s:%s', $message, $file, $line);

    throw new \Exception($errMessage, $severity);
}

set_error_handler('throwExceptionOnError');

Convert E_ERRORS into exceptions in unit tests


<?php

namespace Tyrell;

use Tonic\Resource,
    Tonic\Response,
    Tonic\UnauthorizedException;

/**
 * Simple HTTP authentication example.
 *
 * The condition annotation @secure maps to the secure() method allowing us to easily
 * secure the mySecret() method with the given username and password
 *
 * @uri /secret
 */
class Secret extends Resource {

    /**
     * @method GET
     * @secure aUser aPassword
     */
    function mySecret() {
        return 'My secret';
    }

    function secure($username, $password) {
        if (
            isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == $username &&
            isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] == $password
        ) {
            return;
        }
        #return new Response(401, 'No entry', array('wwwAuthenticate' => 'Basic realm="My Realm"'));
        throw new UnauthorizedException('No entry');
    }
}

<?php

namespace Tyrell;

use Tonic\Resource,
    Tonic\Response,
    Tonic\UnauthorizedException;

/**
 * Simple HTTP authentication example.
 *
 * The condition annotation @secure maps to the secure() method allowing us to easily
 * secure the mySecret() method with the given username and password
 *
 * @uri /secret
 */
class Secret extends Resource {

    /**
     * Resource method to handle GET request and return the secret only if the user
     * has the credentials specified in the @secure annotation.
     *
     * @method GET
     * @secure aUser aPassword
     * @return str
     */
    function mySecret() {
        return 'My secret';
    }

    /**
     * Condition method for the @secure annotation that checks the requests HTTP
     * authentication details against the username and password given in the annotation.
     *
     * @param str $username
     * @param str $password
     * @throws UnauthorizedException
     */
    function secure($username, $password) {
        if (
            isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == $username &&
            isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] == $password
        ) {
            return;
        }
        #return new Response(401, 'No entry', array('wwwAuthenticate' => 'Basic realm="My Realm"'));
        throw new UnauthorizedException('No entry');
    }
}

Add comments to auth example

Add comments to auth example


<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, [
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, array(
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

Update Sami theme as default.

Update Sami theme as default.


<?php

return array(

	'path' => '/database/seeds',
    'chunk_size' => 200 // Maximum number of rows per insert statement

);

<?php

return array(

	'path' => '/database/seeds',
    'chunk_size' => 500 // Maximum number of rows per insert statement

);

Set the default chunk size back to 500.

Set the default chunk size back to 500.


<?php
/**
 * Tests for amp.php.
 *
 * @package AMP
 */

/**
 * Tests for amp.php.
 */
class Test_AMP extends WP_UnitTestCase {

	/**
	 * Tear down and clean up.
	 */
	public function tearDown() {
		parent::tearDown();
		remove_theme_support( 'amp' );
	}

	/**
	 * Test amp_is_canonical().
	 *
	 * @covers amp_is_canonical()
	 */
	public function test_amp_is_canonical() {
		remove_theme_support( 'amp' );
		$this->assertFalse( amp_is_canonical() );

		add_theme_support( 'amp' );
		$this->assertTrue( amp_is_canonical() );

		remove_theme_support( 'amp' );
		add_theme_support( 'amp', array(
			'template_path' => get_template_directory() . 'amp-templates/',
		) );
		$this->assertFalse( amp_is_canonical() );

		remove_theme_support( 'amp' );
		add_theme_support( 'amp', array(
			'custom_prop' => 'something',
		) );
		$this->assertTrue( amp_is_canonical() );
	}
}

<?php
/**
 * Tests for amp.php.
 *
 * @package AMP
 */

/**
 * Tests for amp.php.
 */
class Test_AMP extends WP_UnitTestCase {

	/**
	 * Tear down and clean up.
	 */
	public function tearDown() {
		parent::tearDown();
		remove_theme_support( 'amp' );
	}

	/**
	 * Test amp_is_canonical().
	 *
	 * @covers amp_is_canonical()
	 */
	public function test_amp_is_canonical() {
		remove_theme_support( 'amp' );
		$this->assertFalse( amp_is_canonical() );

		add_theme_support( 'amp' );
		$this->assertTrue( amp_is_canonical() );

		remove_theme_support( 'amp' );
		add_theme_support( 'amp', array(
			'template_dir' => 'amp-templates',
		) );
		$this->assertFalse( amp_is_canonical() );

		remove_theme_support( 'amp' );
		add_theme_support( 'amp', array(
			'custom_prop' => 'something',
		) );
		$this->assertTrue( amp_is_canonical() );
	}
}

Update test_amp_is_canonical() with new naming.


<?php

namespace Spec\Runner\Cli\Files;

class DescribeFoo extends \PHPSpec\Context
{
    function itDoesSomething()
    {

    }
}

<?php

namespace Spec\Runner\Cli\Files;

class DescribeFoo extends \PHPSpec\Context
{
    function itDoesSomething()
    {
        // Text to keep Reporter mock from failing
    }
}

Add comment to empty test to keep the mock from crashing


@extends('layouts.main')

@section('title')
  Payment
@endsection

@section('breadcrumb')

Shop

Cart

Checkout

Pay

@endsection

@section('content')

Pay

Order Details

    @include('orders._summary')

    <form action="" id="pay-now-form" class="row">

            <button type="submit" class="btn btn-success btn-lg btn-block">Pay now</button>

    </form>
@stop

@section('scripts')

@stop

Use ES5 function syntax in script

Use ES5 function syntax in script


<?php
namespace QuickBooksOnline\API\Core\Configuration;

/**
* Base Urls for QBO, QBD and IPP
* -----------------
* Remove QBD part from this and the sdk.config File
* Feb.7th.2017 @Hao
* -----------------
*/
class BaseUrl
{
    /**
     * Gets or sets the url for QuickBooks Online Rest Service.
     * @var string
     */
    public $Qbo;

    /**
     * Gets or sets the url for Platform Rest Service.
     * @var string
     */
    public $Ipp;

    /**
     * Initializes a new instance of the BaseUrl class.
     *
     * @param string $Qbo url for QuickBooks Online Rest Service
     * @param string $Ipp url for Platform Rest Service
     */
    public function __construct($Qbo=null, $Ipp=null)
    {
        $this->Qbo=$Qbo;
        $this->Ipp=$Ipp;
    }
}

<?php
namespace QuickBooksOnline\API\Core\Configuration;

/**
* Base Urls for QBO, QBD and IPP
* -----------------
* Remove QBD part from this and the sdk.config File
* Feb.7th.2017 @Hao
* -----------------
*/
class BaseUrl
{
    /**
     * Gets or sets the url for QuickBooks Online Rest Service.
     * @var string
     */
    public $Qbo;

    /**
     * Gets or sets the url for Platform Rest Service.
     * @var string
     */
    public $Ipp;

    /**
     * Initializes a new instance of the BaseUrl class.
     *
     * @param string $Qbo url for QuickBooks Online Rest Service
     * @param string $Ipp url for Platform Rest Service
     */
    public function __construct($Qbo=null, $Ipp=null)
    {
        $this->Qbo=$Qbo;
        if(isset($Ipp))
        {
          $this->Ipp = $Ipp;
        }else {
          $this->Ipp = "https://appcenter.intuit.com/api/";
        }
    }
}

Set the default IPP URI

Set the default IPP URI


<?php

namespace ProcessWire\GraphQL\Field\Page;

use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Execution\ResolveInfo;
use ProcessWire\GraphQL\Type\Object\PageType as PageObjectType;
use ProcessWire\NullPage;

class PageParentField extends AbstractField {

  public function getType()
  {
    return new PageObjectType();
  }

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

  public function getDescription()
  {
    return 'The parent Page object or a `null` if there is no parent.';
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    $parent = $value->parent;
    if ($parent instanceof NullPage) return null;
    return $parent;
  }

}

<?php

namespace ProcessWire\GraphQL\Field\Page;

use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Field\InputField;
use Youshido\GraphQL\Config\Field\FieldConfig;
use ProcessWire\GraphQL\Type\Scalar\SelectorType;
use ProcessWire\GraphQL\Type\Object\PageType as PageObjectType;
use ProcessWire\NullPage;

class PageParentField extends AbstractField {

  public function getType()
  {
    return new PageObjectType();
  }

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

  public function getDescription()
  {
    return 'The parent Page object, or the closest parent matching the given selector. Returns `null` if there is no parent or no match.';
  }

  public function build(FieldConfig $config)
  {
    $config->addArgument(new InputField([
      'name' => SelectorType::ARGUMENT_NAME,
      'type' => new SelectorType(),
    ]));
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    $s = SelectorType::ARGUMENT_NAME;
    if (isset($args[$s])) $parent = $value->parent($args[$s]);
    else $parent = $value->parent;
    if ($parent instanceof NullPage) return null;
    return $parent;
  }

}

Add optional selector argument support.

Add optional selector argument support.


<?php
namespace WillFarrell\AlfredPkgMan;

require_once('Cache.php');
require_once('Repo.php');

class Hex extends Repo
{
    protected $id         = 'hex';
    protected $kind       = 'components';
    protected $url        = 'https://hex.pm';
    protected $search_url = 'https://hex.pm/api/packages?search=';

    public function search($query)
    {
        if (!$this->hasMinQueryLength($query)) {
            return $this->xml();
        }

        $this->pkgs = $this->cache->get_query_json(
            $this->id,
            $query,
            "{$this->search_url}{$query}"
        );

        foreach ($this->pkgs as $pkg) {
            $url = str_replace('api/', '', $pkg->url);
            $this->cache->w->result(
                $pkg->url,
                $this->makeArg($pkg->name, $url),
                $pkg->name,
                $url,
                "icon-cache/{$this->id}.png"
            );

            // only search till max return reached
            if (count($this->cache->w->results()) == $this->max_return) {
                break;
            }
        }

        $this->noResults($query, "{$this->search_url}{$query}");

        return $this->xml();
    }
}

// Test code, uncomment to debug this script from the command-line
// $repo = new Hex();
// echo $repo->search('test');

<?php
namespace WillFarrell\AlfredPkgMan;

require_once('Cache.php');
require_once('Repo.php');

class Hex extends Repo
{
    protected $id         = 'hex';
    protected $kind       = 'components';
    protected $url        = 'https://hex.pm';
    protected $search_url = 'https://hex.pm/api/packages?sort=downloads&search=';

    public function search($query)
    {
        if (!$this->hasMinQueryLength($query)) {
            return $this->xml();
        }

        $this->pkgs = $this->cache->get_query_json(
            $this->id,
            $query,
            "{$this->search_url}{$query}"
        );

        foreach ($this->pkgs as $pkg) {
            $url = str_replace('api/', '', $pkg->url);
            $this->cache->w->result(
                $pkg->url,
                $this->makeArg($pkg->name, $url),
                $pkg->name,
                $url,
                "icon-cache/{$this->id}.png"
            );

            // only search till max return reached
            if (count($this->cache->w->results()) == $this->max_return) {
                break;
            }
        }

        $this->noResults($query, "{$this->search_url}{$query}");

        return $this->xml();
    }
}

// Test code, uncomment to debug this script from the command-line
// $repo = new Hex();
// echo $repo->search('test');

Add sort by downlaods for hex accuracy

Add sort by downlaods for hex accuracy


<?php
use Laracasts\Integrated\Extensions\Goutte as IntegrationTest;

use Illuminate\Database\Capsule\Manager as Capsule;

trait EloquentFunctionalityTrait
{
    /**
     * Begin a new database transaction.
     *
     * @setUp
     */
    public function beginTransaction()
    {
        $this->capsule->table('m')->truncate();
    }

    /**
     * Rollback the transaction.
     *
     * @tearDown
     */
    public function rollbackTransaction()
    {
        $this->capsule->table('m')->truncate();
    }
}

<?php
use Laracasts\Integrated\Extensions\Goutte as IntegrationTest;

use Illuminate\Database\Capsule\Manager as Capsule;

trait EloquentFunctionalityTrait
{
    protected $tables_used = [];

    /**
     * Begin a new database transaction.
     *
     * @setUp
     */
    public function beginTransaction()
    {
        $this->capsule = buildCapsuleFromConfigFile(__DIR__ . '/../integrated.json');
        $this->clearTables();
    }

    /**
     * Rollback the transaction.
     *
     * @tearDown
     */
    public function rollbackTransaction()
    {
        $this->clearTables();
    }

    protected function clearTables()
    {
        if (!is_array($this->tables_used)) {
            $this->tables_used = [$this->tables_used];
        }

        foreach ($this->tables_used as $table) {
            $this->capsule->table($table)->truncate();
        }
    }
}

Include the fetching of the capsule, allow the truncats to be customizable


<?php

/*
|--------------------------------------------------------------------------
| HTML::title() macro
|--------------------------------------------------------------------------
|
| Page title macro helper.
|
*/

HTML::macro('title', function ($page_title)
{
	$memory     = Orchestra::memory();
	$site_title = $memory->get('site.name');
	$page_title = trim($page_title);
	$format     = $memory->get('site.format.title', ':page-title — :site-title');

	if (empty($page_title)) return $site_title;
	return strtr($format, array(
		":site-title" => $site_title,
		":page-title" => $page_title,
	));
});

/*
|--------------------------------------------------------------------------
| Blade extend for @placeholder
|--------------------------------------------------------------------------
|
| Placeholder is Orchestra version of widget for theme.
|
*/

Blade::extend(function ($view)
{
	$pattern     = '/(\s*)@placeholder\s?\(\s*(.*)\)/';
	$replacement = '$1<?php foreach (Orchestra\Widget::make("placeholder.".$2)->get() as $_placeholder_): echo value($_placeholder_->value ?:""); endforeach; ?>';

	return preg_replace($pattern, $replacement, $view);
});

<?php

/*
|--------------------------------------------------------------------------
| HTML::title() macro
|--------------------------------------------------------------------------
|
| Page title macro helper.
|
*/

HTML::macro('title', function ($page_title)
{
	$memory     = Orchestra::memory();
	$site_title = $memory->get('site.name');
	$page_title = trim($page_title);
	$format     = $memory->get('site.format.title', ':page-title — :site-title');

	if (empty($page_title) or URI::is('/')) return $site_title;

	return strtr($format, array(
		":site-title" => $site_title,
		":page-title" => $page_title,
	));
});

/*
|--------------------------------------------------------------------------
| Blade extend for @placeholder
|--------------------------------------------------------------------------
|
| Placeholder is Orchestra version of widget for theme.
|
*/

Blade::extend(function ($view)
{
	$pattern     = '/(\s*)@placeholder\s?\(\s*(.*)\)/';
	$replacement = '$1<?php foreach (Orchestra\Widget::make("placeholder.".$2)->get() as $_placeholder_): echo value($_placeholder_->value ?:""); endforeach; ?>';

	return preg_replace($pattern, $replacement, $view);
});

Remove page title from frontpage

Remove page title from frontpage

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


<?php
namespace MarkMx\SkelBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class ResetDbType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('confirm', 'checkbox', array(
            'label'         => 'Confirm reset the demo DB to default fixtures losing all current data.',
            'required'      => true,
            'constraints'   => array(
                new NotBlank(array(
                    'message' => 'Confirm box must be checked to reset the DB.'
                ))
            ),
        ));
    }

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

<?php
namespace MarkMx\SkelBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class ResetDbType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('confirm', 'checkbox', array(
            'label'         => 'Confirm current DB data will be destroyed and replaced with fixtures data.',
            'required'      => true,
            'constraints'   => array(
                new NotBlank(array(
                    'message' => 'Confirm box must be checked to reset the DB.'
                ))
            ),
        ));
    }

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

Improve English for checkbox label

Improve English for checkbox label


<?php

use PreSQL\PDO;

class PDOTest extends PHPUnit_Framework_TestCase
{
    public function testIsPreSQLPDOVersionReturnedCorrectly()
    {
        $this->assertEquals(PDO::getVersion(), PDO::$version);
    }
}

<?php

use PreSQL\PDO;

class PDOTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers \PreSQL\PDO
     */
    public function testIsPreSQLPDOVersionReturnedCorrectly()
    {
        $this->assertEquals(PDO::getVersion(), PDO::$version);
    }
}

Add @covers annotation to test how coverage report changes.


<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Nos Bonbons</title>
    <link rel="stylesheet" href="css/main.css">

    <?php
    include "Reference.php";
    	 ?>

<?php include("header.php"); ?>

    <img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap">

<?php echo $Reference[1]['Titre']; ?>

<?php echo $Reference[1]['Description'];?>

    <?php //include("footer.php"); ?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Nos Bonbons</title>
    <link rel="stylesheet" href="css/main.css">

    <?php
    include "Reference.php";
    	 ?>

<?php include("header.php"); ?>

    <img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap">

<?php echo $Reference[1]['Titre']; ?>

<?php echo $Reference[1]['Description'];?>

<?php echo $Reference[1]['Texte']; ?>

    <?php //include("footer.php"); ?>

Add texte to description to producr

Add texte to description to producr


<?php
declare(strict_types=1);

namespace MattyG\BBStatic\Content\Page;

use MattyG\BBStatic\BBCode\NeedsBBCodeRendererTrait;
use MattyG\BBStatic\Util\Vendor\NeedsTemplateEngineTrait;
use Symfony\Component\Filesystem\NeedsFilesystemTrait;

final class PageRenderer
{
    use NeedsBBCodeRendererTrait;
    use NeedsFilesystemTrait;
    use NeedsTemplateEngineTrait;

    /**
     * @param Page $page
     * @return string The filename of the rendered page.
     */
    public function render(Page $page) : string
    {
        $pageType = $page->getPageType();
        $contentFilename = $page->getContentFilename();

        $convertedContent = $this->bbcodeRenderer->build($contentFilename);

        $template = $this->templateEngine->loadTemplate($pageType);
        $context = array(
            "title" => $page->getTitle(),
            "author" => $page->getAuthor(),
            "date_posted" => $page->getDatePosted(),
            "date_updated" => $page->getDateUpdated(),
            "content" => $convertedContent,
            "vars" => $page->getTemplateVariables(),
        );
        $renderedContent = $template->render($context);

        $outFilename = $page->getOutputFolder() . DIRECTORY_SEPARATOR . "index.html";
        $this->filesystem->dumpFile($outFilename, $renderedContent);
        return $outFilename;
    }
}

<?php
declare(strict_types=1);

namespace MattyG\BBStatic\Content\Page;

use MattyG\BBStatic\BBCode\NeedsBBCodeRendererTrait;
use MattyG\BBStatic\Util\Vendor\NeedsTemplateEngineTrait;
use Symfony\Component\Filesystem\NeedsFilesystemTrait;

class PageRenderer
{
    use NeedsBBCodeRendererTrait;
    use NeedsFilesystemTrait;
    use NeedsTemplateEngineTrait;

    /**
     * @param Page $page
     * @return string The filename of the rendered page.
     */
    final public function render(Page $page) : string
    {
        $pageType = $page->getPageType();

        $renderedContent = $this->bbcodeRenderer->build($page->getContentFilename());

        $template = $this->templateEngine->loadTemplate($pageType);
        $context = array_merge($this->prepareContext($page), array("content" => $renderedContent));
        $renderedPage = $template->render($context);

        $outFilename = $page->getOutputFolder() . DIRECTORY_SEPARATOR . "index.html";
        $this->filesystem->dumpFile($outFilename, $renderedPage);
        return $outFilename;
    }

    /**
     * @param Page $page
     * @return array
     */
    protected function prepareContext(Page $page) : array
    {
        return array(
            "title" => $page->getTitle(),
            "author" => $page->getAuthor(),
            "date_posted" => $page->getDatePosted(),
            "date_updated" => $page->getDateUpdated(),
            "vars" => $page->getTemplateVariables(),
        );
    }
}

Split preparating of context into separate method when rendering pages


<?php

namespace Ob\Hex\Domain;

abstract class EventSourcedEntity
{
    protected $changes = [];

    public static function createFromChanges(array $changes)
    {
        return new static($changes);
    }

    protected function __construct(array $changes)
    {
        foreach ($changes as $change) {
            $this->apply($change);
        }
    }

    /**
     * @param mixed $change
     */
    protected function apply($change)
    {
        $classParts = explode('\\', get_class($change));
        $method     = 'apply' . end($classParts);

        if (!method_exists($this, $method)) {
            return;
        }

        $this->changes[] = $change;
        $this->$method($change);
    }

    /**
     * @return array
     */
    public function getChanges()
    {
        return $this->changes;
    }
}

<?php

namespace Ob\Hex\Domain;

abstract class EventSourcedEntity
{
    protected $changes = [];

    public static function createFromChanges(array $changes)
    {
        return new static($changes);
    }

    protected function __construct(array $changes)
    {
        foreach ($changes as $change) {
            $this->apply($change);
        }
    }

    /**
     * @param mixed $change
     */
    protected function apply($change)
    {
        $classParts = explode('\\', get_class($change));
        $method     = 'apply' . end($classParts);

        if (!method_exists($this, $method)) {
            return;
        }

        $this->changes[] = $change;
        $this->$method($change);
    }

    /**
     * @return array
     */
    public function getChanges()
    {
        $changes       = $this->changes;
        $this->changes = [];

        return $changes;
    }
}

Clear queued changes after they are retrieved

This prevents persisting the same changes twice in the event store


<?php

// Maximum number of posts to show on a journal page
$postsVisibleOnPage = 5;

// Whether in production mode or not
$isProduction = false;

// Calculate database file name and path from production switch
$databaseFileName = $isProduction ? 'production' : 'debug';
$databaseFilePath = './conf/' . $databaseFileName . '.sqlite';

// Prefix for database tables
$tablePrefix = 'blog_';

// Aggregated settings array - required for running the backend
$settings = array(
  'Database' => array('Prefix' => $tablePrefix, 'Database' => $databaseFilePath),
  'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'),
  'Defaults' => array('PostsVisible' => $postsVisibleOnPage),
  'Environment' => array('Production' => $isProduction),
  'URLs' => array('GalleryRoot' => 'http://my.site/gallery/')
);

<?php

// Maximum number of posts to show on a journal page
$postsVisibleOnPage = 5;

// Whether in production mode or not
$isProduction = false;

// Calculate database file name and path from production switch
$databaseFileName = $isProduction ? 'production' : 'debug';
$databaseFilePath = './conf/' . $databaseFileName . '.sqlite';

// Prefix for database tables
$tablePrefix = 'blog_';

// Aggregated settings array - required for running the backend
$settings = array(
  'Database' => array('Prefix' => $tablePrefix, 'Database' => $databaseFilePath),
  'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'),
  'Defaults' => array('PostsVisible' => $postsVisibleOnPage),
  'Environment' => array('Production' => $isProduction),
  'URLs' => array('GalleryRoot' => 'http://my.site/gallery/'),
  'Paths' => array('KeyRoot' => '../../private-location/')
);

Add key path config to example settings file


<?php

namespace PhpAbac\Comparison;

class BooleanComparison extends AbstractComparison
{
    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolAnd($expected, $value)
    {
        return $expected && $value;
    }

    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolOr($expected, $value)
    {
        return $expected || $value;
    }
}

<?php

namespace PhpAbac\Comparison;

class BooleanComparison extends AbstractComparison
{
    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolAnd($expected, $value)
    {
        return $expected && $value;
    }

    /**
     * @param bool $expected
     * @param bool $value
     *
     * @return bool
     */
    public function boolOr($expected, $value)
    {
        return $expected || $value;
    }

    /**
     * @param mixed $expected
     * @param mixed $value
     */
    public function isNull($expected, $value)
    {
        return $value === null;
    }
}

Implement comparison method to check if an attribute is null


<?php

namespace GrumPHP\Locator;

use Gitonomy\Git\Diff\File;
use Gitonomy\Git\Repository;
use GrumPHP\Collection\FilesCollection;
use SplFileInfo;

/**
 * Class Git
 *
 * @package GrumPHP\Locator
 */
class ChangedFiles implements LocatorInterface
{

    /**
     * @var Repository
     */
    protected $repository;

    /**
     * @param Repository $repository
     */
    public function __construct(Repository $repository)
    {
        $this->repository = $repository;

    }

    /**
     * @return FilesCollection
     */
    public function locate()
    {
        $diff = $this->repository->getDiff('HEAD');
        $files = array();
        /** @var File $file */
        foreach ($diff->getFiles() as $file) {
            if ($file->isDeletion()) {
                continue;
            }

            $fileName = $file->isRename() ? $file->getNewName() : $file->getName();
            $files[] = new SplFileInfo($fileName);
        }

        return new FilesCollection($files);
    }
}

<?php

namespace GrumPHP\Locator;

use Gitonomy\Git\Diff\File;
use Gitonomy\Git\Repository;
use GrumPHP\Collection\FilesCollection;
use SplFileInfo;

/**
 * Class Git
 *
 * @package GrumPHP\Locator
 */
class ChangedFiles implements LocatorInterface
{

    /**
     * @var Repository
     */
    protected $repository;

    /**
     * @param Repository $repository
     */
    public function __construct(Repository $repository)
    {
        $this->repository = $repository;

    }

    /**
     * @return FilesCollection
     */
    public function locate()
    {
        $diff = $this->repository->getWorkingCopy()->getDiffStaged();
        $files = array();
        /** @var File $file */
        foreach ($diff->getFiles() as $file) {
            if ($file->isDeletion()) {
                continue;
            }

            $fileName = $file->isRename() ? $file->getNewName() : $file->getName();
            $files[] = new SplFileInfo($fileName);
        }

        return new FilesCollection($files);
    }
}

Check only the files that are staged for commit


<?php

namespace Samrap\Validation;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../app/' => app_path()
        ], 'application');
    }
}

<?php

namespace Samrap\Validation;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../app/' => app_path()
        ], 'app');
    }

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

Add register method, change publishes tag.


<?php

require_once('../Config/DBConnection.php');

//enable cross origin resources sharing (CORS)
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

//creates a question node

$getQuestion = htmlspecialchars($_GET['question']);

$queryString = "MERGE (n:Question { question: '" . $getQuestion . "' }) RETURN n";

$client->sendCypherQuery($queryString);

$result = $client->getRows();

header("Content-type: application/json");

$JSON_RETURN = json_encode($result);

echo $JSON_RETURN;
?>

Add in JSON response format

Add in JSON response format


<?php

class SessionsController extends \BaseController {

  /**
   * Show the form for creating a new resource.
   *
   * @return Response
   */
  public function create()
  {
    if (Auth::check())
    {
      return Redirect::route('status');
    }
    return View::make('sessions.create');
  }

}

<?php

class SessionsController extends \BaseController {

  /**
   * Show the form for creating a new resource.
   *
   * @return Response
   */
  public function create()
  {
    if (Auth::check())
    {
      // Already loged in.
    }
    return View::make('sessions.create');
  }

    /**
   * Store a newly created resource in storage.
   *
   * @return Response
   */
  public function store()
  {
    $input = Input::only('email', 'password');
    // Compare this to user api
    $northstar = new Aurora\Services\Northstar\NorthstarAPI;
    $res = $northstar->login($input);

    var_dump($res);
    // Login
  }

}

Use login form to dump out login call.

Use login form to dump out login call.


<?php

namespace RIPS\APIConnector;

use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;

class API
{
    // @var UserRequests
    public $users;

    // @var GuzzleHttp/Client
    protected $client;

    // @var array - Config values for $client
    protected $clientConfig = [
        'base_uri' => 'https://api-test2.internal.ripstech.com',
        'timeout' => 10,
        'connect_timeout' => 10,
    ];

    /**
     * Initialize new API
     *
     * @param string $username
     * @param string $password
     * @param array $clientConfig
     */
    public function __construct(string $username, string $password, array $clientConfig = [])
    {
        $mergedConfig = array_merge($this->clientConfig, $clientConfig, [
            'headers' => [
                'X-API-Username' => $username,
                'X-API-Password' => $password,
                'User-Agent' => 'RIPS-API-Connector/0.0.1',
            ],
        ]);

        $this->client = new Client($mergedConfig);
        $this->users = new UserRequests($this->client);
        $this->orgs = new OrgRequests($this->client);
        $this->quotas = new QuotaRequests($this->client);
    }
}

<?php

namespace RIPS\APIConnector;

use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;

class API
{
    // @var UserRequests
    public $users;

    // @var OrgRequests
    public $orgs;

    // @var QuotaRequests
    public $quotas;

    // @var array - Config values for $client
    protected $clientConfig = [
        'base_uri' => 'https://api-test2.internal.ripstech.com',
        'timeout' => 10,
        'connect_timeout' => 10,
    ];

    /**
     * Initialize new API
     *
     * @param string $username
     * @param string $password
     * @param array $clientConfig
     */
    public function __construct(string $username, string $password, array $clientConfig = [])
    {
        $mergedConfig = array_merge($this->clientConfig, $clientConfig, [
            'headers' => [
                'X-API-Username' => $username,
                'X-API-Password' => $password,
                'User-Agent' => 'RIPS-API-Connector/0.0.1',
            ],
        ]);

        $client = new Client($mergedConfig);
        $this->users = new UserRequests($client);
        $this->orgs = new OrgRequests($client);
        $this->quotas = new QuotaRequests($client);
    }
}

Add missing class property declarations

Add missing class property declarations


<?php

namespace Zhiyi\Plus\Http\Controllers\APIs\V2;

use Illuminate\Http\Request;
use Zhiyi\Plus\Models\File as FileModel;
use Zhiyi\Plus\Http\Controllers\Controller;
use Zhiyi\Plus\Models\FileWith as FileWithModel;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseContract;

class FilesController extends Controller
{
    public function show(Request $request)
    {
        dd($request);
    }

    public function store()
    {
    }

    public function uploaded(Request $request, ResponseContract $response, FileModel $file, string $hash)
    {
        $file = $file->where('hash', $hash)->firstOr(['id'], function () {
            abort(404);
        });

        $fileWith = new FileWithModel();
        $fileWith->file_id = $file->id;

        $request->user()->files()->save($fileWith);
    }
}

<?php

namespace Zhiyi\Plus\Http\Controllers\APIs\V2;

use Illuminate\Http\Request;
use Zhiyi\Plus\Models\File as FileModel;
use Zhiyi\Plus\Http\Controllers\Controller;
use Zhiyi\Plus\Models\FileWith as FileWithModel;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseContract;

class FilesController extends Controller
{
    public function show(Request $request)
    {
        dd($request);
    }

    public function store()
    {
    }

    /**
     * Get or create a uploaded file with id.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Routing\ResponseFactory $response
     * @param \Zhiyi\Plus\Models\File $file
     * @param \Zhiyi\Plus\Models\FileWith $fileWith
     * @param string $hash
     * @return mixed
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function uploaded(Request $request, ResponseContract $response, FileModel $file, FileWithModel $fileWith, string $hash)
    {
        $file = $file->where('hash', $hash)->firstOr(['id'], function () {
            abort(404);
        });

        // 复用空类型数据～减少资源浪费.
        $fileWith = $fileWith->where('file_id', $file->id)
            ->where('user_id', $request->user()->id)
            ->where('channel', null)
            ->where('raw', null)
            ->firstOr(['id'], function () use ($file, $request, $fileWith) {
                $fileWith->file_id = $file->id;
                $fileWith->channel = null;
                $fileWith->raw = null;
                $request->user()->files()->save($fileWith);

                return $fileWith;
            });

        return $response->json([
            'message' => ['success'],
            'id' => $fileWith->id,
        ])->setStatusCode(200);
    }
}

Add File uploaded check or create API.

Add File uploaded check or create API.


<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Run;

class WhoopsServiceProvider extends Provider
{

    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }
        $run = new Run;

        $handler = new ErrorHandler();
        $json_handler = new JsonErrorHandler();

        $run->pushHandler($handler);
        $run->pushHandler($json_handler);

        $run->register();
    }

}

<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Handler\PlainTextHandler;
use Whoops\Run;

class WhoopsServiceProvider extends Provider
{

    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }
        $run = new Run;

        $handler = new ErrorHandler();
        $json_handler = new JsonErrorHandler();
        $cli_handler = new PlainTextHandler();
        $cli_handler->onlyForCommandLine(true);

        $run->pushHandler($handler);
        $run->pushHandler($json_handler);
        $run->pushHandler($cli_handler);

        $run->register();
    }

}

Add plaintext error output for CLI

Add plaintext error output for CLI


<?php

use yii\db\Migration;

class m160219_091156_createUser extends Migration
{
    public function up()
    {
        $userName = 'webmaster';

        $tableName = \dektrium\user\models\User::tableName();
        $query = 'SELECT COUNT(*) FROM '.$tableName.' WHERE `username`=:username';
        $count = Yii::$app->db->createCommand($query, [':username'=>$userName])->queryScalar();
        if($count>0)
            return true;

        $user = \Yii::createObject([
            'class'    => \dektrium\user\models\User::className(),
            'scenario' => 'create',
            'username' => $userName,
            'password' => $userName,
            'email' => $userName.'@yii2enterprise.dev',
        ]);

        return $user->create();
    }

    public function down()
    {
        echo "m160219_091156_createUser cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

<?php

use yii\db\Migration;

class m160219_091156_createUser extends Migration
{
    public function up()
    {
        $userName = 'webmaster';

        $tableName = \dektrium\user\models\User::tableName();
        $query = 'SELECT COUNT(*) FROM '.$tableName.' WHERE `username`=:username';
        $count = \Yii::$app->db->createCommand($query, [':username'=>$userName])->queryScalar();
        if($count>0)
            return true;

        $user = \Yii::createObject([
            'class'    => \dektrium\user\models\User::className(),
            'scenario' => 'create',
            'username' => $userName,
            'password' => $userName,
            'email' => $userName.'@yii2enterprise.dev',
        ]);

        return $user->create();
    }

    public function down()
    {
        echo "m160219_091156_createUser cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

Update and try fix bug with migration

Update and try fix bug with migration


<?php

namespace Backend\Core\Tests;

use Common\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

abstract class BackendWebTestCase extends WebTestCase
{
    /**
     * Make sure we are no longer logged-in
     */
    protected function tearDown(): void
    {
        $client = $this->getProvidedData()[0] ?? null;
        if ($client instanceof Client) {
            $this->logout($client);
        }
    }

    protected function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }
    }

    protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void
    {
        // make sure we aren't logged in with the client
        $this->logout($client);

        self::assertGetsRedirected(
            $client,
            $url,
            '/private/en/authentication?querystring=' . rawurlencode($url),
            $method
        );
    }
}

<?php

namespace Backend\Core\Tests;

use Common\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

abstract class BackendWebTestCase extends WebTestCase
{
    /**
     * Make sure we are no longer logged-in
     */
    protected function tearDown(): void
    {
        $client = $this->getProvidedData()[0] ?? null;
        if ($client instanceof Client) {
            $this->logout($client);
        }
    }

    protected function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }
    }

    protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void
    {
        // make sure we aren't logged in with the client
        $this->logout($client);

        self::assertGetsRedirected(
            $client,
            $url,
            '/private/en/authentication?querystring=' . rawurlencode($url),
            $method
        );
    }

    protected function appendCsrfTokenToUrl(Client $client, string $url): string
    {
        $connectionSymbol = (strpos($url, '?') !== false) ? '&' : '?';

        return $url . $connectionSymbol . 'token=' . $client->getRequest()->getSession()->get('csrf_token');
    }
}

Add a method to add the csrf token to the url in tests


<?php

namespace Common\BlockEditor\Blocks;

use Frontend\Core\Engine\TwigTemplate;

abstract class EditorBlock
{
    /** @var TwigTemplate */
    private $template;

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

    final public function getName(): string
    {
        return static::class;
    }

    /**
     * @return array The config must contain the key "class" with the JS class for the editor
     */
    abstract public function getConfig(): array;

    /**
     * @see https://github.com/editor-js/editorjs-php#configuration-file
     */
    abstract public function getValidation(): array;

    abstract public function parse(array $data): string;
}

<?php

namespace Common\BlockEditor\Blocks;

use Frontend\Core\Engine\TwigTemplate;

abstract class EditorBlock
{
    /** @var TwigTemplate */
    private $template;

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

    final public function getName(): string
    {
        return static::class;
    }

    /**
     * @return array The config must contain the key "class" with the JS class for the editor
     */
    abstract public function getConfig(): array;

    /**
     * @see https://github.com/editor-js/editorjs-php#configuration-file
     */
    abstract public function getValidation(): array;

    /** The path to the JS file with the config needed to make this block work in the editor */
    abstract public function getJavaScriptPath(): string;

    abstract public function parse(array $data): string;
}

Add extra method so we know what JS files to load


<?php

namespace JsonLd\ContextTypes;

class Place extends Thing
{
    /**
     * Property structure
     *
     * @var array
     */
    protected $extendedStructure = [
        'address' => PostalAddress::class,
        'review' => Review::class,
        'aggregateRating' => AggregateRating::class,
    ];

    /**
     * Constructor. Merges extendedStructure up
     *
     * @param array $attributes
     * @param array $extendedStructure
     */
    public function __construct(array $attributes, array $extendedStructure = [])
    {
        parent::__construct($attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure));
    }

}

<?php

namespace JsonLd\ContextTypes;

class Place extends Thing
{
    /**
     * Property structure
     *
     * @var array
     */
    protected $extendedStructure = [
        'address' => PostalAddress::class,
        'review' => Review::class,
        'aggregateRating' => AggregateRating::class,
        'geo' => GeoCoordinates::class,
    ];

    /**
     * Constructor. Merges extendedStructure up
     *
     * @param array $attributes
     * @param array $extendedStructure
     */
    public function __construct(array $attributes, array $extendedStructure = [])
    {
        parent::__construct($attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure));
    }

}

Add geo property to place type

Add geo property to place type


<?php require_once("utilities.php");

$file = fopen("cached/proposed.json","w");
$count = 0;
$result = doUnprotectedQuery("SELECT pv_id, pv_name, pv_lat, pv_lng, pv_images, pv_population, pv_dev_problem, DATE_FORMAT(pv_date_added, '%M %e, %Y') AS dateAdded FROM proposed_villages WHERE pv_promoted=0");
while ($row = $result->fetch_assoc()) {

	fwrite($file, ($count > 0 ? "," : '{ "type": "FeatureCollection", "features": [').
	'{
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": ['.$row['pv_lng'].', '.$row['pv_lat'].']
		},
		"properties": {
			"id": "'.$row['pv_id'].'",
			"name": "'.$row['pv_name'].'",
			"pictures": "'.$row['pv_images'].'",
			"date_added": "'.$row['dateAdded'].'",
			"dev_problem": "'.$row['pv_dev_problem'].'",
			"population": "'.$row['pv_population'].'"
		}
	}');
	$count++;
}
fwrite($file, "]}");
fclose($file);
?>

<?php require_once("utilities.php");

$file = fopen("cached/proposed.json","w");
$count = 0;
$result = doUnprotectedQuery("SELECT pv_id, pv_name, pv_lat, pv_lng, pv_images, pv_population, pv_dev_problem, DATE_FORMAT(pv_date_added, '%M %e, %Y') AS dateAdded FROM proposed_villages WHERE pv_promoted=0");
while ($row = $result->fetch_assoc()) {

	fwrite($file, ($count > 0 ? "," : '{ "type": "FeatureCollection", "features": [').
	'{
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": ['.$row['pv_lng'].', '.$row['pv_lat'].']
		},
		"properties": {
			"id": "'.$row['pv_id'].'",
			"name": "'.$row['pv_name'].'",
			"pictures": "'.$row['pv_images'].'",
			"date_added": "'.$row['dateAdded'].'",
			"dev_problem": "'.str_replace(array("\r\n", "\n", "\r"), ' ', $row['pv_dev_problem']).'",
			"population": "'.$row['pv_population'].'"
		}
	}');
	$count++;
}
fwrite($file, "]}");
fclose($file);
?>

Handle newlines in proposed json

Handle newlines in proposed json


<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }
}

<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testDefaultOptions()
    {
        $this->assertNull($this->rule->getOption('min'));
        $this->assertTrue($this->rule->getOption('inclusive'));
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }
}

Add test to review the default values with no options


<?php

namespace Tests;

use Rosio\EncryptedCookie;
use Rosio\EncryptedCookie\CookieFactory;
use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;

class CookieFactoryTest extends \PHPUnit_Framework_TestCase
{
	public function testEncryptDecrypt ()
	{
		$this->markTestIncomplete('Need to find workaround so as to not try and actually set a cookie.');

		$factory = new CookieFactory(new AES_SHA1('symtest', 'hmactest'));

		$data = 'blah';

		$cookie = $factory->create('testCookie')->setData($data)->save();

		$newCookie = $factory->get('testCookie');

		$this->assertEquals($data, $newCookie->getData());
	}
}

<?php

namespace Tests;

use Mockery as m;

use Rosio\EncryptedCookie;
use Rosio\EncryptedCookie\CookieFactory;
use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;

class CookieFactoryTest extends \PHPUnit_Framework_TestCase
{
	public function tearDown ()
	{
		m::close();
	}

	public function testEncryptDecrypt ()
	{
		$storage = m::mock('\Rosio\EncryptedCookie\CookieStorage');
		$storage->shouldReceive('set')->once()->with(m::type('\Rosio\EncryptedCookie\EncryptedCookie'));
		$storage->shouldReceive('has')->once()->andReturn(true);
		$storage->shouldReceive('get')->once()->andReturn('blah');

		$factory = new CookieFactory(new AES_SHA1('symtest', 'hmactest'), $storage);

		$data = 'blah';

		$cookie = $factory->create('testCookie')->setData($data)->save();

		$newCookie = $factory->get('testCookie');

		// Returned data wasn't the correctly encrypted data, so it should fail to decrypt it
		$this->assertFalse($newCookie->getData());
	}
}

Test the factory a bit

Test the factory a bit


<?php
class ScribbleFixture extends CakeTestFixture {

	public $useDbConfig = 'test';

	public $import = 'Scribble';

	public $records = array(
		array('id' => 1, 'title' => 'Test Scribble', 'body' => 'I am a Scribble!', 'ukey' => '1234567', 'short_link' => 'http://www.example.com', 'created' => '2013-10-12 01:01:01', 'modified' => '2013-10-12 01:01:01')
	);
}

<?php
class ScribbleFixture extends CakeTestFixture {

	public $useDbConfig = 'test';

	public $fields = array(
		'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 10, 'key' => 'primary'),
		'title' => array('type' => 'string', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'body' => array('type' => 'text', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'ukey' => array('type' => 'string', 'null' => true, 'default' => null, 'key' => 'unique', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'short_link' => array('type' => 'string', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
		'modified' => array('type' => 'datetime', 'null' => true, 'default' => null),
		'indexes' => array(
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
			'ukey' => array('column' => 'ukey', 'unique' => 1)
		),
		'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
	);

	public $records = array(
		array('id' => 1, 'title' => 'Test Scribble', 'body' => 'I am a Scribble!', 'ukey' => '1234567', 'short_link' => 'http://www.example.com', 'created' => '2013-10-12 01:01:01', 'modified' => '2013-10-12 01:01:01')
	);
}

Define the database schema in test.

Define the database schema in test.


<?php

namespace ViewerBundle\Form\Type;

use Core\CoreBundle\Form\Type\GenericEntityType;
use Core\ProjectBundle\Component\Helper\ProjectHelper;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ServerUrlsType extends AbstractType
{
    /**
     * @var RegistryInterface
     */
    private $doctrine;

    /**
     * @var ProjectHelper
     */
    private $projectHelper;

    public function __construct(RegistryInterface $doctrine, ProjectHelper $projectHelper)
    {
        $this->doctrine = $doctrine;
        $this->projectHelper = $projectHelper;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $fixedValues = array();
        $fixedValues['project'] = $this->projectHelper->getProject();
        $fixedValues['domain'] = $this->projectHelper->getDomain();

        $builder->add('serverUrls',
                      'collection',
                      array(
                          'type' => new GenericEntityType($this->doctrine),
                          'allow_add' => true,
                          'allow_delete' => true,
                          'options' => array('data_class' => 'ViewerBundle\Entity\ServerUrl',
                                             'fixed_values' => $fixedValues),
                          'by_reference' => false,
                      ));

    }

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

}

<?php

namespace ViewerBundle\Form\Type;

use Core\CoreBundle\Form\Type\GenericEntityType;
use Core\ProjectBundle\Component\Helper\ProjectHelper;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ServerUrlsType extends AbstractType
{
    /**
     * @var RegistryInterface
     */
    private $doctrine;

    /**
     * @var ProjectHelper
     */
    private $projectHelper;

    public function __construct(RegistryInterface $doctrine, ProjectHelper $projectHelper)
    {
        $this->doctrine = $doctrine;
        $this->projectHelper = $projectHelper;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $fixedValues = array();
        $fixedValues['project'] = $this->projectHelper->getProject();
        $fixedValues['domain'] = $this->projectHelper->getDomain();
        $fixedValues = array_filter($fixedValues);

        $builder->add('serverUrls',
                      'collection',
                      array(
                          'type' => new GenericEntityType($this->doctrine),
                          'allow_add' => true,
                          'allow_delete' => true,
                          'options' => array('data_class' => 'ViewerBundle\Entity\ServerUrl',
                                             'fixed_values' => $fixedValues),
                          'by_reference' => false,
                      ));

    }

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

}

Delete null values from fixed values

Delete null values from fixed values


<?php
set_time_limit(0);

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

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

echo "LinMon slave version ".getVersion("version")." started. \n";
echo checkVersion();
echo "Collecting data every ".$config['updateinterval']." seconds \n";

while (true){
	echo "Starting data collection \n";
	sleep($config['updateinterval']);
}
?>

<?php
set_time_limit(0);

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

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

echo "LinMon slave version ".getVersion("version")." started. \n\n";
echo checkVersion()."\n\n";
echo "Collecting data every ".$config['updateinterval']." seconds \n\n";

while (true){
	echo "Starting data collection \n";
	sleep($config['updateinterval']);
}
?>

Add some more linespacing to make output easier to read


<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
 *
 * @author Roeland Jago Douma <roeland@famdouma.nl>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

style('core', 'login/authpicker');

/** @var array $_ */
?>

<?php p($l->t('Account connected')) ?>

		<?php print_unescaped($l->t('Your client should now be connected! You can close this window.')) ?>

<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
 *
 * @author Roeland Jago Douma <roeland@famdouma.nl>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

style('core', 'login/authpicker');

/** @var array $_ */
?>

<?php p($l->t('Account connected')) ?>

		<?php p($l->t('Your client should now be connected!')) ?>

		<?php p($l->t('You can close this window.')) ?>

Move "you can close this window" to newline

Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>


<?php

namespace SebastiaanLuca\Migrations\Commands;

use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
use Illuminate\Support\Composer;
use SebastiaanLuca\Migrations\ExtendedMigrationCreator;

class GenerateMigration extends MigrateMakeCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:migration
                            {name : The name of the migration}
                            {--create= : The table to be created}
                            {--table= : The table to migrate}
                            {--path= : The location where the migration file should be created}
                            {--module= : The table to migrate}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an unbreakable migration class that uses transactional queries.';

    /**
     * Create a new migration install command instance.
     *
     * @param \SebastiaanLuca\Migrations\ExtendedMigrationCreator $creator
     * @param \Illuminate\Support\Composer $composer
     */
    public function __construct(ExtendedMigrationCreator $creator, Composer $composer)
    {
        parent::__construct($creator, $composer);
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire() : void
    {
        if ($module = $this->option('module')) {
            $this->input->setOption('path', 'modules/' . $module . '/database/migrations');
        }

        parent::fire();
    }
}

<?php

namespace SebastiaanLuca\Migrations\Commands;

use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
use Illuminate\Support\Composer;
use SebastiaanLuca\Migrations\ExtendedMigrationCreator;

class GenerateMigration extends MigrateMakeCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:migration
                            {name : The name of the migration}
                            {--create= : The table to be created}
                            {--table= : The table to migrate}
                            {--path= : The location where the migration file should be created}
                            {--module= : The table to migrate}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an unbreakable migration class that uses transactional queries.';

    /**
     * Create a new migration install command instance.
     *
     * @param \SebastiaanLuca\Migrations\ExtendedMigrationCreator $creator
     * @param \Illuminate\Support\Composer $composer
     */
    public function __construct(ExtendedMigrationCreator $creator, Composer $composer)
    {
        parent::__construct($creator, $composer);
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle() : void
    {
        if ($module = $this->option('module')) {
            $this->input->setOption('path', 'modules/' . $module . '/database/migrations');
        }

        parent::handle();
    }
}

Update command to use new handle method

Update command to use new handle method


<?php

// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );

if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) {
	define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) {
	define( 'WP_CLI_VENDOR_DIR', dirname( dirname( WP_CLI_ROOT ) ) );
} else {
	define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
}

// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['REMOTE_ADDR']     = '127.0.0.1';

require_once WP_CLI_ROOT . '/php/bootstrap.php';
\WP_CLI\bootstrap();

<?php

// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );

if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) {
	define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) {
	define( 'WP_CLI_VENDOR_DIR', dirname( dirname( WP_CLI_ROOT ) ) );
} elseif ( file_exists( dirname( WP_CLI_ROOT ) . '/vendor/autoload.php' ) ) {
	define( 'WP_CLI_VENDOR_DIR', dirname( WP_CLI_ROOT ) . '/vendor' );
} else {
	define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
}

// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['REMOTE_ADDR']     = '127.0.0.1';

require_once WP_CLI_ROOT . '/php/bootstrap.php';
\WP_CLI\bootstrap();

Add sibling `vendor` folder location

Add sibling `vendor` folder location

For the development use case where all repositories are checked out into a flat folder hierarchy (mirroring the GitHub org), the `vendor` folder will end up being a sibling to the `wp-cli` framework folder.

The bootstrapping code needs to allow for this setup as well.


<?php
class Kwf_Component_MasterLayout_Legacy extends Kwf_Component_MasterLayout_Abstract
{
    public function getContexts(Kwf_Component_Data $data)
    {
        return null;
    }

    public function getContentWidth(Kwf_Component_Data $data)
    {
        if (!$this->_hasSetting('contentWidth')) {
            throw new Kwf_Exception('contentWidth has to be set for $data->componentClass (getting width for $data->componentId)');
        }
        $ret = $this->_getSetting('contentWidth');
        if (!$this->_hasSetting('contentWidthBoxSubtract')) return $ret;

        $boxes = array();
        foreach ($data->getChildBoxes() as $box) {
            $boxes[$box->box] = $box;
        }
        if ($this->_hasSetting('contentWidthBoxSubtract')) {
            foreach ($this->_getSetting('contentWidthBoxSubtract') as $box=>$width) {
                if (!isset($boxes[$box])) continue;
                $c = $boxes[$box];
                if ($c && $c->hasContent()) {
                    $ret -= $width;
                }
            }
        }
        return $ret;
    }
}

<?php
class Kwf_Component_MasterLayout_Legacy extends Kwf_Component_MasterLayout_Abstract
{
    public function getContexts(Kwf_Component_Data $data)
    {
        return null;
    }

    public function getContentWidth(Kwf_Component_Data $data)
    {
        if (!$this->_hasSetting('contentWidth')) {
            throw new Kwf_Exception("contentWidth has to be set for $data->componentClass (getting width for $data->componentId)");
        }
        $ret = $this->_getSetting('contentWidth');
        if (!$this->_hasSetting('contentWidthBoxSubtract')) return $ret;

        $boxes = array();
        foreach ($data->getChildBoxes() as $box) {
            $boxes[$box->box] = $box;
        }
        if ($this->_hasSetting('contentWidthBoxSubtract')) {
            foreach ($this->_getSetting('contentWidthBoxSubtract') as $box=>$width) {
                if (!isset($boxes[$box])) continue;
                $c = $boxes[$box];
                if ($c && $c->hasContent()) {
                    $ret -= $width;
                }
            }
        }
        return $ret;
    }
}

Use correct quotes for exception message


<?php

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

use Illuminate\Http\Request;

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);

Route::get('login', 'AuthController@redirectToProvider');

Route::get('callback', 'AuthController@handleProviderCallback');

Route::get('test', function (){
    $ping = new \JamylBot\Pingbot\Pingbot();
    return $ping->processPingCommand([]);
});

Route::post('sendping', function (Request $request){
    $ping = new \JamylBot\Pingbot\Pingbot();
    return $ping->processPingCommand($request->all());
});

<?php

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

use Illuminate\Http\Request;
use \JamylBot\Pingbot\Pingbot;

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);

Route::get('login', 'AuthController@redirectToProvider');

Route::get('callback', 'AuthController@handleProviderCallback');

Route::post('sendping', function (Request $request, Pingbot $pingbot){
    return $pingbot->processPingCommand($request->all());
});

Switch route to use dependency injection


<?php

namespace CuteControllers\Base;

abstract class Controller
{
    protected $request;

    public function __construct(\CuteControllers\Request $request)
    {
        $this->request = $request;
    }

    abstract public function route();
}

<?php

namespace CuteControllers\Base;

abstract class Controller
{
    protected $request;

    public function __construct(\CuteControllers\Request $request)
    {
        $this->request = $request;
    }

    protected function require_get()
    {
        $required = func_get_args();
        foreach ($required as $require) {
            if ($this->request->get($require) === NULL) {
                throw new \CuteControllers\HttpError(400);
            }
        }
    }

    protected function require_post()
    {
        $required = func_get_args();
        foreach ($required as $require) {
            if ($this->request->post($require) === NULL) {
                throw new \CuteControllers\HttpError(400);
            }
        }
    }

    protected function require_request()
    {
        $required = func_get_args();
        foreach ($required as $require) {
            if ($this->request->request($require) === NULL) {
                throw new \CuteControllers\HttpError(400);
            }
        }
    }

    abstract public function route();
}

Add simple require support to base controller


<?php

class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread
{
    protected function _getFields()
    {
        $fields = parent::_getFields();

        $fields['xf_thread']['word_count'] = array(
            'type'         => self::TYPE_UNKNOWN,
            'verification' => array('$this', '_verifyWordCount')
        );

        return $fields;
    }

    public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false)
    {
        parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId);

        $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id'));

        $this->set('word_count', $wordCount);
    }

    protected function _verifyWordCount($wordCount)
    {
        if (is_int($wordCount) || is_null($wordCount)) {
            return true;
        }

        return false;
    }
}

<?php

class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread
{
    protected function _getFields()
    {
        $fields = parent::_getFields();

        $fields['xf_thread']['word_count'] = array(
            'type'         => self::TYPE_UNKNOWN,
            'verification' => array('$this', '_verifyWordCount')
        );

        return $fields;
    }

    public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false)
    {
        parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId);

        if (SV_Utils_AddOn::addOnIsActive('sidaneThreadmarks', 1030002))
        {
            $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id'));
            $this->set('word_count', $wordCount);
        }
    }

    protected function _verifyWordCount($wordCount)
    {
        if (is_int($wordCount) || is_null($wordCount)) {
            return true;
        }

        return false;
    }
}

Fix unchecked function call in thread datawriter


<?php

namespace App\Nova\Filters;

use App\Team;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserTeam extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return $query->whereHas('teams', function ($query) {
            $query->where('id', '=', $value);
        });
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function options(Request $request)
    {
        $teams = [];
        if ($request->user()->can('read-teams')) {
            $teams = Team::where('attendable', 1)
                ->when($request->user()->cant('read-teams-hidden'), function ($query) {
                    $query->where('visible', 1);
                })->get()
                ->mapWithKeys(function ($item) {
                    return [$item['name'] => $item['id']];
                })->toArray();
        }

        return $teams;
    }
}

<?php

namespace App\Nova\Filters;

use App\Team;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserTeam extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return $query->whereHas('teams', function ($query) use ($value) {
            $query->where('id', '=', $value);
        });
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function options(Request $request)
    {
        $teams = [];
        if ($request->user()->can('read-teams')) {
            $teams = Team::where('attendable', 1)
                ->when($request->user()->cant('read-teams-hidden'), function ($query) {
                    $query->where('visible', 1);
                })->get()
                ->mapWithKeys(function ($item) {
                    return [$item['name'] => $item['id']];
                })->toArray();
        }

        return $teams;
    }
}

Fix closure for team filteR

Fix closure for team filteR