<?php
/**
 * Documentation Configuration
 *
 * Please override any of these options in your own projects _config.php file.
 * For more information and documentation see docsviewer/docs/en
 */

if(!defined('DOCSVIEWER_PATH')) {
	define('DOCSVIEWER_PATH', dirname(__FILE__));
}

if(!defined('DOCSVIEWER_DIR')) {
	$dir = explode(DIRECTORY_SEPARATOR, DOCSVIEWER_PATH);

	define('DOCSVIEWER_DIR', array_pop($dir));
}

// default location for documentation. If you want this under a custom url
// define your own rule in your mysite/_config.php
Director::addRules(100, array(
	'dev/docs' => 'DocumentationViewer'
));

// define filetypes to ignore
DocumentationService::set_ignored_files(array(
	'.', '..', '.DS_Store',
	'.svn', '.git', 'assets', 'themes', '_images', '_resources'
));

Add _resources to the list of files to be ignored

using DocumentationService::set_ignored_files() in _config


<?php

/**
 * My Website Project
 *
 * PHP version 5
 *
 * @category Demo
 * @package  None
 * @author   Christophe Vanlancker <carroarmato0@gmail.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://carroarmato0.be
 *
 */

  echo "Hello World";

Make PHP Code Sniffer happy by adding doc

Signed-off-by: Christophe Vanlancker <e326f9f563002de800fc8506f2187bbb9dd743fc@inuits.eu>


<?php
/* ------------------------------------------------------------------------ *\
 * Functions: Rewrites
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___pwa_rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", parse_url(get_stylesheet_directory_uri(), PHP_URL_PATH) . "/assets/media/$1", "top");
}
add_action("init", "__gulp_init_namespace___pwa_rewrite_rules");

<?php
/* ------------------------------------------------------------------------ *\
 * Functions: Rewrites
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___pwa_rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top");
}
add_action("init", "__gulp_init_namespace___pwa_rewrite_rules");

Adjust media rewrite so that it will work in all circumstances


<?php

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

// vendors not installed
if(!is_dir(__DIR__ . '/vendor'))
{
	echo 'You are missing some dependencies. Please run composer install.';
	exit;
}

// Fork has not yet been installed
$installer = dirname(__FILE__) . '/install/cache';
if(
	file_exists($installer) &&
	is_dir($installer) &&
	!file_exists($installer . '/installed.txt') &&
	substr($_SERVER['REQUEST_URI'], 0, 8) != '/install'
)
{
	header('Location: /install');
}

use Symfony\Component\HttpFoundation\Request;

require_once __DIR__ . '/autoload.php';
require_once __DIR__ . '/app/AppKernel.php';

$kernel = new AppKernel();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

<?php

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

// vendors not installed
if(!is_dir(__DIR__ . '/vendor'))
{
	echo 'You are missing some dependencies. Please run composer install.';
	exit;
}

// Fork has not yet been installed
$installer = dirname(__FILE__) . '/install/cache';
if(
	file_exists($installer) &&
	is_dir($installer) &&
	!file_exists($installer . '/installed.txt') &&
	substr($_SERVER['REQUEST_URI'], 0, 8) != '/install'
)
{
	header('Location: /install');
	exit;
}

use Symfony\Component\HttpFoundation\Request;

require_once __DIR__ . '/autoload.php';
require_once __DIR__ . '/app/AppKernel.php';

$kernel = new AppKernel();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

Exit after redirecting to prevent to entire application from being executed.


<?php

namespace ZF\ApiFirstAdmin\Model;

use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;

class CodeConnectedRpcFactory
{
    /**
     * @var ConfigResourceFactory
     */
    protected $configFactory;

    /**
     * @var ModuleUtils
     */
    protected $modules;

    /**
     * @param  ModuleUtils $modules
     * @param  ConfigResource $config
     */
    public function __construct(ModuleUtils $modules, ConfigResourceFactory $configFactory)
    {
        $this->modules = $modules;
        $this->config  = $config;
    }

    /**
     * @param  string $module
     * @return CodeConnectedRpc
     */
    public function factory($module)
    {
        if (isset($this->models[$module])) {
            return $this->models[$module];
        }

        $config = $this->configFactory->factory($module);
        $this->models[$module] = new CodeConnectedRpc($module, $this->modules, $config);

        return $this->models[$module];
    }
}

<?php

namespace ZF\ApiFirstAdmin\Model;

use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;

class CodeConnectedRpcFactory
{
    /**
     * @var ConfigResourceFactory
     */
    protected $configFactory;

    /**
     * @var ModuleUtils
     */
    protected $modules;

    /**
     * @param  ModuleUtils $modules
     * @param  ConfigResource $config
     */
    public function __construct(ModuleUtils $modules, ConfigResourceFactory $configFactory)
    {
        $this->modules = $modules;
        $this->config  = $config;
    }

    /**
     * @param  string $module
     * @return CodeConnectedRpc
     */
    public function factory($module)
    {
        $module = $this->normalizeModuleName($module);

        if (isset($this->models[$module])) {
            return $this->models[$module];
        }

        $config = $this->configFactory->factory($module);
        $this->models[$module] = new CodeConnectedRpc($module, $this->modules, $config);

        return $this->models[$module];
    }

    /**
     * @param  string $name
     * @return string
     */
    protected function normalizeModuleName($name)
    {
        return str_replace('\\', '.', $name);
    }
}

Normalize module name before processing

Normalize module name before processing


<?php
// the path to your web site.
// if you are at the root dir of your domain, this can be an empty string.
// otherwise, use an url like http://example.com
define('WEBROOT', '');
//just like above, just for the subfolder /ajax.
//either /ajax
//or http://example.com/ajax
define('SERVICEPATH', '/ajax');

//chado database
define('DB_ADAPTER','pgsql');
define('DB_CONNSTR', 'pgsql:host=${chado_db_host};dbname=${chado_db_name};port=${chado_db_port}');
define('DB_USERNAME', '${chado_db_username}');
define('DB_PASSWORD', '${chado_db_password}');

//set error reporting to a level that suits you
error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE);
ini_set('display_errors', '0');

//uncomment for debugging
if (isset($_REQUEST['DEBUG']))
    define('DEBUG', true);
error_reporting(E_ALL );
ini_set('display_errors', '1');
?>

<?php
// the path to your web site.
// if you are at the root dir of your domain, this can be an empty string.
// otherwise, use an url like http://example.com
define('WEBROOT', '');
//just like above, just for the subfolder /ajax.
//either /ajax
//or http://example.com/ajax
define('SERVICEPATH', '/ajax');

//chado database
const DATABASE = array("1.0" => array(
    'DB_ADAPTER' => 'pgsql',
    'DB_CONNSTR' => 'pgsql:host=${chado_db_host};dbname=${chado_db_name};port=${chado_db_port}',
    'DB_USERNAME' => '${chado_db_username}',
    'DB_PASSWORD' => '${chado_db_password}'
    ));

//set error reporting to a level that suits you
error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE);
ini_set('display_errors', '0');

//uncomment for debugging
if (isset($_REQUEST['DEBUG']))
    define('DEBUG', true);
error_reporting(E_ALL );
ini_set('display_errors', '1');
?>

Change structure of db constant

Change structure of db constant


<?php

require_once('config.inc.php');
require_once('misc.inc.php');
require_once('db.inc.php');
require_once('html.inc.php');

date_default_timezone_set('Europe/Berlin');
setlocale(LC_TIME, 'de_DE');

session_start();

// Actual content generation:
$db = new db();

switch ($_GET['view']) {
case 'public':
    authenticate(VIEW_PUBLIC, 'index.php?view=public');
    $source = new ovp_public($db);
    break;
case 'print':
    authenticate(VIEW_PRINT, 'index.php?view=print');
    if (isset($_GET['date'])) {
        $source = new ovp_print($db, $_GET['date']);
    } else {
        $source = new ovp_print($db);
    }
    break;
case 'author':
    authenticate(VIEW_AUTHOR, 'index.php?view=author');
    $source = new ovp_author($db);
    break;
case 'admin':
    authenticate(VIEW_ADMIN, 'index.php?view=admin');
    $source = new ovp_admin($db);
    break;
case 'login':
default:
    $source = new ovp_login($db);
}

$page = new ovp_page($source);
exit($page->get_html());

?>

<?php

require_once('config.inc.php');
require_once('misc.inc.php');
require_once('db.inc.php');
require_once('html.inc.php');

date_default_timezone_set('Europe/Berlin');
setlocale(LC_TIME, 'de_DE');

session_start();

// Actual content generation:
$db = new db();

switch ($_GET['view']) {
case 'print':
    authenticate(VIEW_PRINT, 'index.php?view=print');
    if (isset($_GET['date'])) {
        $source = new ovp_print($db, $_GET['date']);
    } else {
        $source = new ovp_print($db);
    }
    break;
case 'author':
    authenticate(VIEW_AUTHOR, 'index.php?view=author');
    $source = new ovp_author($db);
    break;
case 'admin':
    authenticate(VIEW_ADMIN, 'index.php?view=admin');
    $source = new ovp_admin($db);
    break;
case 'login':
    $source = new ovp_login($db);
    break;
case 'public':
default:
    authenticate(VIEW_PUBLIC, 'index.php?view=public');
    $source = new ovp_public($db);
}

$page = new ovp_page($source);
exit($page->get_html());

?>

Undo "Make login the default view"

Undo "Make login the default view"

(97c89395eb34093f103cc8816c1d2420e6c8e44d)

Signed-off-by: Tillmann Karras <28ed73209cf4ae5252aebcefd0036a7597a64897@gmail.com>


	<time datetime="<?php echo esc_attr( date( 'c', $this->get( 'post_publish_timestamp' ) ) ); ?>">
		<?php
		echo esc_html(
			sprintf(
                /* translators: %s: the human-readable time difference. */
                __( '%s ago', 'amp' ),
				human_time_diff( $this->get( 'post_publish_timestamp' ), current_time( 'timestamp' ) )
			)
		);
		?>
	</time>

Fix indentation in template file

Fix indentation in template file


<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;

use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;

class SchemaConfigMakeCommandTest extends TestCase
{
    use MakeCommandAssertionTrait;

    /**
     * @dataProvider dataForMakeCommand
     */
    public function testCommand(
        string $inputName,
        string $expectedFilename,
        string $expectedClassDefinition,
    ): void {
        $this->assertMakeCommand(
            'Schema',
            SchemaConfigMakeCommand::class,
            $inputName,
            $expectedFilename,
            'App\\\\GraphQL\\\\Schemas',
            $expectedClassDefinition,
        );
    }

    public function dataForMakeCommand(): array
    {
        return [
            'Example' => [
                'inputName' => 'Example',
                'expectedFilename' => 'GraphQL/Schemas/Example.php',
                'expectedClassDefinition' => 'Example implements ConfigConvertible',
            ],
            'ExampleSchema' => [
                'inputName' => 'ExampleSchema',
                'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
                'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
            ],
        ];
    }
}

<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;

use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;

class SchemaConfigMakeCommandTest extends TestCase
{
    use MakeCommandAssertionTrait;

    /**
     * @dataProvider dataForMakeCommand
     */
    public function testCommand(
        string $inputName,
        string $expectedFilename,
        string $expectedClassDefinition
    ): void {
        $this->assertMakeCommand(
            'Schema',
            SchemaConfigMakeCommand::class,
            $inputName,
            $expectedFilename,
            'App\\\\GraphQL\\\\Schemas',
            $expectedClassDefinition,
        );
    }

    public function dataForMakeCommand(): array
    {
        return [
            'Example' => [
                'inputName' => 'Example',
                'expectedFilename' => 'GraphQL/Schemas/Example.php',
                'expectedClassDefinition' => 'Example implements ConfigConvertible',
            ],
            'ExampleSchema' => [
                'inputName' => 'ExampleSchema',
                'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
                'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
            ],
        ];
    }
}

Make code compatible with PHP < 8

Make code compatible with PHP < 8


<?php

abstract class SVGNode {

    protected $parent;
    protected $styles;

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

    public function getStyle($name) {
        return $this->styles[$name];
    }

    public function setStyle($name, $value) {
        $this->styles[$name] = $value;
    }

    public function removeStyle($name) {
        unset($this->styles[$name]);
    }

    public function getComputedStyle($name) {

        $style = null;

        if (isset($this->styles[$name]))
            $style = $this->styles[$name];

        if (($style === null || $style === 'inherit') && isset($this->parent))
            return $this->parent->getComputedStyle($name);

        // 'inherit' is not what we want. Either get the real style, or
        // nothing at all.
        return $style !== 'inherit' ? $style : null;

    }

    public abstract function toXMLString();

    public abstract function draw(SVGRenderingHelper $rh, $scaleX, $scaleY, $offsetX = 0, $offsetY = 0);

    public function __toString() {
        return $this->toXMLString();
    }

}

<?php

abstract class SVGNode {

    protected $parent;
    protected $styles;

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

    public function getStyle($name) {
        return isset($this->styles[$name]) ? $this->styles[$name] : null;
    }

    public function setStyle($name, $value) {
        $this->styles[$name] = $value;
    }

    public function removeStyle($name) {
        unset($this->styles[$name]);
    }

    public function getComputedStyle($name) {

        $style = null;

        if (isset($this->styles[$name]))
            $style = $this->styles[$name];

        if (($style === null || $style === 'inherit') && isset($this->parent))
            return $this->parent->getComputedStyle($name);

        // 'inherit' is not what we want. Either get the real style, or
        // nothing at all.
        return $style !== 'inherit' ? $style : null;

    }

    public abstract function toXMLString();

    public abstract function draw(SVGRenderingHelper $rh, $scaleX, $scaleY, $offsetX = 0, $offsetY = 0);

    public function __toString() {
        return $this->toXMLString();
    }

}

Fix E_NOTICE caused by unset styles

Fix E_NOTICE caused by unset styles


<?php
	require("bin/fw.php");
	define('N', "\n");
	define('BR', "
");
	define('BRN', "
\n");

# plg_visitor
	echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN;

# plg_dump
	$arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants());
	echo dump($arr, TRUE, TRUE).BRN;

# plg_system
	echo 'echo clean_number(\'4f32k91025\'); will output '.clean_number('4f32k91025').BRN;
	echo 'echo '.BRN;

<?php
	require("bin/fw.php");
	define('N', "\n");
	define('BR', "
");
	define('BRN', "
\n");

# plg_visitor
	echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN;

# plg_dump
	$arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants());
	echo dump($arr, TRUE, TRUE).BRN;

# plg_system
	echo 'echo clean_number(\'4f32k91025\'); # will output '.clean_number('4f32k91025').''.BRN;
	echo 'echo decimal_to_fraction(\'.675\'); # will output '.decimal_to_fraction ('.675').''.BRN;

Update ver 0.1 Beta (Build 7) plg_system examples


<!DOCTYPE HTML>
<?php
session_start();
if($_SESSION['errorMessage'] == null)
{
	$_SESSION['errorMessage']="";
}
$uName="";
$pWord="";
?>

		<title>Login</title>
		<meta charset="utf-8" />
		<link rel="stylesheet" type="text/css" href="main.css" />

Login

		<form action="bibliography_management.php" method="post">
		Name:
<input type="text" name="name">

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

		<input id="button" type="submit" name="submit" value="Log-In">
		</form>

		<?php echo $_SESSION['errorMessage']; ?>

		Register

<!DOCTYPE HTML>
<?php
session_start();
if($_SESSION['errorMessage'] == null)
{
	$_SESSION['errorMessage']="";
}
else
{
	$errorMessage = $_SESSION['errorMessage'];
	$_SESSION['errorMessage']="";
}

$uName="";
$pWord="";
?>

		<title>Login</title>
		<meta charset="utf-8" />
		<link rel="stylesheet" type="text/css" href="main.css" />

Login

		<form action="bibliography_management.php" method="post">
		Name:
<input type="text" name="name">

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

		<input id="button" type="submit" name="submit" value="Log-In">
		</form>

		<?php echo $errorMessage; ?>

		Register

Clear the error message after it has been displayed once


<?php
class Kwc_ParagraphsPassword_Component extends Kwc_Paragraphs_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Paragraphs passwordprotected');
        $ret['extConfig'] = 'Kwc_ParagraphsPassword_ExtConfig';
        $ret['ownModel'] = 'Kwf_Component_FieldModel';
        $ret['plugins'][] = 'Kwc_ParagraphsPassword_Plugin_Component';

        $ret['flags']['skipFulltext'] = true;
        return $ret;
    }

    public function getPassword()
    {
        return $this->_getRow()->password;
    }
}

<?php
class Kwc_ParagraphsPassword_Component extends Kwc_Paragraphs_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Paragraphs passwordprotected');
        $ret['extConfig'] = 'Kwc_ParagraphsPassword_ExtConfig';
        $ret['ownModel'] = 'Kwf_Component_FieldModel';
        $ret['plugins']['password'] = 'Kwc_ParagraphsPassword_Plugin_Component';

        $ret['flags']['skipFulltext'] = true;
        return $ret;
    }

    public function getPassword()
    {
        return $this->_getRow()->password;
    }
}

Set key for password plugin

Set key for password plugin


skyLight Configuration

Note: To change your local configuration options, edit the 'application/config/skylight.php' file by hand.

            <?php
                $i = 0;
        foreach ($config_array as $key => $value) {
                if(preg_match('/^skylight_/',$key)) {
                    $i++;
                    if($i % 2 == 0) {
                        $rowclass="even";
                    }
                    else {
                        $rowclass="odd";
                    }
            ?>
            <tr class="<?php echo $rowclass; ?>"><?php echo $key; ?>	<?php
                if(is_array($value)) {
                    ?>
 <?php
                    foreach($value as $key => $value) {
                        ?>
<?php echo $key ?>	<?php echo $value ?>
                                <?php
                    }
                        ?>
 <?php
                }

                else {
                    echo $value;
                }
             ?>

        <?php }
            }
                ?>

Skylight Configuration

Note: To change your local configuration options, edit the 'application/config/skylight.php' file by hand.

            <?php
                $i = 0;
        foreach ($config_array as $key => $value) {
                if(preg_match('/^skylight_/',$key)) {
                    $i++;
                    if($i % 2 == 0) {
                        $rowclass="even";
                    }
                    else {
                        $rowclass="odd";
                    }
            ?>
            <tr class="<?php echo $rowclass; ?>"><?php echo $key; ?>	<?php
                if(is_array($value)) {
                    ?>
 <?php
                    foreach($value as $key => $value) {
                        ?>
<?php echo $key ?>	<?php echo $value ?>
                                <?php
                    }
                        ?>
 <?php
                }

                else {
                    echo $value;
                }
             ?>

        <?php }
            }
                ?>

Add required page div elements

Add required page div elements


<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\Doctrine\QueryBuilder\Filter\ORM;

class Between extends AbstractFilter
{
    public function filter($queryBuilder, $metadata, $option)
    {
        if (isset($option['where'])) {
            if ($option['where'] === 'and') {
                $queryType = 'andWhere';
            } elseif ($option['where'] === 'or') {
                $queryType = 'orWhere';
            }
        }

        if (! isset($queryType)) {
            $queryType = 'andWhere';
        }

        if (! isset($option['alias'])) {
            $option['alias'] = 'row';
        }

        $format = isset($option['format']) ? $option['format'] : null;

        $from = $this->typeCastField($metadata, $option['field'], $option['from'], $format);
        $to = $this->typeCastField($metadata, $option['field'], $option['to'], $format);

        $fromParameter = uniqid('a');
        $toParameter = uniqid('a');

        $queryBuilder->$queryType(
            $queryBuilder
                ->expr()
                ->between(
                    sprintf('%s.%s', $option['alias'], $option['field']),
                    sprintf(':%s', $fromParameter),
                    sprintf(':%s', $toParameter)
                )
        );
        $queryBuilder->setParameter($fromParameter, $from);
        $queryBuilder->setParameter($toParameter, $to);
    }
}

<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\Doctrine\QueryBuilder\Filter\ORM;

class Between extends AbstractFilter
{
    public function filter($queryBuilder, $metadata, $option)
    {
        if (isset($option['where'])) {
            if ($option['where'] === 'and') {
                $queryType = 'andWhere';
            } elseif ($option['where'] === 'or') {
                $queryType = 'orWhere';
            }
        }

        if (! isset($queryType)) {
            $queryType = 'andWhere';
        }

        if (! isset($option['alias'])) {
            $option['alias'] = 'row';
        }

        $format = isset($option['format']) ? $option['format'] : null;

        $from = $this->typeCastField($metadata, $option['field'], $option['from'], $format);
        $to = $this->typeCastField($metadata, $option['field'], $option['to'], $format);

        $fromParameter = uniqid('a1');
        $toParameter = uniqid('a2');

        $queryBuilder->$queryType(
            $queryBuilder
                ->expr()
                ->between(
                    sprintf('%s.%s', $option['alias'], $option['field']),
                    sprintf(':%s', $fromParameter),
                    sprintf(':%s', $toParameter)
                )
        );
        $queryBuilder->setParameter($fromParameter, $from);
        $queryBuilder->setParameter($toParameter, $to);
    }
}

Fix wrong merge parameters with same hash


<?php
function convert_mysql_date_to_php_date($date) {
    if ($date == "0000-00-00") {
        $date = "N/A";
    } else {
        $date = date('d-M-y', strtotime($date));
    }
    return $date;
}

function convert_str_date_to_mysql_date($date) {
    if ($date == "N/A" || $date == "0") {
        $date = "0";
    } else {
        try {
            $date = date('Y-m-d', strtotime($date));
        } catch (Exception $e) {
            $date = "0";
        }
    }
    return $date;
}

?>

<?php
function convert_mysql_date_to_php_date($date) {
    if ($date == "0000-00-00") {
        $date = "N/A";
    } else {
        $date = date('d-M-y', strtotime($date));
    }
    return $date;
}

function convert_str_date_to_mysql_date($date) {
    if ($date == "N/A" || $date == "0") {
        $date = NULL;
    } else {
        try {
            $date = date('Y-m-d', strtotime($date));
        } catch (Exception $e) {
            $date = NULL;
        }
    }
    return $date;
}

?>

Set date to NULL if not present or invalid


<?php

namespace Oro\Bundle\OrganizationBundle\Ownership;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;

/**
 * Default implementation of check owner assignment algorithm
 */
class OwnerAssignmentChecker implements OwnerAssignmentCheckerInterface
{
    /**
     * {@inheritdoc}
     */
    public function hasAssignments($ownerId, $entityClassName, $ownerFieldName, EntityManager $em)
    {
        $findResult = $this->getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, $em)
            ->getQuery()
            ->getArrayResult();

        return !empty($findResult);
    }

    /**
     * Returns a query builder is used to check if assignments exist
     *
     * @param mixed         $ownerId
     * @param string        $entityClassName
     * @param string        $ownerFieldName
     * @param EntityManager $em
     * @return QueryBuilder
     */
    protected function getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, EntityManager $em)
    {
        return $em->getRepository($entityClassName)
            ->createQueryBuilder('entity')
            ->select('owner.id')
            ->innerJoin(sprintf('entity.%s', $ownerFieldName), 'owner')
            ->where('owner.id = ?1')
            ->setParameter(1, $ownerId)
            ->setMaxResults(1);
    }
}

<?php

namespace Oro\Bundle\OrganizationBundle\Ownership;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;

/**
 * Default implementation of check owner assignment algorithm
 */
class OwnerAssignmentChecker implements OwnerAssignmentCheckerInterface
{
    /**
     * {@inheritdoc}
     */
    public function hasAssignments($ownerId, $entityClassName, $ownerFieldName, EntityManager $em)
    {
        $findResult = $this->getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, $em)
            ->getQuery()
            ->getArrayResult();

        return !empty($findResult);
    }

    /**
     * Returns a query builder is used to check if assignments exist
     *
     * @param mixed         $ownerId
     * @param string        $entityClassName
     * @param string        $ownerFieldName
     * @param EntityManager $em
     * @return QueryBuilder
     */
    protected function getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, EntityManager $em)
    {
        return $em->getRepository($entityClassName)
            ->createQueryBuilder('entity')
            ->select('owner.id')
            ->innerJoin(sprintf('entity.%s', $ownerFieldName), 'owner')
            ->where('owner.id = :ownerId')
            ->setParameter('ownerId', $ownerId)
            ->setMaxResults(1);
    }
}

BAP-2874: Disable to delete user if he is used as owner, BAP-2843: it is possible to delete default business unit assigned to users


Update default key to 'locale'.

Update default key to 'locale'.


<?php
// Put the PML into a temp file.
$pmlTempFile = tempnam("/tmp", "PML_IDE");
file_put_contents($pmlTempFile, $_POST["value"]);

// Generate the graphviz file.
$graphvizTempFile = tempnam("/tmp", "pml-studio");
file_put_contents($graphvizTempFile, shell_exec("../thirdparty/traverse/traverse $pmlTempFile"));

$tempFile = tempnam(".", "pml-studio");
shell_exec("sed '2d' $graphvizTempFile > $tempFile && mv $tempFile $graphvizTempFile");

// Generate the image.
$pngTempFile = tempnam("../images", "pml-studio");
file_put_contents($pngTempFile, shell_exec("dot -Tpng $graphvizTempFile"));

// Make it accessible.
chmod($pngTempFile, 0755);

// Return the relative file name of the image.
echo "images/" . basename($pngTempFile);?>

<?php
// Put the PML into a temp file.
$pmlTempFile = tempnam("/tmp", "PML_IDE");
file_put_contents($pmlTempFile, $_POST["value"]);

// Generate the graphviz file.
$graphvizTempFile = tempnam("/tmp", "pml-studio");
file_put_contents($graphvizTempFile, shell_exec("../thirdparty/traverse/traverse $pmlTempFile"));

// The second line in the file causes the filename to be displayed in the image,
// looks messy when the filename is a tempfile generated here, remove the name.
$tempFile = tempnam(".", "pml-studio");
shell_exec("sed '2d' $graphvizTempFile > $tempFile && mv $tempFile $graphvizTempFile");

// Generate the image.
$pngTempFile = tempnam("../images", "pml-studio");
file_put_contents($pngTempFile, shell_exec("dot -Tpng $graphvizTempFile"));

// Make it accessible.
chmod($pngTempFile, 0755);

// Return the relative file name of the image.
echo "images/" . basename($pngTempFile);?>

Add comment where it's probably necessary


<?php

$lang['streams:bootstrap_time.name'] = 'Bootstrap Time Picker';
$lang['streams.format_time.instructions'] = 'Por favor ingrese el formato de hora para mostrar una vez guardado el dato, use formatos de hora php, por defecto usara g:i A';
$lang['streams:bootstrap_time.format'] = 'Formato de hora';

<?php

$lang['streams:bootstrap_time.name'] = 'Seleccionador de Hora';
$lang['streams.format_time.instructions'] = 'Por favor ingrese el formato de hora para mostrar una vez guardado el dato, use formatos de hora php, por defecto usara g:i A';
$lang['streams:bootstrap_time.format'] = 'Formato de hora';

Change the name for spanish

Change the name for spanish


<?php

class Metrodi_Proto {

	protected $thing;

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

	/**
	 * Intercept all function calls so there are no stopping errors.
	 * in DEV mode (_set('env', 'dev')) a trace will be emitted.
	 */
	public function __call($name, $args) {
		//only show proto messages in dev mode
		if (_get('env') != 'dev') {
			return;
		}
		$bt = debug_backtrace();
		$line = $bt[0]['line'];
		$file = $bt[0]['file'];
		$bt = null;
		$parts = explode(DIRECTORY_SEPARATOR, $file);
		$fname = array_pop($parts);
		$file = array_pop($parts).DIRECTORY_SEPARATOR.$fname;
		var_dump("Called: ".$name." against proto object of type: ".$this->thing." from: ".$file." (".$line.").");
		return $this;
	}

	public function __toString() {
		return "Proto object of type: ".$this->thing.PHP_EOL;
	}
}

<?php

class Metrodi_Proto {

	protected $thing;

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

	/**
	 * Intercept all function calls so there are no stopping errors.
	 * in DEV mode (_set('env', 'dev')) a trace will be emitted.
	 */
	public function __call($name, $args) {
		//only show proto messages in dev mode
		if (_get('env') != 'dev') {
			return $this;
		}
		$bt = debug_backtrace();
		if (!isset($bt[0]) ||
		    !array_key_exists('line', $bt[0])) {
			return $this;
		}
		$line = $bt[0]['line'];
		$file = $bt[0]['file'];
		$bt = null;
		$parts = explode(DIRECTORY_SEPARATOR, $file);
		$fname = array_pop($parts);
		$file = array_pop($parts).DIRECTORY_SEPARATOR.$fname;
		echo("Called [".$name."] against proto object of type: ".$this->thing." from: ".$file." (".$line.").\n");
		return $this;
	}

	public function __toString() {
		return "Proto object of type: ".$this->thing.PHP_EOL;
	}
}

Fix some errors in stack trace printing.

Return $this for chaining.


@extends('folio::admin.layout')

<?php
	$settings_title = config('settings.title');
	if($settings_title == '') {
		$settings_title = "Folio";
	}
    $site_title = 'Versions of Item '.$item->id.' | '. $settings_title;
?>

@section('title', 'Versions of Item '.$item->id)

@section('floating.menu')
  	{!! view('folio::partial.c-floating-menu', ['buttons' => [
		  '' => $item->editPath(),
		  ]]) !!}
@stop

@section('content')

            id }}">Return to Item

        @foreach($item->versions->reverse() as $key=>$version)
            <?php
            $date = new Date($version->updated_at);
            $date = ucWords($date->format('F').' '.$date->format('j, Y').$date->format(' H:i:s'));
            ?>

                {{ $date }}

            <textarea>{!! $version->getModel()->text; !!}</textarea>

        @endforeach

@endsection

@extends('folio::admin.layout')

<?php
	$settings_title = config('settings.title');
	if($settings_title == '') {
		$settings_title = "Folio";
	}
    $site_title = 'Versions of Item '.$item->id.' | '. $settings_title;
?>

@section('title', 'Versions of Item '.$item->id)

@section('floating.menu')
  	{!! view('folio::partial.c-floating-menu', ['buttons' => [
		  '' => $item->editPath(),
		  ]]) !!}
@stop

@section('content')

            id }}">Return to Item

        @foreach($item->versions->reverse() as $key=>$version)
            <?php
            $date = new Date($version->updated_at);
            $date = ucWords($date->format('F').' '.$date->format('j, Y').$date->format(' H:i:s'));
            $text_languages = json_decode($version->getModel()->text);
            ?>

                {{ $date }}

            @foreach ($text_languages as $lang => $text)

                {!! $lang !!}

                <textarea>{!! $text !!}</textarea>

            @endforeach

        @endforeach

@endsection

Improve versions page to show plain text of multiple languages.


<?php namespace Orchestra\Foundation\Bootstrap;

use Illuminate\Contracts\Foundation\Application;

class NotifyIfSafeMode
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        $app['events']->listen('orchestra.extension: booted', function () use ($app) {
            if ('on' === $app['session']->get('orchestra.safemode')) {
                $app['orchestra.messages']->extend(function ($messages) {
                    $messages->add('info', trans('orchestra/foundation::response.safe-mode'));
                });
            }
        });
    }
}

<?php namespace Orchestra\Foundation\Bootstrap;

use Illuminate\Contracts\Foundation\Application;

class NotifyIfSafeMode
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if ($app['orchestra.extension.mode']->check()) {
            $app['orchestra.messages']->extend(function ($messages) {
                $messages->add('info', trans('orchestra/foundation::response.safe-mode'));
            });
        }
    }
}

Update checking safe mode notification.

Update checking safe mode notification.

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


<?php
/**
 * CodeIgniter PHP-Development Server Rewrite Rules
 *
 * This script works with the CLI serve command to help run a seamless
 * development server based around PHP's built-in development
 * server. This file simply tries to mimic Apache's mod_rewrite
 * functionality so the site will operate as normal.
 *
 */
// @codeCoverageIgnoreStart
// Avoid this file run when listing commands
if (php_sapi_name() === 'cli')
{
	return;
}

// If we're serving the site locally, then we need
// to let the application know that we're in development mode
$_SERVER['CI_ENVIRONMENT'] = 'development';

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

// Front Controller path - expected to be in the default folder
$fcpath = FCPATH;

// Full path
$path = $fcpath . ltrim($uri, '/');

// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path)))
{
	return false;
}

// Otherwise, we'll load the index file and let
// the framework handle the request from here.
require_once $fcpath . 'index.php';
// @codeCoverageIgnoreEnd

<?php
/**
 * CodeIgniter PHP-Development Server Rewrite Rules
 *
 * This script works with the CLI serve command to help run a seamless
 * development server based around PHP's built-in development
 * server. This file simply tries to mimic Apache's mod_rewrite
 * functionality so the site will operate as normal.
 *
 */
// @codeCoverageIgnoreStart
// Avoid this file run when listing commands
if (php_sapi_name() === 'cli')
{
	return;
}

// If we're serving the site locally, then we need
// to let the application know that we're in development mode
$_SERVER['CI_ENVIRONMENT'] = 'development';

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

// Front Controller path - expected to be in the default folder
$fcpath = realpath(__DIR__ . '/../../../public') . DIRECTORY_SEPARATOR;

// Full path
$path = $fcpath . ltrim($uri, '/');

// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path)))
{
	return false;
}

// Otherwise, we'll load the index file and let
// the framework handle the request from here.
require_once $fcpath . 'index.php';
// @codeCoverageIgnoreEnd

Revert "Fixed a bug where you can not change the path freely"


<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Merchant;

use ActiveCollab\Payments\Common\AddressibleObjectInterface;
use ActiveCollab\Payments\Gateway\GatewayInterface;

interface MerchantInterface extends AddressibleObjectInterface
{
    public function getReference(GatewayInterface $gateway);

    public function getOurReference();
}

<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Merchant;

use ActiveCollab\Payments\Gateway\GatewayInterface;

interface MerchantInterface
{
    public function getReference(GatewayInterface $gateway);

    public function getOurReference();
}

Remove addressible object from merchant interface


<?php
/**
 * Gallery
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Olivier Paroz <galleryapps@oparoz.com>
 *
 * @copyright Olivier Paroz 2016
 */

use \Page\Acceptance\Login;
use \Page\Gallery as GalleryPage;

$I = new AcceptanceTester($scenario);
$I->am('a standard user');
$I->wantTo('load the Gallery app');
$I->lookForwardTo('seeing my holiday pictures');

$loginPage = new Login($I);
$loginPage->login('admin', 'admin');
$loginPage->confirmLogin();

$I->click('.menutoggle');
$I->click('Gallery', '#navigation');
$I->seeCurrentUrlEquals(GalleryPage::$URL);
$I->seeElement(['css' => GalleryPage::$contentDiv]);

<?php
/**
 * Gallery
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Olivier Paroz <galleryapps@oparoz.com>
 *
 * @copyright Olivier Paroz 2016
 */

use \Page\Acceptance\Login;
use \Page\Gallery as GalleryPage;

$I = new AcceptanceTester($scenario);
$I->am('a standard user');
$I->wantTo('load the Gallery app');
$I->lookForwardTo('seeing my holiday pictures');

$loginPage = new Login($I);
$loginPage->login('admin', 'admin');
$loginPage->confirmLogin();

$I->click('Gallery', '#appmenu');
$I->seeCurrentUrlEquals(GalleryPage::$URL);
$I->seeElement(['css' => GalleryPage::$contentDiv]);

Fix the acceptance tests sine we have a fancy new appmenu!

Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>


<?php
/**
 * @author Rizart Dokollari <r.dokollari@gmail.com>
 * @since 12/10/2015
 */

/**
 * Class homePageTest verifies a guest can view all content pertaining to the home page '/'.
 */
class LayoutTest extends TestCase
{

	/** @test */
	public function it_reads_sidebar()
	{
		$this->visit(route('home'))
			->seePageIs(route('home'))
			->see('see('Gazzete')
			->see('DEREE News. 24/7.')
			->see('Latest story.')
			->see('Subtitle')
			->see('Join Our Newsletter');
	}

	/** @test */
	public function it_reads_panel_menu()
	{
		$this->visit(route('home'))
			->seePageIs(route('home'))
			->dontSee('Home')
			->dontSee('Contributors')
			->dontSee('About')
			->dontSee('Contact')
			->dontSee('Articles')
			->dontSee('Categories')
			->dontSee('Tags')
			->dontSee('Favorites')
			->click('')
			->see('Home')
			->see('Contributors')
			->see('About')
			->see('Contact')
			->see('Articles')
			->see('Categories')
			->see('Tags')
			->see('Favorites');
	}
}

<?php
/**
 * @author Rizart Dokollari <r.dokollari@gmail.com>
 * @since 12/10/2015
 */

/**
 * Class homePageTest verifies a guest can view all content pertaining to the home page '/'.
 */
class LayoutTest extends TestCase
{

	/** @test */
	public function it_reads_sidebar()
	{
		$this->visit(route('home'))
			->seePageIs(route('home'))
			->see('<span class="menu-trigger animated fadeInDown"')
			->see('Gazzete')
			->see('DEREE News. 24/7.')
			->see('Latest story.')
			->see('Subtitle')
			->see('Join Our Newsletter');
	}

	/** @test */
	public function it_reads_panel_menu()
	{
		$this->visit(route('home'))
			->see('Home')
			->see('Contributors')
			->see('About')
			->see('Contact')
			->see('Articles')
			->see('Categories')
			->see('Tags')
			->see('Favorites');
	}
}

Verify panelmenu shows expected options.


<?php

class TemplatePreviewRequestHandler
{
	public static function handleRequest()
	{
		$GLOBALS['Session']->requireAccountLevel('Developer');

		Emergence\Dwoo\Engine::respond(implode('/', Site::$pathStack));
	}
}

<?php

class TemplatePreviewRequestHandler
{
    public static $requiredAccountLevel = 'Developer';

    public static function handleRequest()
	{
        if (static::$requiredAccountLevel) {
		    $GLOBALS['Session']->requireAccountLevel(static::$requiredAccountLevel);
        }

		Emergence\Dwoo\Engine::respond(implode('/', Site::$pathStack));
	}
}

Support configuring required account level for template previewing


<?php

namespace Matcher;

use PhpSpec\Exception\Example\FailureException;
use PhpSpec\Matcher\MatcherInterface;
use Symfony\Component\Console\Tester\ApplicationTester;

class ApplicationOutputMatcher implements MatcherInterface
{

    /**
     * Checks if matcher supports provided subject and matcher name.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     *
     * @return Boolean
     */
    public function supports($name, $subject, array $arguments)
    {
        return ($name == 'haveOutput' && $subject instanceof ApplicationTester);
    }

    /**
     * Evaluates positive match.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     */
    public function positiveMatch($name, $subject, array $arguments)
    {
        $expected = $arguments[0];
        if (strpos($subject->getDisplay(), $expected) === false) {
            throw new FailureException(sprintf(
                "Application output did not contain expected '%s'. Actual output:\n'%s'" ,
                $expected,
                $subject->getDisplay()
            ));
        }
    }

    /**
     * Evaluates negative match.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     */
    public function negativeMatch($name, $subject, array $arguments)
    {
        throw new FailureException('Negative application output matcher not implemented');
    }

    /**
     * Returns matcher priority.
     *
     * @return integer
     */
    public function getPriority()
    {
        return 51;
    }
}

<?php

namespace Matcher;

use PhpSpec\Exception\Example\FailureException;
use PhpSpec\Matcher\MatcherInterface;
use Symfony\Component\Console\Tester\ApplicationTester;

class ApplicationOutputMatcher implements MatcherInterface
{

    /**
     * Checks if matcher supports provided subject and matcher name.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     *
     * @return Boolean
     */
    public function supports($name, $subject, array $arguments)
    {
        return ($name == 'haveOutput' && $subject instanceof ApplicationTester);
    }

    /**
     * Evaluates positive match.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     */
    public function positiveMatch($name, $subject, array $arguments)
    {
        $expected = $this->normalise($arguments[0]);
        $actual = $this->normalise($subject->getDisplay());
        if (strpos($actual, $expected) === false) {
            throw new FailureException(sprintf(
                "Application output did not contain expected '%s'. Actual output:\n'%s'" ,
                $expected,
                $subject->getDisplay()
            ));
        }
    }

    private function normalise($string)
    {
        $string = preg_replace('/\([0-9]+ms\)/', '', $string);

        return $string;
    }

    /**
     * Evaluates negative match.
     *
     * @param string $name
     * @param mixed $subject
     * @param array $arguments
     */
    public function negativeMatch($name, $subject, array $arguments)
    {
        throw new FailureException('Negative application output matcher not implemented');
    }

    /**
     * Returns matcher priority.
     *
     * @return integer
     */
    public function getPriority()
    {
        return 51;
    }
}

Remove sensitivity to time warnings in formatter output


<?php

require_once 'app.php';

$result = SmsClient::unserializeInboundMessages();

// Process the inbound message here...

// We'll just save this object:
$fileName = PUSH_LOG_DIRECTORY . '/inbound-message-' . strftime('%Y-%m-%d %H:%M') . '.txt';
$data = print_r($result, true);

file_put_contents($fileName, $data);

// Not needed, but just for testing:
echo 'OK';

<?php

require_once 'app.php';

$result = SmsClient::unserializeInboundMessages();

// Process the inbound message here...

// We'll send a response here:
$message = new SMSRequest();
$message->senderAddress = $result->destinationAddress;
$message->address = $result->senderAddress;
$message->message = 'Thank you for your message (' . $result->message . ')!';

// Initialize the client:
$smsClient = new SmsClient(USERNAME, PASSWORD);

$result = $smsClient->sendSMS($message);

// We'll just save this object:
$fileName = PUSH_LOG_DIRECTORY . '/inbound-message-' . strftime('%Y-%m-%d %H:%M') . '.txt';
$data = print_r($result, true);

file_put_contents($fileName, $data);

// Not needed, but just for testing:
echo 'OK';

Send message on inbound push

Send message on inbound push


<?php

class SomethingDigital_EnterpriseIndexPerf_Model_Changelog extends Enterprise_Index_Model_Changelog
{
    /**
     * Load changelog ids by metadata.
     *
     * This differs from the parent by adding a DISTINCT.
     *
     * @param null|int $currentVersion Version id to stop at.
     * @return int[]
     */
    public function loadByMetadata($currentVersion = null)
    {
        $select = $this->_connection->select()
            ->from(array('changelog' => $this->_metadata->getChangelogName()), array())
            ->where('version_id >= ?', $this->_metadata->getVersionId())
            ->columns(array($this->_metadata->getKeyColumn()))
            ->distinct();

        if ($currentVersion) {
            $select->where('version_id < ?', $currentVersion);
        }

        return $this->_connection->fetchCol($select);
    }
}

<?php

class SomethingDigital_EnterpriseIndexPerf_Model_Changelog extends Enterprise_Index_Model_Changelog
{
    /**
     * Load changelog ids by metadata.
     *
     * This differs from the parent by adding a DISTINCT.
     *
     * @param null|int $currentVersion Version id to stop at.
     * @return int[]
     */
    public function loadByMetadata($currentVersion = null)
    {
        $select = $this->_connection->select()
            ->from(array('changelog' => $this->_metadata->getChangelogName()), array())
            ->where('version_id > ?', $this->_metadata->getVersionId())
            ->columns(array($this->_metadata->getKeyColumn()))
            ->distinct();

        if ($currentVersion) {
            $select->where('version_id <= ?', $currentVersion);
        }

        return $this->_connection->fetchCol($select);
    }
}

Apply changelog versioning fix from 1.14.3.1.

Had thought this looked wrong, but didn't want to alter behavior.


<?php

namespace Backend\Modules\Pages\Tests\Model;

use Backend\Modules\Pages\Engine\Model;

class ModelTest extends \PHPUnit_Framework_TestCase
{
    public function testUrlIsEncoded()
    {
        $this->assertEquals(
            'http://www.google.be/Quote',
            Model::getEncodedRedirectURL('http://www.google.be/Quote')
        );
        $this->assertEquals(
            'http://www.google.be/Quote%22HelloWorld%22',
            Model::getEncodedRedirectURL('http://www.google.be/Quote"HelloWorld"')
        );
        $this->assertEquals(
            'http://www.google.be/Quote%27HelloWorld%27',
            Model::getEncodedRedirectURL("http://www.google.be/Quote'HelloWorld'")
        );
        $this->assertEquals(
            'http://cédé.be/Quote%22HelloWorld%22',
            Model::getEncodedRedirectURL('http://cédé.be/Quote"HelloWorld"')
        );
    }
}

<?php

namespace Backend\Modules\Pages\Tests\Model;

use Backend\Modules\Pages\Engine\Model;
use PHPUnit_Framework_TestCase;

class ModelTest extends PHPUnit_Framework_TestCase
{
    public function testUrlIsEncoded()
    {
        $this->assertEquals(
            'http://www.google.be/Quote',
            Model::getEncodedRedirectURL('http://www.google.be/Quote')
        );
        $this->assertEquals(
            'http://www.google.be/Quote%22HelloWorld%22',
            Model::getEncodedRedirectURL('http://www.google.be/Quote"HelloWorld"')
        );
        $this->assertEquals(
            'http://www.google.be/Quote%27HelloWorld%27',
            Model::getEncodedRedirectURL("http://www.google.be/Quote'HelloWorld'")
        );
        $this->assertEquals(
            'http://cédé.be/Quote%22HelloWorld%22',
            Model::getEncodedRedirectURL('http://cédé.be/Quote"HelloWorld"')
        );
    }
}

Increase minimum php version to5. 6::q

Increase minimum php version to5. 6::q

PHP 5.5 reaches EOL on 10 Jul 2016, after that we no longer support it for security reasons


<?php

$config = Configuration::getInstance();
$config->override('auth_module', 'single');
$config->override('user.default', 'cake');
$config->override('user.default.teams', array(1, 2));

// get the module
$auth = AuthBackend::getInstance();
test_nonnull($auth, "failed to get auth backend");
test_class($auth, 'SingleAuth', "auth backend was of the wrong class");

test_null($auth->getCurrentUserName(), "auth falsely returned a user");
test_true($auth->authUser('cake', 'bees'), 'authentication failed');
test_equal($auth->getCurrentUserName(), 'cake', 'auth returned incorrect user');
test_equal($auth->getCurrentUserTeams(), array(1, 2), "user not in 2 teams as per config file");
$token = $auth->getNextAuthToken();
$auth->deauthUser($token);
test_null($auth->getCurrentUserName(), 'auth did not deauthenticate user');

<?php

$config = Configuration::getInstance();
$config->override('auth_module', 'single');
$config->override('user.default', 'cake');
$config->override('user.default.teams', array(1, 2));
$config->override('user.default.read_only_teams', array());

// get the module
$auth = AuthBackend::getInstance();
test_nonnull($auth, "failed to get auth backend");
test_class($auth, 'SingleAuth', "auth backend was of the wrong class");

test_null($auth->getCurrentUserName(), "auth falsely returned a user");
test_true($auth->authUser('cake', 'bees'), 'authentication failed');
test_equal($auth->getCurrentUserName(), 'cake', 'auth returned incorrect user');
test_equal($auth->getCurrentUserTeams(), array(1, 2), "user not in 2 teams as per config file");
$token = $auth->getNextAuthToken();
$auth->deauthUser($token);
test_null($auth->getCurrentUserName(), 'auth did not deauthenticate user');

Fix test by hiding read-only teams.

Fix test by hiding read-only teams.

This test doesn't want to care about these.

Change-Id: I68a90bcbd88402a99099217e03528e42ffc862ee


		{{ $field_title }}

			<input type="text" value="{{ $formatter->formatShortDate(strtotime($field['value'])) }}"
				data-name="{{ $field['name'] }}" data-type="date"
				data-date-rel="field[{{ $id_language }}][{{ $field['name'] }}]" />
			<input type="hidden" name="field[{{ $id_language }}][{{ $field['name'] }}]"
				value="{{ date('Y-m-d', strtotime($field['value'])) }}" />

		{{ $field_title }}
		@if (array_key_exists('required', $field) && $field['required'] === true)

		@endif

			<input type="text" value="{{ $formatter->formatShortDate(strtotime($field['value'])) }}"
				data-name="{{ $field['name'] }}" data-type="date"
				data-date-rel="field[{{ $id_language }}][{{ $field['name'] }}]" />
			<input type="hidden" name="field[{{ $id_language }}][{{ $field['name'] }}]"
				value="{{ date('Y-m-d', strtotime($field['value'])) }}" />

Add required indicator to admin add field date


<?php

namespace Oro\Bundle\UIBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;

use Twig_Environment;

use Oro\Bundle\UIBundle\View\ScrollData;

class BeforeListRenderEvent extends Event
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    /**
     * @var ScrollData
     */
    protected $scrollData;

    /**
     * @var FormView|null
     */
    protected $formView;

    /**
     * @param \Twig_Environment $environment
     * @param ScrollData $scrollData
     * @param FormView|null $formView
     */
    public function __construct(Twig_Environment $environment, ScrollData $scrollData, FormView $formView = null)
    {
        $this->formView    = $formView;
        $this->scrollData  = $scrollData;
        $this->environment = $environment;
    }

    /**
     * @return \Twig_Environment
     */
    public function getEnvironment()
    {
        return $this->environment;
    }

    /**
     * @return FormView|null
     */
    public function getFormView()
    {
        return $this->formView;
    }

    /**
     * @return ScrollData
     */
    public function getScrollData()
    {
        return $this->scrollData;
    }

    /**
     * @param ScrollData $scrollData
     * @return BeforeListRenderEvent
     */
    public function setScrollData(ScrollData $scrollData)
    {
        $this->scrollData = $scrollData;

        return $this;
    }
}

<?php

namespace Oro\Bundle\UIBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;

use Twig_Environment;

use Oro\Bundle\UIBundle\View\ScrollData;

class BeforeListRenderEvent extends Event
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    /**
     * @var ScrollData
     */
    protected $scrollData;

    /**
     * @var FormView|null
     */
    protected $formView;

    /**
     * @param \Twig_Environment $environment
     * @param ScrollData $scrollData
     * @param FormView|null $formView
     */
    public function __construct(Twig_Environment $environment, ScrollData $scrollData, FormView $formView = null)
    {
        $this->environment = $environment;
        $this->scrollData  = $scrollData;
        $this->formView    = $formView;
    }

    /**
     * @return \Twig_Environment
     */
    public function getEnvironment()
    {
        return $this->environment;
    }

    /**
     * @return FormView|null
     */
    public function getFormView()
    {
        return $this->formView;
    }

    /**
     * @return ScrollData
     */
    public function getScrollData()
    {
        return $this->scrollData;
    }

    /**
     * @param ScrollData $scrollData
     * @return BeforeListRenderEvent
     */
    public function setScrollData(ScrollData $scrollData)
    {
        $this->scrollData = $scrollData;

        return $this;
    }
}

BB-562: Add possibility to inject code into forms and view templates
- CR fixes


<?php
namespace Wisembly\Behat\Extension\Initializer;

use Behat\Behat\Context\Context;
use Behat\Behat\Context\Initializer\ContextInitializer;

use Wisembly\Behat\Extension\Tools\Debug;
use Wisembly\Behat\Extension\Context\WizInterface;

/**
 * Initializes wiz contexts (which should be implemented by all contexts)
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class Wiz implements ContextInitializer
{
    /** @var string */
    private $environment;

    /** @var Debug */
    private $debug;

    /*
     * @param string $environment Environment in which the behat suite is ran
     * @param boolean $debug Is the debug mode activated ?
     */
    public function __construct($environment, Debug $debug)
    {
        $this->debug = $debug;
        $this->environment = (string) $environment;
    }

    /** {@inheritDoc} */
    public function initializeContext(Context $context)
    {
        if (!$context instanceof WizContextInterface) {
            return;
        }

        $context->initializeWiz($this->environment, $this->debug->getStatus());
    }
}

<?php
namespace Wisembly\Behat\Extension\Initializer;

use Behat\Behat\Context\Context;
use Behat\Behat\Context\Initializer\ContextInitializer;

use Wisembly\Behat\Extension\Tools\Debug;
use Wisembly\Behat\Extension\Context\WizInterface;

/**
 * Initializes wiz contexts (which should be implemented by all contexts)
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class Wiz implements ContextInitializer
{
    /** @var string */
    private $environment;

    /** @var Debug */
    private $debug;

    /*
     * @param string $environment Environment in which the behat suite is ran
     * @param boolean $debug Is the debug mode activated ?
     */
    public function __construct($environment, Debug $debug)
    {
        $this->debug = $debug;
        $this->environment = (string) $environment;
    }

    /** {@inheritDoc} */
    public function initializeContext(Context $context)
    {
        if (!$context instanceof WizInterface) {
            return;
        }

        $context->initializeWiz($this->environment, $this->debug->getStatus());
    }
}

Fix a nasty nasty namespace bug

Fix a nasty nasty namespace bug


<?php
include_once("../database/manageProgramEntries.php");

function getSelect2ProgramsList($db) {
    $programs = manageProgramEntries::getAllProgramsFromDatabase($db);

    $programsArrayForSelect2 = array();
    for ($i = 1; $i < count($programs); $i++) {
        $programsArrayForSelect2[$i] = array("id" => $i, "text" => $programs[$i]);
    }

    $programs = json_encode(array_values($programsArrayForSelect2));
    return $programs;
}

<?php
include_once("database/manageProgramEntries.php");

function getSelect2ProgramsList($db) {
    $programs = manageProgramEntries::getAllProgramsFromDatabase($db);

    $programsArrayForSelect2 = array();
    for ($i = 1; $i < count($programs); $i++) {
        $programsArrayForSelect2[$i] = array("id" => $i, "text" => $programs[$i]);
    }

    $programs = json_encode(array_values($programsArrayForSelect2));
    return $programs;
}

Fix path to select2 include

Fix path to select2 include


<?php

function print_header( $embed = false ) {
?>
<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<title>IsValid | Quantify the results of A/B tests</title>

		<!--[if lt IE 9]>
			<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->

		<!-- Fonts -->
		<script type="text/javascript" src="//use.typekit.net/ivm8epx.js"></script>
		<script type="text/javascript">try{Typekit.load();}catch(e){}</script>

		<!-- Bootstrap -->
		<link href="css/bootstrap-compiled.min.css" rel="stylesheet">

		<!-- Local -->
		<script src="static/scripts.min.js"></script>
		<link href="css/isvalid.css" rel="stylesheet">
	<?php if ( $embed ): ?>
		<link href="css/embed.css" rel="stylesheet">
	<?php endif; ?>
	</head>
<?php
}

<?php

function print_header( $embed = false ) {
?>
<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<title>IsValid | Quantify the results of A/B tests</title>

		<!--[if lt IE 9]>
			<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->

		<!-- Bootstrap -->
		<link href="css/bootstrap-compiled.min.css" rel="stylesheet">

		<!-- Local -->
		<link href="css/isvalid.css" rel="stylesheet">
		<script src="static/scripts.min.js"></script>

		<!-- Fonts -->
		<script type="text/javascript" src="//use.typekit.net/ivm8epx.js"></script>
		<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
	<?php if ( $embed ): ?>
		<link href="css/embed.css" rel="stylesheet">
	<?php endif; ?>
	</head>
<?php
}

Load all CSS before JavaScript

Load all CSS before JavaScript


<?php

namespace RadDB;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

<?php

namespace RadDB;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Returns whether is_admin flag is set or not
     */
    public function isAdmin()
    {
        return $this->is_admin;
    }
}

Add function to check admin flag

Add function to check admin flag


<?php

namespace LaVestima\HannaAgency\InfrastructureBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class BaseWebTestCase extends WebTestCase
{
    protected $client;

    public function __construct($name = null, array $data = [], $dataName = '')
    {
        $this->client = static::createClient();

        parent::__construct($name, $data, $dataName);
    }

//    public function setUp()
//    {
//
//    }

    protected function logInAdmin()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'admin',
            'PHP_AUTH_PW'   => 'admin',
        ]);
    }

    protected function logInCustomer()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'customer',
            'PHP_AUTH_PW'   => 'customer',
        ]);
    }

//    protected function logInUser()
//    {
//        $this->client = static::createClient([], [
//            'PHP_AUTH_USER' => 'user',
//            'PHP_AUTH_PW'   => 'user',
//        ]);
//    }

    protected function logInGuest()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'guest',
            'PHP_AUTH_PW'   => 'guest',
        ]);
    }
}

<?php

namespace LaVestima\HannaAgency\InfrastructureBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class BaseWebTestCase extends WebTestCase
{
    protected $client;

    public function __construct($name = null, array $data = [], $dataName = '')
    {
        $this->createNewClient();

        parent::__construct($name, $data, $dataName);
    }

    protected function createNewClient()
    {
        $this->client = static::createClient();
    }

    public function setUp()
    {
        $this->createNewClient();
    }

    protected function logInAdmin()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'admin',
            'PHP_AUTH_PW'   => 'admin',
        ]);
    }

    protected function logInCustomer()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'customer',
            'PHP_AUTH_PW'   => 'customer',
        ]);
    }

//    protected function logInUser()
//    {
//        $this->client = static::createClient([], [
//            'PHP_AUTH_USER' => 'user',
//            'PHP_AUTH_PW'   => 'user',
//        ]);
//    }

    protected function logInGuest()
    {
        $this->client = static::createClient([], [
            'PHP_AUTH_USER' => 'guest',
            'PHP_AUTH_PW'   => 'guest',
        ]);
    }
}

Clear the client before every test

Clear the client before every test


{{-- checkbox with loose false/null/0 checking --}}
@php
$checkValue = data_get($entry, $column['name']);

$checkedIcon = data_get($column, 'icons.checked', 'fa-check-circle');
$uncheckedIcon = data_get($column, 'icons.unchecked', 'fa-circle');

$exportCheckedText = data_get($column, 'labels.checked', 'Yes');
$exportUncheckedText = data_get($column, 'labels.unchecked', 'No');

$icon = $checkValue == false ? $uncheckedIcon : $checkedIcon;
$text = $checkValue == false ? $exportUncheckedText : $exportCheckedText;
@endphp

{{ $text }}

{{-- checkbox with loose false/null/0 checking --}}
@php
$checkValue = data_get($entry, $column['name']);

$checkedIcon = data_get($column, 'icons.checked', 'fa-check-circle');
$uncheckedIcon = data_get($column, 'icons.unchecked', 'fa-circle');

$exportCheckedText = data_get($column, 'labels.checked', trans('backpack::crud.yes'));
$exportUncheckedText = data_get($column, 'labels.unchecked', trans('backpack::crud.no'));

$icon = $checkValue == false ? $uncheckedIcon : $checkedIcon;
$text = $checkValue == false ? $exportUncheckedText : $exportCheckedText;
@endphp

{{ $text }}

Use translation file for check column

Use translation file for check column


<?php
/**
 * This file controls a day view output for iCalendar information.
 */
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
X-WR-CALNAME:<?php echo $this->calendar->name; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:20060803T160007Z
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
	UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR

<?php
/**
 * This file controls a day view output for iCalendar information.
 */
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:UNL_UCBCN//UNL Event Publisher
X-WR-CALNAME:<?php echo $this->calendar->name; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:<?php echo date('Ymd\THis\Z'); ?>
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
	UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR

Add required PRODID to icalendar export, and last modified date.


<?php

namespace actsmart\actsmart;

use actsmart\actsmart\Sensors\SensorInterface;
use actsmart\actsmart\Controllers\ControllerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Response;

class Agent
{
    /** @var  SensorInterface */
    protected $sensors;

    /** @var EventDispatcher */
    protected $dispatcher;

    /** @var  Response */
    protected $http_response = null;

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

    public function addSensor(SensorInterface $sensor)
    {
        $this->sensors[$sensor->getName()] = $sensor;
    }

    /**
     * Makes an infostore a listener to sensor events.
     *
     * @param $sensor
     * @param $infostore
     */
    public function bindSensorToStore($sensor, $store)
    {
        $this->dispatcher->addListener($sensor->getEventName(), array($store, 'store'));
    }

    public function bindSensorToController(SensorInterface $sensor, ControllerInterface $controller)
    {
        $this->dispatcher->addListener($sensor->getEventName(), array($controller, 'execute'));
    }

    public function sensorReceive($sensor_name, $message)
    {
        return $this->sensors[$sensor_name]->receive($message);
    }

    public function setHttpReaction(Response $response)
    {
        $this->http_response = $response;
    }

    public function httpReact()
    {
        if ($this->http_response == null) {
            return new Response('', Response::HTTP_OK, ['content-type' => 'text/html']);
        }
        return $this->http_response;
    }
}

<?php

namespace actsmart\actsmart;

use actsmart\actsmart\Sensors\SensorInterface;
use actsmart\actsmart\Controllers\ControllerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Response;

class Agent
{
    /** @var  SensorInterface */
    protected $sensors;

    /** @var EventDispatcher */
    protected $dispatcher;

    /** @var  Response */
    protected $http_response = null;

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

    public function addSensor(SensorInterface $sensor)
    {
        $this->sensors[$sensor->getKey()] = $sensor;
    }

    /**
     * Makes an infostore a listener to sensor events.
     *
     * @param $sensor
     * @param $infostore
     */
    public function bindSensorToStore($sensor, $store)
    {
        $this->dispatcher->addListener($sensor->getEventName(), array($store, 'store'));
    }

    public function bindSensorToController(SensorInterface $sensor, ControllerInterface $controller)
    {
        $this->dispatcher->addListener($sensor->getEventName(), array($controller, 'execute'));
    }

    public function sensorReceive($sensor_key, $message)
    {
        return $this->sensors[$sensor_key]->receive($message);
    }

    public function setHttpReaction(Response $response)
    {
        $this->http_response = $response;
    }

    public function httpReact()
    {
        if ($this->http_response == null) {
            return new Response('', Response::HTTP_OK, ['content-type' => 'text/html']);
        }
        return $this->http_response;
    }
}

Use getKey for both sensors and actuators


<?php

namespace ProcessWire\GraphQL;

class Cache
{
  private static $store = [];

  public static function &type(string $name, $build = null)
  {
    if (isset(self::$store[$name])) {
      return self::$store[$name];
    }

    if (is_null($build) || !is_callable($build)) {
      throw \Exception('The second argument for Cache::type() should be a callable.');
    }

    self::$store[$name] = Utils::placeholder();
    self::$store[$name] = $build();
    return self::$store[$name];
  }
}

<?php

namespace ProcessWire\GraphQL;

class Cache
{
  private static $store = [];

  public static function &type(string $name, $build = null)
  {
    if (isset(self::$store[$name])) {
      return self::$store[$name];
    }

    if (is_null($build) || !is_callable($build)) {
      throw \Exception('The second argument for Cache::type() should be a callable.');
    }

    self::$store[$name] = Utils::placeholder();
    self::$store[$name] = $build();
    return self::$store[$name];
  }

  public static function clear()
  {
    self::$store = [];
  }
}

Add the ability to clear the cache.

Add the ability to clear the cache.


<?php

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

$secretFile = '../.secret';
$secret = NULL;
if (TRUE === file_exists($secretFile)) {
	$secret = file_get_contents($secretFile);
}
$data = file_get_contents('php://input');

$payload = new \NamelessCoder\Gizzle\Payload($data, $secret);
$payload->loadPlugins('NamelessCoder\\Gizzle');
$payload->run();

<?php

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

$secretFile = '../.secret';
$secret = NULL;
if (TRUE === file_exists($secretFile)) {
	$secret = file_get_contents($secretFile);
}
$data = file_get_contents('php://input');

try {
	$payload = new \NamelessCoder\Gizzle\Payload($data, $secret);
	$payload->loadPlugins('NamelessCoder\\Gizzle');
	$payload->run();
} catch (\RuntimeException $error) {
	echo $error->getMessage() . ' (' . $error->getCode() . ')';
}

Add try-catch in public API

[TASK] Add try-catch in public API


<?php

namespace Nietonfir\Google\ReCaptchaBundle\Validator\Constraints;

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

class ReCaptchaResponseValidator extends ConstraintValidator
{
    private $revisor;

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

    public function validate($value, Constraint $constraint)
    {
        $response = $this->revisor->verify($value);
        if (!$response->isValid()) {
            // If you're using the new 2.5 validation API (you probably are!)
            $this->context->buildViolation($constraint->message)->addViolation();

            // If you're using the old 2.4 validation API
            // $this->context->addViolation(
            //     $constraint->message,
            //     array('%string%' => $value)
            // );
        }
    }
}

<?php

namespace Nietonfir\Google\ReCaptchaBundle\Validator\Constraints;

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

class ReCaptchaResponseValidator extends ConstraintValidator
{
    private $revisor;

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

    public function validate($value, Constraint $constraint)
    {
        $response = $this->revisor->verify($value);
        if (!$response->isValid()) {
            $this->context->buildViolation($constraint->message)->addViolation();
        }
    }
}

Drop the 2.4 validation API comment

Drop the 2.4 validation API comment


<?php

/*
 * This file is part of the Pagerfanta package.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pagerfanta\Adapter;

/**
 * PropelAdapter.
 *
 * @author William DURAND <william.durand1@gmail.com>
 */
class PropelAdapter implements AdapterInterface
{
    private $query;

    /**
     * Constructor.
     */
    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * Returns the query.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * {@inheritdoc}
     */
    public function getNbResults()
    {
        return $this->query->limit(0)->count();
    }

    /**
     * {@inheritdoc}
     */
    public function getSlice($offset, $length)
    {
        return $this->query->limit($length)->offset($offset)->find();
    }
}

<?php

/*
 * This file is part of the Pagerfanta package.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pagerfanta\Adapter;

/**
 * PropelAdapter.
 *
 * @author William DURAND <william.durand1@gmail.com>
 */
class PropelAdapter implements AdapterInterface
{
    private $query;

    /**
     * Constructor.
     */
    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * Returns the query.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * {@inheritdoc}
     */
    public function getNbResults()
    {
        $q = clone $this->getQuery();
        return $q->limit(0)->offset(0)->count();
    }

    /**
     * {@inheritdoc}
     */
    public function getSlice($offset, $length)
    {
        $q = clone $this->getQuery();
        return $q->limit($length)->offset($offset)->find();
    }
}

Fix the offset to 0 for getNbResults and clone queries before modify.


<?php namespace Aedart\Scaffold\Console;

use Aedart\Laravel\Helpers\Traits\Filesystem\FileTrait;
use Aedart\Scaffold\Indexes\IndexBuilder;

/**
 * Index Command
 *
 * TODO... description of command
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
class IndexCommand extends BaseCommand
{
    use FileTrait;

    protected function configure()
    {
        $this
            ->setName('index')
            ->setDescription('TODO');
            //->addArgument('config', InputArgument::REQUIRED, 'Path to the scaffold configuration file')
            //->addOption('output', null, InputOption::VALUE_OPTIONAL, 'Path where to build project or resource', getcwd())
            //->setHelp($this->formatHelp());
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    public function runCommand()
    {
        $builder = new IndexBuilder();

        $builder->build();

        // TODO: Remove this...
        $this->output->success('Index command...');
    }
}

<?php namespace Aedart\Scaffold\Console;

use Aedart\Laravel\Helpers\Traits\Filesystem\FileTrait;
use Aedart\Scaffold\Indexes\IndexBuilder;
use Composer\Factory;
use Symfony\Component\Console\Input\InputOption;

/**
 * Index Command
 *
 * TODO... description of command
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
class IndexCommand extends BaseCommand
{
    use FileTrait;

    protected function configure()
    {
        $this
            ->setName('index')
            ->setDescription('TODO')
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force build a new index file');
            //->addArgument('config', InputArgument::REQUIRED, 'Path to the scaffold configuration file')
            //->addOption('output', null, InputOption::VALUE_OPTIONAL, 'Path where to build project or resource', getcwd())
            //->setHelp($this->formatHelp());
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    public function runCommand()
    {
        $this->output->title('Building index');

        $builder = new IndexBuilder($this->output);

        $builder->build($this->directories(), $this->input->getOption('force'));

        $this->output->success('Indexing completed');
    }

    /**
     * Returns a list of directory paths in which scaffold files
     * are to be searched for, in order to build an index
     *
     * @return string[]
     */
    public function directories()
    {
        $composerConfig = Factory::createConfig(null, getcwd());

        $vendorDir = $composerConfig->get('vendor-dir');
        $globalVendorDir = (Factory::createConfig(null, $composerConfig->get('home')))->get('vendor-dir');

        return [

            // The current working directory of where this command
            // is being executed from
            getcwd() . DIRECTORY_SEPARATOR,

            // The vendor folder inside the current working directory
            $vendorDir,

            // The "global" vendor directory inside the composer home
            $globalVendorDir
        ];
    }
}

Add directories and force option

Add directories and force option

Can now build index files, based on found scaffold files in the
given directories. Also possible to force indexing.


<?php

namespace Studio\Console;

use Studio\Package;
use Studio\Config\Config;
use Studio\Shell\Shell;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Filesystem\Filesystem;

class ScrapCommand extends BaseCommand
{

    protected $config;

    public function __construct(Config $config)
    {
        parent::__construct();

        $this->config = $config;
    }

    protected function configure()
    {
        $this
            ->setName('scrap')
            ->setDescription('Delete a previously created package skeleton')
            ->addArgument(
                'path',
                InputArgument::REQUIRED,
                'The path where the package resides'
            );
    }

    protected function fire()
    {
        $path = $this->input->getArgument('path');

        if ($this->abortDeletion($path)) {
            $this->output->note('Aborted.');
            return;
        }

        $package = Package::fromFolder($path);
        $this->config->removePackage($package);

        $this->output->note('Removing package...');
        $filesystem = new Filesystem;
        $filesystem->remove($path);
        $this->output->success('Package successfully removed.');

        $this->output->note('Dumping autoloads...');
        Shell::run('composer dump-autoload');
        $this->output->success('Autoloads successfully generated.');
    }

    protected function abortDeletion($path)
    {
        return ! $this->output->confirm(
            "<question>Do you really want to scrap the package at $path?</question> ",
            false
        );
    }

}

<?php

namespace Studio\Console;

use Studio\Package;
use Studio\Config\Config;
use Studio\Shell\Shell;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Filesystem\Filesystem;

class ScrapCommand extends BaseCommand
{

    protected $config;

    public function __construct(Config $config)
    {
        parent::__construct();

        $this->config = $config;
    }

    protected function configure()
    {
        $this
            ->setName('scrap')
            ->setDescription('Delete a previously created package skeleton')
            ->addArgument(
                'path',
                InputArgument::REQUIRED,
                'The path where the package resides'
            );
    }

    protected function fire()
    {
        $path = $this->input->getArgument('path');

        if ($this->abortDeletion($path)) {
            $this->output->note('Aborted.');
            return;
        }

        $package = Package::fromFolder($path);
        $this->config->removePackage($package);

        $this->output->note('Removing package...');
        $filesystem = new Filesystem;
        $filesystem->remove($path);
        $this->output->success('Package successfully removed.');

        $this->output->note('Dumping autoloads...');
        Shell::run('composer dump-autoload');
        $this->output->success('Autoloads successfully generated.');
    }

    protected function abortDeletion($path)
    {
        $this->output->caution("This will delete the entire $path folder and all files within.");

        return ! $this->output->confirm(
            "<question>Do you really want to scrap the package at $path?</question> ",
            false
        );
    }

}

Add a big, fat warning message that scrap will delete the entire folder.

Closes #39.


<?php

namespace Luminary\Services\ApiLoader\Loaders;

use Luminary\Services\ApiLoader\Registry\Registrar;

class EntityLoader extends AbstractApiLoader
{
    /**
     * Return the relative path to the directory
     * for auto loading
     *
     * @return string
     */
    public static function path() :string
    {
        return 'Entities';
    }

    /**
     * Initialize a service path by name
     * to include
     *
     * @param \Luminary\Services\ApiLoader\Registry\Registrar $registrar
     */
    protected function register(Registrar $registrar)
    {
        $registrar->registerModelFactories('Database/Factories');
        $registrar->registerMigrations('Database/Migrations');
        $registrar->registerMiddleware('Middleware');
        $registrar->registerPolicies('Policies/PolicyRegistrar.php');
        $registrar->registerSeeders('Database/Seeds');
        $registrar->registerEvents('Events/EventRegistrar.php');
        $registrar->registerMorphMap('Models');

        // Http
        if(config('luminary.dynamic_routing') !== false) {
            $registrar->registerRoutes('Http/routes.php');
            $registrar->registerCustomRoutes('Http/custom-routes.php');
            $registrar->registerRouteMiddleware('Http/Middleware/registry.php');
            $registrar->registerAuthorizer('Http/Requests/Auth.php');
            $registrar->registerSanitizer('Http/Requests/Sanitizer.php');
            $registrar->registerValidators('Http/Requests/Validators');
        }
    }
}

<?php

namespace Luminary\Services\ApiLoader\Loaders;

use Luminary\Services\ApiLoader\Registry\Registrar;

class EntityLoader extends AbstractApiLoader
{
    /**
     * Return the relative path to the directory
     * for auto loading
     *
     * @return string
     */
    public static function path() :string
    {
        return 'Entities';
    }

    /**
     * Initialize a service path by name
     * to include
     *
     * @param \Luminary\Services\ApiLoader\Registry\Registrar $registrar
     */
    protected function register(Registrar $registrar)
    {
        $registrar->registerModelFactories('Database/Factories');
        $registrar->registerMigrations('Database/Migrations');
        $registrar->registerMiddleware('Middleware');
        $registrar->registerPolicies('Policies/PolicyRegistrar.php');
        $registrar->registerSeeders('Database/Seeds');
        $registrar->registerEvents('Events/EventRegistrar.php');
        $registrar->registerMorphMap('Models');

        // Http
        $registrar->registerRoutes('Http/routes.php');
        $registrar->registerCustomRoutes('Http/custom-routes.php');
        $registrar->registerRouteMiddleware('Http/Middleware/registry.php');
        $registrar->registerAuthorizer('Http/Requests/Auth.php');
        $registrar->registerSanitizer('Http/Requests/Sanitizer.php');
        $registrar->registerValidators('Http/Requests/Validators');
    }
}

Set entity loader to autoload Http namespace


<?php

namespace Tests\Feature;

use Tests\TestCase;

class RegisterTest extends TestCase
{
    /** @test */
    public function can_register()
    {
        $this->postJson('/api/register', [
            'name' => 'Test User',
            'email' => 'test@test.app',
            'password' => 'secret',
            'password_confirmation' => 'secret',
        ])
        ->assertSuccessful()
        ->assertJsonStructure(['id', 'name', 'email']);
    }
}

<?php

namespace Tests\Feature;

use Tests\TestCase;

use App\User;

class RegisterTest extends TestCase
{
    /** @test */
    public function can_register()
    {
        $this->postJson('/api/register', [
            'name' => 'Test User',
            'email' => 'test@test.app',
            'password' => 'secret',
            'password_confirmation' => 'secret',
        ])
        ->assertSuccessful()
        ->assertJsonStructure(['id', 'name', 'email']);
    }

    /** @test */
    public function can_not_register_with_existing_email()
    {
        factory(User::class)->create(['email' => 'test@test.app']);

        $this->postJson('/api/register', [
            'name' => 'Test User',
            'email' => 'test@test.app',
            'password' => 'secret',
            'password_confirmation' => 'secret',
        ])
        ->assertStatus(422)
        ->assertJsonValidationErrors(['email']);
    }
}

Test register with existing email

Test register with existing email

Closes #140


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\Http\Middleware\RedirectIfInstalled;

class RedirectIfNotInstalled extends RedirectIfInstalled
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$this->alreadyInstalled() && config('kleis.installer')) {
            return redirect('/install');
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\Http\Middleware\RedirectIfInstalled;

class RedirectIfNotInstalled extends RedirectIfInstalled
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$this->alreadyInstalled() && config('kleis.installer')) {
            return redirect('/install');
        }

        return $next($request);
    }
}

Fix phpdoc in noinstaller middleware

Fix phpdoc in noinstaller middleware


<?php

define("MULTISHIP_API", true);

require_once "include/error.php";
require_once "objects/object.php";
require_once "include/open_api.php";
require_once "include/config.php";

class Multiship
{
  static function init($config = null)
  {
    if ($config == null)
    {
      require_once "config/config.php";
    }
    if (!isset($config) || !isset($config->client_id) || ($config->client_id == ''))
    {
      die(MULTISHIP_ERROR_CONFIG);
    }

    return new Multiship_OpenApi($config);
  }
}

<?php

define("MULTISHIP_API", true);

require_once "include/error.php";
require_once "objects/object.php";
require_once "include/open_api.php";
require_once "include/config.php";

class Multiship
{
  static function init($config = null)
  {
    if ($config == null)
    {
      require "config/config.php";
    }
    if (!isset($config) || !isset($config->client_id) || ($config->client_id == ''))
    {
      die(MULTISHIP_ERROR_CONFIG);
    }

    return new Multiship_OpenApi($config);
  }
}

Change require_once to require for config array loading


<?php

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

namespace Sylius\Bundle\ResourceBundle\Controller;

use Sylius\Component\Resource\Factory\FactoryInterface;
use Symfony\Component\Config\Resource\ResourceInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface NewResourceFactoryInterface
{
    /**
     * @param RequestConfiguration $requestConfiguration
     * @param FactoryInterface $factory
     *
     * @return ResourceInterface
     */
    public function create(RequestConfiguration $requestConfiguration, FactoryInterface $factory);
}

<?php

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

namespace Sylius\Bundle\ResourceBundle\Controller;

use Sylius\Component\Resource\Factory\FactoryInterface;
use Sylius\Component\Resource\Model\ResourceInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface NewResourceFactoryInterface
{
    /**
     * @param RequestConfiguration $requestConfiguration
     * @param FactoryInterface $factory
     *
     * @return ResourceInterface
     */
    public function create(RequestConfiguration $requestConfiguration, FactoryInterface $factory);
}

Fix use statement for doc comment

[ResourceBundle] Fix use statement for doc comment


<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Inspire::class,
    ];

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

<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        // Commands\Inspire::class,
    ];

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

Disable demonstration command If the purpose of the command is to demonstrate, does not become nescessário leave it enabled by default.


<?php namespace net\xp_framework\unittest\util;

use io\{TempFile, IOException};
use util\Properties;

/**
 * Testcase for util.Properties class.
 *
 * @see   xp://net.xp_framework.unittest.util.AbstractPropertiesTest
 * @see   xp://util.Properties#fromFile
 * @test  xp://net.xp_framework.unittest.util.FilesystemPropertySourceTest
 */
class FileBasedPropertiesTest extends AbstractPropertiesTest {

  /** Create a new properties object from a string source */
  protected function newPropertiesFrom(string $source): Properties {
    with ($t= new TempFile()); {
      $t->out()->write($source);
      $t->close();
    }

    return (new Properties())->load($t);
  }

  #[@test]
  public function from_resource() {
    $prop= new Properties($this->getClass()->getPackage()->getResourceAsStream('example.ini')->getURI());
    $this->assertEquals('value', $prop->readString('section', 'key'));
  }

  #[@test, @expect(IOException::class)]
  public function throws_error_when_reading() {
    $p= new Properties('@@does-not-exist.ini@@');
    $p->readString('section', 'key');
  }

  #[@test]
  public function properties_from_same_file_are_equal() {
    $this->assertEquals(new Properties('a.ini'), new Properties('a.ini'));
  }

  #[@test]
  public function properties_from_different_file_are_not_equal() {
    $this->assertNotEquals(new Properties('a.ini'), new Properties('b.ini'));
  }
}

<?php namespace net\xp_framework\unittest\util;

use io\{TempFile, IOException};
use util\Properties;

/**
 * Testcase for util.Properties class.
 *
 * @see   xp://net.xp_framework.unittest.util.AbstractPropertiesTest
 * @see   xp://util.Properties#fromFile
 * @test  xp://net.xp_framework.unittest.util.FilesystemPropertySourceTest
 */
class FileBasedPropertiesTest extends AbstractPropertiesTest {

  /** Create a new properties object from a string source */
  protected function newPropertiesFrom(string $source): Properties {
    with ($t= new TempFile()); {
      $t->out()->write($source);
      $t->close();
    }

    return (new Properties())->load($t);
  }

  #[@test]
  public function from_resource() {
    $prop= new Properties(typeof($this)->getPackage()->getResourceAsStream('example.ini')->getURI());
    $this->assertEquals('value', $prop->readString('section', 'key'));
  }

  #[@test, @expect(IOException::class)]
  public function throws_error_when_reading() {
    $p= new Properties('@@does-not-exist.ini@@');
    $p->readString('section', 'key');
  }

  #[@test]
  public function properties_from_same_file_are_equal() {
    $this->assertEquals(new Properties('a.ini'), new Properties('a.ini'));
  }

  #[@test]
  public function properties_from_different_file_are_not_equal() {
    $this->assertNotEquals(new Properties('a.ini'), new Properties('b.ini'));
  }
}

Use typeof() instead of getClass()

Use typeof() instead of getClass()