<?php
/**
 * This file script is used to provide the data stored for some user
 * in a server side storage.
 *
 * Expects an uid as a POST parameter, returns a file with that name from
 * $userdatapath which has a json ending. The mime type is set accordingly.
 * @uses $userdataPath
 * @see getUserId.php
 * @package user-data
 */

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

/**
 * Uses the common modules config file.
 */
  include "../utils-php/config.php";

  header('Content-type: application/json');
// use POST
  if (isset($_POST['uid']) && trim($_POST['uid']) != "")
// use GET
//  if (isset($_GET['uid']) && trim($_GET['uid']) != "")
  {
    $uid = trim($_POST['uid']);
    $filename = $userdataPath . $uid . ".json";
    if (file_exists($filename))
    {
      readfile($filename);
    }
  }
  else
    print "null";

<?php
/**
 * This file script is used to provide the data stored for some user
 * in a server side storage.
 *
 * Expects an uid as a POST parameter, returns a file with that name from
 * $userdatapath which has a json ending. The mime type is set accordingly.
 * @uses $userdataPath
 * @see getUserId.php
 * @package user-data
 */

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

/**
 * Uses the common modules config file.
 */
  include "../utils-php/config.php";

  header('Content-type: application/json');
// use POST
if (isset($_POST['uid']) && trim($_POST['uid']) != "") {
// use GET
//  if (isset($_GET['uid']) && trim($_GET['uid']) != "")
    $uid = trim($_POST['uid']);
    $filename = $userdataPath . $uid . ".json";
    if (file_exists($filename)) {
        readfile($filename);
    } else {
        print "false";
    }
} else {
    print "null";
}

Return something to identify file not found.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CandidacyStep1Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', array('required' => true))
        	    ->add('lastname', 'text', array('required' => true))
        	    ->add('dni', 'text', array('required' => true))
        	    ->add('email', 'email', array('required' => true))
        	    ->add('province', 'text', array('required' => true))
        	    ->add('town', 'text', array('required' => true))
        	    ->add('phone', 'text', array('required' => true))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class CandidacyStep1Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', array(
        				'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
        	    ->add('lastname', 'text', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
        	    ->add('dni', 'text', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
        	    ->add('email', 'email', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        					new Assert\Email(),
        				)))
        	    ->add('province', 'text', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
        	    ->add('town', 'text', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
        	    ->add('phone', 'text', array(
        	    		'required' => true,
        				'constraints' => array(
        					new Assert\NotBlank(),
        				)))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add contrainst to candidacy step 1 type form


All GOV.UK blogs

All GOV.UK blog posts

GOV.UK

All departments

All policies

Cookies

Accessibility statement

Add link to a11y statement

Add link to a11y statement

This is a legal requirement for the client.

Resolves: https://dxw.zendesk.com/agent/tickets/10049
Resolves: https://trello.com/c/SJFUZtxT


<?php
if (!defined('InternalAccess')) exit('{"Status": 0,"ErrorMessage": "403"}');
?>
{
	"Status": 1,
	"Page": "<?php echo $Page;?>",
	"TotalPage": "<?php echo $TotalPage;?>",
	"IsFavorite": "<?php echo $CurUserID?$IsFavorite:0;?>",
	"TopicInfo" : <?php echo json_encode($Topic); ?>,
	"PostsArray": <?php echo json_encode($PostsArray);?>
}

<?php
if (!defined('InternalAccess')) exit('{"Status": 0,"ErrorMessage": "403"}');
foreach($PostsArray as $key => $Post)
{
	$PostsArray['PostFloor'] = ($Page-1) * $Config['PostsPerPage'] + $key;
}
?>
{
	"Status": 1,
	"Page": "<?php echo $Page;?>",
	"TotalPage": "<?php echo $TotalPage;?>",
	"IsFavorite": "<?php echo $CurUserID?$IsFavorite:0;?>",
	"TopicInfo" : <?php echo json_encode($Topic); ?>,
	"PostsArray": <?php echo json_encode($PostsArray);?>
}

Add more information to Topic API.

Add more information to Topic API.


<?php

namespace Parable\Tests\Components\ORM;

class Base extends \Parable\Tests\Base
{
    /** @var \Parable\ORM\Database */
    protected $database;

    /** @var \Parable\Filesystem\Path */
    protected $path;

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

        $this->database = \Parable\DI\Container::get(\Parable\ORM\Database::class);
        $this->path     = \Parable\DI\Container::get(\Parable\Filesystem\Path::class);

        if (!extension_loaded('sqlite3')) {
            $this->markTestSkipped('sqlite3 is not available');
        }

        $this->database->setType(\Parable\ORM\Database::TYPE_SQLITE);
        $this->database->setLocation(\Parable\ORM\Database::LOCATION_SQLITE_MEMORY);

        $sql = file_get_contents($this->path->getDir('tests/db/test-setup.sql'));
        $this->database->getInstance()->exec($sql);
    }

    protected function tearDown()
    {
        parent::tearDown();

        $sql = file_get_contents($this->path->getDir('tests/db/test-teardown.sql'));
        $this->database->getInstance()->exec($sql);
    }
}

<?php

namespace Parable\Tests\Components\ORM;

class Base extends \Parable\Tests\Base
{
    /** @var \Parable\ORM\Database */
    protected $database;

    /** @var \Parable\Filesystem\Path */
    protected $path;

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

        $this->skipIfSqliteNotAvailable();

        $this->database = \Parable\DI\Container::get(\Parable\ORM\Database::class);
        $this->path     = \Parable\DI\Container::get(\Parable\Filesystem\Path::class);

        $this->database->setType(\Parable\ORM\Database::TYPE_SQLITE);
        $this->database->setLocation(\Parable\ORM\Database::LOCATION_SQLITE_MEMORY);

        $sql = file_get_contents($this->path->getDir('tests/db/test-setup.sql'));
        $this->database->getInstance()->exec($sql);
    }

    protected function skipIfSqliteNotAvailable()
    {
        if (!extension_loaded('sqlite33')) {
            $this->markTestSkipped('sqlite3 is not available');
        }
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->skipIfSqliteNotAvailable();

        $sql = file_get_contents($this->path->getDir('tests/db/test-teardown.sql'));
        $this->database->getInstance()->exec($sql);
    }
}

Make sure all ORM-related tests are skipped if sqlite3 isn't available.


<?php

namespace Concrete\Core\Block\Command;

use Concrete\Core\Block\Block;
use Concrete\Core\Block\Command\DeleteBlockCommand;
use Concrete\Core\Page\Page;

class AddAliasDefaultsBlockCommandHandler
{

    public function __invoke(AddAliasDefaultsBlockCommand $command)
    {
        $page = Page::getByID($command->getPageID(), $command->getCollectionVersionID());
        if ($page && !$page->isError()) {
            $mc = Page::getByID($command->getOriginalPageID(), $command->getOriginalCollectionVersionID());
            if ($mc && !$mc->isError()) {
                $b = Block::getByID($command->getOriginalBlockID(), $mc, $command->getOriginalAreaHandle());
                if ($b) {
                    $b->alias($page);
                }
            }
        }
    }

}

<?php

namespace Concrete\Core\Block\Command;

use Concrete\Core\Block\Block;
use Concrete\Core\Block\Command\DeleteBlockCommand;
use Concrete\Core\Page\Page;

class AddAliasDefaultsBlockCommandHandler
{

    public function __invoke(AddAliasDefaultsBlockCommand $command)
    {
        $page = Page::getByID($command->getPageID(), $command->getCollectionVersionID());
        if ($page && !$page->isError()) {
            $mc = Page::getByID($command->getOriginalPageID(), $command->getOriginalCollectionVersionID());
            if ($mc && !$mc->isError()) {
                $b = Block::getByID($command->getOriginalBlockID(), $mc, $command->getOriginalAreaHandle());
                if ($b) {
                    $bt = $b->getBlockTypeObject();
                    if ($bt->isCopiedWhenPropagated()) {
                        $b->duplicate($page, true);
                    } else {
                        $b->alias($page);
                    }
                }
            }
        }
    }

}

Duplicate block instance if we should copy it instead of aliasing from master collection


<?php

Director::addRules(50, array(
	WorldpayPayment_Handler::$URLSegment . '/$Action/$ID' => 'WorldpayPayment_Handler',
	PayPalPayment_Handler::$URLSegment . '/$Action/$ID' => 'PayPalPayment_Handler',
	'harness/$Action/$Class/$ID' => 'DPSHarness',
));

Object::add_extension('Member', 'PayerHavingReceipt');

?>

<?php

Director::addRules(50, array(
	WorldpayPayment_Handler::$URLSegment . '/$Action/$ID' => 'WorldpayPayment_Handler',
	PayPalPayment_Handler::$URLSegment . '/$Action/$ID' => 'PayPalPayment_Handler',
	'harness/$Action/$Class/$ID' => 'Harness',
));

Object::add_extension('Member', 'PayerHavingReceipt');

?>

APICHANGE: Rename DPSHarness class to Harness and move it out from DPSPayment, use it as a Harness general interface


<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * @Flow\Inject
     * @var BaseUriProvider
     */
    protected $baseUriProvider;

    /**
     * @Flow\Inject
     * @var ServerRequestFactoryInterface
     */
    protected $serverRequestFactory;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
     *
     * @return ServerRequestInterface
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if ($requestHandler instanceof HttpRequestHandlerInterface) {
            return $requestHandler->getHttpRequest();
        }
        try {
            $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
        } catch (Exception $e) {
            $baseUri = 'http://localhost';
        }
        return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
    }
}

<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
 *
 * Note: Naturally this class is not being used explicitly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * @Flow\Inject
     * @var BaseUriProvider
     */
    protected $baseUriProvider;

    /**
     * @Flow\Inject
     * @var ServerRequestFactoryInterface
     */
    protected $serverRequestFactory;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
     *
     * @return ServerRequestInterface
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if ($requestHandler instanceof HttpRequestHandlerInterface) {
            return $requestHandler->getHttpRequest();
        }
        try {
            $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
        } catch (Exception $e) {
            $baseUri = 'http://localhost';
        }
        return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
    }
}

Add comment about Provider not being used in userland code


<?php
require '../www/config.php';
require '../util.php';

function update_req($reqid, $status)
{
    $query = "
        UPDATE requests
        SET status='$status'
        WHERE
            reqid='$reqid'
            AND curr_type='BTC'
        ";
    do_query($query);
}

$query = "
    SELECT
        requests.reqid AS reqid,
        uid,
        TRUNCATE(amount, -6) AS amount,
        addy
    FROM requests
    JOIN bitcoin_requests
    ON requests.reqid=bitcoin_requests.reqid
    WHERE
        req_type='WITHDR'
        AND status='VERIFY'
        AND curr_type='BTC'
    ";
$result = do_query($query);
while ($row = mysql_fetch_assoc($result)) {
    $reqid = $row['reqid'];
    $uid = $row['uid'];
    $amount = $row['amount'];
    $addy = $row['addy'];

    update_req($reqid, "PROCES");
    $bitcoin = connect_bitcoin();
    $bitcoin->sendfrom("", $addy, $amount);
    update_req($reqid, "FINAL");
}

?>

<?php
require '../www/config.php';
require '../util.php';

function update_req($reqid, $status)
{
    $query = "
        UPDATE requests
        SET status='$status'
        WHERE
            reqid='$reqid'
            AND curr_type='BTC'
        ";
    do_query($query);
}

$query = "
    SELECT
        requests.reqid AS reqid,
        uid,
        TRUNCATE(amount, -6) AS amount,
        addy
    FROM requests
    JOIN bitcoin_requests
    ON requests.reqid=bitcoin_requests.reqid
    WHERE
        req_type='WITHDR'
        AND status='VERIFY'
        AND curr_type='BTC'
    ";
$result = do_query($query);
$bitcoin = connect_bitcoin();
while ($row = mysql_fetch_assoc($result)) {
    $reqid = $row['reqid'];
    $uid = $row['uid'];
    $amount = $row['amount'];
    $addy = $row['addy'];

    $reserve_needed = gmp_add($amount, '1000000000');
    if (gmp_cmp($bitcoin->getbalance(""), $reserve_needed) >= 1)
    {
        update_req($reqid, "PROCES");
        $bitcoin->sendfrom("", $addy, $amount);
        update_req($reqid, "FINAL");
    }
}

?>

Use a reserve for withdrawing bitcoins.

Use a reserve for withdrawing bitcoins.


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DataProviderTestSuite extends TestSuite
{
    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @param string[] $dependencies
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;

        foreach ($this->tests as $test) {
            if (!$test instanceof TestCase) {
                continue;
            }

            $test->setDependencies($dependencies);
        }
    }

    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    public function hasDependencies(): bool
    {
        return \count($this->dependencies) > 0;
    }

    /**
     * Returns the size of the each test created using the data provider(s)
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function getSize(): int
    {
        [$className, $methodName] = \explode('::', $this->getName());

        /* @psalm-suppress ArgumentTypeCoercion */
        return TestUtil::getSize($className, $methodName);
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DataProviderTestSuite extends TestSuite
{
    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @param string[] $dependencies
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;

        foreach ($this->tests as $test) {
            if (!$test instanceof TestCase) {
                continue;
            }

            $test->setDependencies($dependencies);
        }
    }

    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    public function hasDependencies(): bool
    {
        return \count($this->dependencies) > 0;
    }

    /**
     * Returns the size of the each test created using the data provider(s)
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function getSize(): int
    {
        [$className, $methodName] = \explode('::', $this->getName());

        /** @psalm-suppress ArgumentTypeCoercion */
        return TestUtil::getSize($className, $methodName);
    }
}

Revert "Last codestyle fix (I hope)"

Revert "Last codestyle fix (I hope)"

This reverts commit 79c42c9bff7390fbc649578b89dcbef93633f33c.


<?php declare(strict_types=1);
namespace Phan\Language\Type;

final class CallableType extends NativeType
{
    /** @phan-override */
    const NAME = 'callable';

    /**
     * @return bool
     * True if this type is a callable or a Closure.
     */
    public function isCallable() : bool
    {
        return true;
    }
}

<?php declare(strict_types=1);
namespace Phan\Language\Type;

use Phan\Language\Type;

final class CallableType extends NativeType
{
    /** @phan-override */
    const NAME = 'callable';

    /**
     * @return bool
     * True if this type is a callable or a Closure.
     */
    public function isCallable() : bool
    {
        return true;
    }

    protected function canCastToNonNullableType(Type $type) : bool
    {
        // CallableDeclarationType is not a native type, we check separately here
        return parent::canCastToNonNullableType($type) || $type instanceof CallableDeclarationType;
    }
}

Allow callable():T to cast to callable

Allow callable():T to cast to callable


<?php
final class Db
{
    protected static $_instances = Array();

    public static function factory($driver = Null, $config)
    {
        $driver = isset($driver) ? $driver : App::instance()->config['database']['driver'];

        if (!isset(self::$_instances[$driver])) {
            include_once(App::instance()->drivers.'db/'.(strtolower($driver)).'.php');

            $class = ucwords(strtolower($driver)).'Db';
            self::$_instances[$driver] = new $class($config);
        }

        return self::$_instances[$driver];
    }
}

<?php
final class Db
{
    protected static $_instances = Array();

    public static function factory($driver = Null, $config)
    {
        $driver = isset($driver) ? $driver : App::instance()->config['database']['driver'];

        $instanceName = $driver . ':' . $config['host'] . ':' . $config['port'];

        if (!isset(self::$_instances[$instanceName])) {
            include_once(App::instance()->drivers.'db/'.(strtolower($driver)).'.php');

            $class = ucwords(strtolower($driver)).'Db';
            self::$_instances[$instanceName] = new $class($config);
        }

        return self::$_instances[$instanceName];
    }
}

Allow to have separate DB instances for each server


<?php
namespace Concrete\Tests\Core\Routing;

use PHPUnit_Framework_TestCase;
use Concrete\Core\Support\Facade\Application;

class CheckRoutesTest extends PHPUnit_Framework_TestCase
{
    public function routeDestinationProvider()
    {
        $app = Application::getFacadeApplication();
        $config = $app->make('config');
        $routes = $config->get('app.routes');
        $result = [];
        foreach ($routes as $path => $data) {
            if (is_array($data) && isset($data[0]) && is_string($data[0]) && $data[0] !== '') {
                $result[] = [$path, $data[0]];
            }
        }

        return $result;
    }

    /**
     * @dataProvider routeDestinationProvider
     */
    public function testRouteDestination($path, $callable)
    {
        if (preg_match('/^(.+)::(__construct)$/', $callable, $m)) {
            $this->assertTrue(class_exists($m[1], true), "Invalid route for path $path: $callable");
        } else {
            $this->assertTrue(is_callable($callable), "Invalid route for path $path: $callable");
        }
    }
}

<?php
namespace Concrete\Tests\Core\Routing;

use Concrete\Core\Application\Application;
use Concrete\Core\Support\Facade\Application as ApplicationFacade;
use PHPUnit_Framework_TestCase;

class CheckRoutesTest extends PHPUnit_Framework_TestCase
{
    public function routeDestinationProvider()
    {
        $app = ApplicationFacade::getFacadeApplication();
        $config = $app->make('config');
        $routes = $config->get('app.routes');
        $result = [];
        foreach ($routes as $path => $data) {
            if (is_array($data) && isset($data[0]) && is_string($data[0]) && $data[0] !== '') {
                $result[] = [$app, $path, $data[0]];
            }
        }

        return $result;
    }

    /**
     * @dataProvider routeDestinationProvider
     *
     * @param Application $app
     * @param mixed $path
     * @param mixed $callable
     */
    public function testRouteDestination(Application $app, $path, $callable)
    {
        $checked = false;
        if (preg_match('/^([^:]+)::([^:]+)$/', $callable, $m)) {
            $class = $m[1];
            $method = $m[2];
            if ($method === '__construct') {
                $this->assertTrue(class_exists($m[1], true), "Invalid route for path $path: $callable");
                $checked = true;
            }
            elseif (interface_exists($class, true)) {
                $this->assertTrue(method_exists($class, $method), "Invalid route for path $path: $callable");
                $this->assertTrue($app->bound($class), "Invalid route for path $path: $callable");
                $checked = true;
            }
        }
        if ($checked === false) {
            $this->assertTrue(is_callable($callable), "Invalid route for path $path: $callable");
        }
    }
}

Check route pointing to bound interfaces


<?php namespace Wardrobe;

class Post extends \Eloquent {

	/**
	 * The table associated with the model.
	 *
	 * @var string
	 */
	protected $table = 'posts';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = array('title', 'slug', 'content');

	/**
	 * Tags Relationship
	 * @return Relationship
	 */
	public function tags()
  {
		return $this->hasMany('\Wardrobe\Tag', 'post_id');
	}
}

<?php namespace Wardrobe;

class Post extends \Eloquent {

	/**
	 * The table associated with the model.
	 *
	 * @var string
	 */
	protected $table = 'posts';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = array('title', 'slug', 'content', 'active');

	/**
	 * Tags Relationship
	 * @return Relationship
	 */
	public function tags()
  {
		return $this->hasMany('\Wardrobe\Tag', 'post_id');
	}
}

Add active to post fillable.

Add active to post fillable.


<?php
define('APP_ENV', 'UNIT_TESTS');
require(__DIR__.'/../core/app-load.php');

<?php
define('APP_ENV', 'UNIT_TESTS');
require(__DIR__.'/../app/core/app-load.php');

Fix path for app-load in tests

Fix path for app-load in tests


<?php namespace Nwidart\Modules\Tests;

use Nwidart\Modules\LaravelModulesServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class BaseTestCase extends OrchestraTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->setUpDatabase();
    }

    protected function getPackageProviders($app)
    {
        return [
            LaravelModulesServiceProvider::class,
        ];
    }

    /**
     * Set up the environment.
     *
     * @param \Illuminate\Foundation\Application $app
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', array(
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
        ));
    }

    protected function setUpDatabase()
    {
        $this->resetDatabase();
    }

    protected function resetDatabase()
    {
        file_put_contents($this->getTempDirectory().'/database.sqlite', null);
    }

    private function getTempDirectory()
    {
        return __DIR__ . '/temp';
    }
}

<?php namespace Nwidart\Modules\Tests;

use Nwidart\Modules\LaravelModulesServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class BaseTestCase extends OrchestraTestCase
{
    public function setUp()
    {
        parent::setUp();

        // $this->setUpDatabase();
    }

    private function resetDatabase()
    {
        $this->artisan('migrate:reset', [
            '--database' => 'sqlite',
        ]);
    }

    protected function getPackageProviders($app)
    {
        return [
            LaravelModulesServiceProvider::class,
        ];
    }

    /**
     * Set up the environment.
     *
     * @param \Illuminate\Foundation\Application $app
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', array(
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
        ));
    }

    protected function setUpDatabase()
    {
        $this->resetDatabase();
    }
}

Disable database setup for now

Disable database setup for now


<?php

namespace Oro\Bundle\DataGridBundle\Extension\Formatter\Property;

use Symfony\Component\Routing\RouterInterface;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface;
use Oro\Bundle\UIBundle\Twig\Environment;

class LinkProperty extends UrlProperty
{
    const TEMPLATE = 'OroDataGridBundle:Extension:Formatter/Property/linkProperty.html.twig';

    /**
     * @var Environment
     */
    protected $twig;

    /**
     * @param RouterInterface $router
     * @param Environment     $twig
     */
    public function __construct(RouterInterface $router, Environment $twig)
    {
        $this->router = $router;
        $this->twig = $twig;
    }

    /**
     * {@inheritdoc}
     */
    public function getRawValue(ResultRecordInterface $record)
    {
        $label = null;

        try {
            $label = $record->getValue($this->getOr(self::DATA_NAME_KEY) ?: $this->get(self::NAME_KEY));
        } catch (\LogicException $e) {
        }

        return $this->twig
            ->loadTemplate(self::TEMPLATE)
            ->render(
                [
                    'url'   => parent::getRawValue($record),
                    'label' => $label
                ]
            );
    }
}

<?php

namespace Oro\Bundle\DataGridBundle\Extension\Formatter\Property;

use Symfony\Component\Routing\RouterInterface;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface;
use Oro\Bundle\UIBundle\Twig\Environment;

class LinkProperty extends UrlProperty
{
    const TEMPLATE = 'OroDataGridBundle:Extension:Formatter/Property/linkProperty.html.twig';

    /**
     * @var Environment
     */
    protected $twig;

    /**
     * @param RouterInterface $router
     * @param Environment     $twig
     */
    public function __construct(RouterInterface $router, Environment $twig)
    {
        $this->router = $router;
        $this->twig = $twig;
    }

    /**
     * {@inheritdoc}
     */
    public function getRawValue(ResultRecordInterface $record)
    {
        $label = null;

        try {
            $label = $record->getValue($this->getOr(self::DATA_NAME_KEY) ?: $this->get(self::NAME_KEY));

            // if the foreign object doesn't exist there is no link possible
            if (!$label) return "";
        } catch (\LogicException $e) {
        }

        return $this->twig
            ->loadTemplate(self::TEMPLATE)
            ->render(
                [
                    'url'   => parent::getRawValue($record),
                    'label' => $label
                ]
            );
    }
}

Return empty link if no foreign object

Return empty link if no foreign object


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\FirewallEntryPointBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;

class EntryPointStub implements AuthenticationEntryPointInterface
{
    const RESPONSE_TEXT = '2be8e651259189d841a19eecdf37e771e2431741';

    public function start(Request $request, AuthenticationException $authException = null): Response
    {
        return new Response(self::RESPONSE_TEXT);
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\FirewallEntryPointBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;

class EntryPointStub implements AuthenticationEntryPointInterface
{
    public const RESPONSE_TEXT = '2be8e651259189d841a19eecdf37e771e2431741';

    public function start(Request $request, AuthenticationException $authException = null): Response
    {
        return new Response(self::RESPONSE_TEXT);
    }
}

Apply "visibility_required" CS rule to constants

php-cs-fixer fix --rules='{"visibility_required": ["property", "method", "const"]}'


<?php

declare(strict_types = 1);

namespace Helldar\Helpers\Tests;

use GrahamCampbell\TestBench\AbstractTestCase;
use Helldar\Helpers\Support\Images;

class ImagesTest extends AbstractTestCase
{
    public function testImageOrDefault()
    {
        $no_image = '/no-image.jpg';

        $this->assertEquals($no_image, (new Images('unknown.txt'))->imageOrDefault($no_image));
        $this->assertEquals(null, (new Images('unknown.txt'))->imageOrDefault());
    }
}

<?php

declare(strict_types = 1);

namespace Helldar\Helpers\Tests;

use GrahamCampbell\TestBench\AbstractTestCase;
use Helldar\Helpers\Support\Images;

class ImagesTest extends AbstractTestCase
{
    public function testImageOrDefault()
    {
        $no_image = '/no-image.jpg';

        $this->assertEquals($no_image, (new Images('unknown.txt'))->imageOrDefault($no_image));
        $this->assertEquals(null, (new Images('unknown.txt'))->imageOrDefault());

        $this->assertEquals(null, (new Images('http://u.loc/unknown.txt'))->imageOrDefault());
        $this->assertEquals($no_image, (new Images('http://u.loc/unknown.txt'))->imageOrDefault($no_image));
    }
}

Add test rules for Images

Add test rules for Images


<?php

namespace Berrybird\Cerberus\Credential;

/**
 * Compares two credentials in a length-constant time.
 *
 * @link  https://crackstation.net/hashing-security.htm?=rd#slowequals
 *
 * @package    Berrybird\Cerberus\Credential
 * @copyright  Copyright (C) 2011-2014 Miodrag Tokić
 * @license    New BSD
 */
class SlowCredentialMatcher implements CredentialMatcher
{
    /**
     * {@inheritdoc}
     */
    public function equals($credential1, $credential2)
    {
        $diff = strlen($credential1) ^ strlen($credential2);

        for ($i = 0; $i < strlen($credential1) && $i < strlen($credential2); $i++) {
            $diff |= ord($credential1[$i]) ^ ord($credential2[$i]);
        }

        return $diff === 0;
    }
}

<?php

namespace Berrybird\Cerberus\Credential;

/**
 * Compares two credentials in a length-constant time.
 *
 * @see  https://crackstation.net/hashing-security.htm?=rd#slowequals
 *
 * @package    Berrybird\Cerberus\Credential
 * @copyright  Copyright (C) 2011-2014 Miodrag Tokić
 * @license    New BSD
 */
class SlowCredentialMatcher implements CredentialMatcher
{
    /**
     * {@inheritdoc}
     */
    public function equals($credential1, $credential2)
    {
        $diff = strlen($credential1) ^ strlen($credential2);

        for ($i = 0; $i < strlen($credential1) && $i < strlen($credential2); $i++) {
            $diff |= ord($credential1[$i]) ^ ord($credential2[$i]);
        }

        return $diff === 0;
    }
}

Replace @link with @see PHPDoc tag

Replace @link with @see PHPDoc tag

As per proposed PSR-5, usage of @see PHPDoc tag is recommended instead
of @link PHPDoc tag.


<?php

namespace Illuminate\Support\Facades;

/**
 * @method static void compile($path = null)
 * @method static string getPath()
 * @method static void setPath($path)
 * @method static string compileString($value)
 * @method static string stripParentheses($expression)
 * @method static void extend(callable $compiler)
 * @method static array getExtensions()
 * @method static void if($name, callable $callback)
 * @method static bool check($name, ...$parameters)
 * @method static void component($path, $alias = null)
 * @method static void include($path, $alias = null)
 * @method static void directive($name, callable $handler)
 * @method static array getCustomDirectives()
 * @method static void setEchoFormat($format)
 * @method static void withDoubleEncoding()
 * @method static void withoutDoubleEncoding()
 *
 * @see \Illuminate\View\Compilers\BladeCompiler
 */
class Blade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'blade.compiler';
    }
}

<?php

namespace Illuminate\Support\Facades;

/**
 * @method static void compile(string|null $path = null)
 * @method static string getPath()
 * @method static void setPath(string $path)
 * @method static string compileString(string $value)
 * @method static string stripParentheses(string $expression)
 * @method static void extend(callable $compiler)
 * @method static array getExtensions()
 * @method static void if(string $name, callable $callback)
 * @method static bool check(string $name, array ...$parameters)
 * @method static void component(string $path, string|null $alias = null)
 * @method static void include(string $path, string|null $alias = null)
 * @method static void directive(string $name, callable $handler)
 * @method static array getCustomDirectives()
 * @method static void setEchoFormat(string $format)
 * @method static void withDoubleEncoding()
 * @method static void withoutDoubleEncoding()
 *
 * @see \Illuminate\View\Compilers\BladeCompiler
 */
class Blade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'blade.compiler';
    }
}

Add type-hints to Artisan Facade methods props


<?php

namespace Harp\Core\Test\Repo;

use Harp\Core\Test\Model;
use Harp\Core\Test\Rel;

/**
 * @author     Ivan Kerin
 * @copyright  (c) 2014 Clippings Ltd.
 * @license    http://www.opensource.org/licenses/isc-license.txt
 */
class BlogPost extends Post {

    public static function newInstance()
    {
        return new BlogPost('Harp\Core\Test\Model\BlogPost', 'Post.json');
    }

    public function initialize()
    {
        parent::initialize();

        $this
            ->addRels([
                new Rel\One('address', $this, Address::get()),
            ]);
    }
}

<?php

namespace Harp\Core\Test\Repo;

use Harp\Core\Test\Model;
use Harp\Core\Test\Rel;

/**
 * @author     Ivan Kerin
 * @copyright  (c) 2014 Clippings Ltd.
 * @license    http://www.opensource.org/licenses/isc-license.txt
 */
class BlogPost extends Post {

    public static function newInstance()
    {
        return new BlogPost('Harp\Core\Test\Model\BlogPost', 'Post.json');
    }

    public function initialize()
    {
        parent::initialize();

        $this
            ->setRootRepo(Post::get())
            ->addRels([
                new Rel\One('address', $this, Address::get()),
            ]);
    }
}

Set proper config for inherited repo

:lipstick: Set proper config for inherited repo


<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Categories Database Table Class
 *
 * @author      John Bell <http://nooku.assembla.com/profile/johnbell>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 */
class ComCategoriesDatabaseTableCategories extends KDatabaseTableDefault
{
    public function  _initialize(KConfig $config)
    {
        $config->identity_column = 'id';

        $config->append(array(
            'name'       => 'categories',
            'behaviors'  => array('lockable',
                                   'com.categories.database.behavior.orderable',
                                   'sluggable',
                                   'com.categories.database.behavior.cascadable'),
            'column_map' => array(
                'enabled'      => 'published',
                'locked_on'    => 'checked_out_time',
                'locked_by'    => 'checked_out',
                'slug'         => 'alias'
                ),
            ));

        parent::_initialize($config);
    }
}

<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Categories Database Table Class
 *
 * @author      John Bell <http://nooku.assembla.com/profile/johnbell>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Categories
 */
class ComCategoriesDatabaseTableCategories extends KDatabaseTableDefault
{
    public function  _initialize(KConfig $config)
    {
        $config->identity_column = 'id';

        $config->append(array(
            'name'       => 'categories',
            'behaviors'  => array('lockable', 'orderable', 'sluggable', 'cascadable'),
            'column_map' => array(
                'enabled'      => 'published',
                'locked_on'    => 'checked_out_time',
                'locked_by'    => 'checked_out',
                'slug'         => 'alias'
                ),
            ));

        parent::_initialize($config);
    }
}

Use KDatabaseTableAbstract::getBehavior() to create behaviors using the behavior name instead of the full identifier. Component specific behaviors can now also be loaded using behavior names instead of identifier strings.


<?php
declare(strict_types=1);

use Booking\Domain\Operator\OperatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

final class DumbOperator implements OperatorInterface
{
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(string $spec): Closure
    {
        return function (...$args) use ($spec) {
            $executable = $this->container->get($spec);

            if (\method_exists($executable, '__invoke')) {
                return ($executable)(...$args);
            }

            return $executable;
        };
    }
}

return function (ContainerInterface $container): void {
    $container->autowire(DumbOperator::class, DumbOperator::class)
        ->setShared(true);

    $container->setAlias(OperatorInterface::class, DumbOperator::class);
};

<?php
declare(strict_types=1);

use Booking\Domain\Operator\OperatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

final class DumbOperator implements OperatorInterface
{
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(string $spec): Closure
    {
        return function (...$args) use ($spec) {
            $object = $this->container->get($spec);

            if (\is_callable($object)) {
                return $object(...$args);
            }

            return $object;
        };
    }
}

return function (ContainerInterface $container): void {
    $container->autowire(DumbOperator::class, DumbOperator::class)
        ->setShared(true);

    $container->setAlias(OperatorInterface::class, DumbOperator::class);
};

Simplify the condition to check for a callable type


<?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

class BookmarkHelper extends AppHelper {
	var $helpers = array('Html');

	function print_bookmark($bookmark) {
		echo $this->favicon($bookmark);

		echo '';
		echo $this->Html->link($bookmark['title'],
			array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
			array('class' => 'bookmark_link', 'title' => $bookmark['url']));
		echo '	';

		echo '';
		echo $this->Html->link(__('View', true),
			array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
			array('class' => 'edit_option'));
		echo '	';
	}

	function favicon($bookmark) {
		$html = '';

		if (Configure::read('favicon.show')) {
			$url = $this->favicon_url($bookmark['url']);

			$html .= '	';
		}

		return $html;
	}

	function favicon_url($url) {
		$url = trim(
			str_replace(
				'http://',
				'',
				trim($url)
			),
			'/'
		);
		$url = explode('/', $url);
		$url = 'http://' . $url[0] . '/favicon.ico';

		return $url;
	}
}

<?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

class BookmarkHelper extends AppHelper {
	var $helpers = array('Html');

	function print_bookmark($bookmark) {
		echo $this->favicon($bookmark);

		echo '';
		echo $this->Html->link($bookmark['title'],
			array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
			array('class' => 'bookmark_link', 'title' => $bookmark['url']));
		echo '	';

		echo '';
		echo $this->Html->link(__('View', true),
			array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
			array('class' => 'edit_option'));
		echo '	';
	}

	function favicon($bookmark) {
		$html = '';

		if (Configure::read('favicon.show')) {
			$url = $this->favicon_url($bookmark['url']);

			$html .= '	';
		}

		return $html;
	}

	function favicon_url($url) {
		preg_match('#(https?://[^/]+)/?.*#', $url, $matches);
		if (count($matches) >= 2) {
			$favico_url = $matches[1].'/favicon.ico';
		}
		else {
			$favico_url = '';
		}

		return $favico_url;
	}
}

Use regex instead of explode

Use regex instead of explode


<?php

defined('BASEPATH') or exit('No direct script access allowed');

// row.php Chris Dart Jan 28, 2015 4:24:29 PM chrisdart@cerebratorium.com

?>

<?php echo form_dropdown("subject[]",$subjects,"","required");?>

<?php echo form_dropdown("kCategory[]",$categories,"","id='kCategory' required");?>

	<input
		type="text"
		name="assignment[]"
		required
		id="assignment"
		value="" />
	<input
		type="text"
		style="width: 25px"
		required
		name="points[]"
		id="points"
		value="" />
	<input
		type="checkbox"
		name="prepopulate[]"
		id="prepopulate"
		value="1" />
	<input
		type="date"
		name="date[]"
		id="date"
		required
		size="13"
		value="" />

<?php

defined('BASEPATH') or exit('No direct script access allowed');

// row.php Chris Dart Jan 28, 2015 4:24:29 PM chrisdart@cerebratorium.com

?>

<?php echo form_dropdown("subject[]",$subjects,$subject,"required");?>

<?php echo form_dropdown("kCategory[]",$categories,"","id='kCategory' required");?>

	<input
		type="text"
		name="assignment[]"
		required
		id="assignment"
		value="" />
	<input
		type="text"
		style="width: 25px"
		required
		name="points[]"
		id="points"
		value="" />
	<input
		type="checkbox"
		name="prepopulate[]"
		id="prepopulate"
		value="1" />
	<input
		type="date"
		name="date[]"
		id="date"
		required
		size="13"
		value="" />

Fix batch assignment add so it shows the current subject.


<?php
namespace Cujo\Content;

abstract class Content implements \ArrayAccess
{
    public function __get($offset)
    {
        return $this->offsetGet($offset);
    }

    public function __set($offset, $value)
    {
        $this->offsetSet($offset, $value);
    }

    public function __isSet($offset)
    {
        return $this->offsetExists($offset);
    }

    public function __unset($offset)
    {
        $this->offsetUnset($offset);
    }

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

    public function offsetSet($offset, $value)
    {
        if ($this instanceof Mutable) {
            $this->set($offset, $value);
        }
        throw new \Exception('Content ' . get_class($this) . ' is not mutable');
    }

    public function offsetExists($offset)
    {
        return true;
    }

    public function offsetUnset($offset)
    {
        if ($this instanceof Mutable) {
            $this->remove($offset);
        }
        throw new \Exception('Content ' . get_class($this) . ' is not mutable');
    }

    abstract protected function get($key);

    abstract public function find(array $criteria);

    public function isMutable()
    {
        return $this instanceof Mutable;
    }
}

<?php
namespace Cujo\Content;

abstract class Content implements \ArrayAccess
{
    protected $fallbackToKey = false;

    public function __get($offset)
    {
        return $this->offsetGet($offset);
    }

    public function __set($offset, $value)
    {
        $this->offsetSet($offset, $value);
    }

    public function __isSet($offset)
    {
        return $this->offsetExists($offset);
    }

    public function __unset($offset)
    {
        $this->offsetUnset($offset);
    }

    public function offsetGet($offset)
    {
        $r = $this->get($offset);
        if ((false !== $r && null !== $r)) {
            return $r;
        }
        return $this->isFallbackToKey() ? $offset : false;
    }

    public function offsetSet($offset, $value)
    {
        if ($this instanceof Mutable) {
            $this->set($offset, $value);
        }
        throw new \Exception('Content ' . get_class($this) . ' is not mutable');
    }

    public function offsetExists($offset)
    {
        return true;
    }

    public function offsetUnset($offset)
    {
        if ($this instanceof Mutable) {
            $this->remove($offset);
        }
        throw new \Exception('Content ' . get_class($this) . ' is not mutable');
    }

    abstract protected function get($key);

    abstract public function find(array $criteria);

    public function isMutable()
    {
        return $this instanceof Mutable;
    }

    public function setFallbackToKey($fallback = true)
    {
        $this->fallbackToKey = $fallback;
    }

    public function isFallbackToKey()
    {
        return $this->fallbackToKey;
    }
}

Add fallback to key option

Add fallback to key option


<?php

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

class RemoveInfoOpsSourceRealmTargetDominionConstraint extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table('info_ops', static function (Blueprint $table) {
            $table->boolean('latest')
                ->after('data')
                ->default(true);

            $table->index(['source_realm_id']);
            $table->index(['target_dominion_id']);
            $table->dropUnique(['source_realm_id', 'target_dominion_id', 'type']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table('info_ops', static function (Blueprint $table) {
            $table->dropColumn(['latest']);

            $table->unique(['source_realm_id', 'target_dominion_id', 'type']);
            $table->dropIndex(['source_realm_id']);
            $table->dropIndex(['target_dominion_id']);
        });
    }
}

<?php

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

class RemoveInfoOpsSourceRealmTargetDominionConstraint extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table('info_ops', static function (Blueprint $table) {
            $table->boolean('latest')
                ->after('data')
                ->default(true);

            $table->dropUnique(['source_realm_id', 'target_dominion_id', 'type']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table('info_ops', static function (Blueprint $table) {
            $table->unique(['source_realm_id', 'target_dominion_id', 'type']);

            $table->dropColumn(['latest']);
        });
    }
}

Remove dropIndex on foreign keys from migration


<?php
namespace CI\UI\Controller;

class HookController
{
    public function hook(\Silex\Application $app)
    {
    	$client= new \GearmanClient();
		$client->addServer('127.0.0.1', 4730);
		$test_id = $client->doNormal('create_test', $app['request']->get('id'));

        if ($app['request']->get('redirect'))
        {
            return $app->redirect('/project/' . $app['request']->get('id'));
        }

		return $app->json(array(
			'success' => true
		));
    }
}

<?php
namespace CI\UI\Controller;

class HookController
{
    public function hook(\Silex\Application $app)
    {
    	$client= new \GearmanClient();
		$client->addServer('127.0.0.1', 4730);
		$test_id = $client->doBackground('create_test', $app['request']->get('id'));

		return $app->json(array(
			'success' => true
		));
    }
}

Remove redirect in Hook, and make it "doBackground"


<?php

require_once('../_include.php');

try {

	$config = SimpleSAML_Configuration::getInstance();
	$session = SimpleSAML_Session::getInstance();

	/* Make sure that the user has admin access rights. */
	if (!isset($session) || !$session->isValid('login-admin') ) {
		SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
		                               array('RelayState' => SimpleSAML_Utilities::selfURL())
		                               );
	}

	$stats = SimpleSAML_MemcacheStore::getStats();

	$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
	$template->data['title'] = 'Memcache stats';
	$template->data['table'] = $stats;
	$template->show();

} catch(Exception $e) {
	SimpleSAML_Utilities::fatalError('na', NULL, $e);
}

?>

<?php

require_once('../_include.php');

try {

	$config = SimpleSAML_Configuration::getInstance();
	$session = SimpleSAML_Session::getInstance();

	/* Make sure that the user has admin access rights. */
	if (!isset($session) || !$session->isValid('login-admin') ) {
		SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
		                               array('RelayState' => SimpleSAML_Utilities::selfURL())
		                               );
	}

	$stats = SimpleSAML_Memcache::getStats();

	$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
	$template->data['title'] = 'Memcache stats';
	$template->data['table'] = $stats;
	$template->show();

} catch(Exception $e) {
	SimpleSAML_Utilities::fatalError('na', NULL, $e);
}

?>

Fix Memcachestat. Using wrong classname

Fix Memcachestat. Using wrong classname


<?php

// Custom form validation messages
$lang['form_validation_alpha_dot_dash'] = 'The {field} field may only contain alphanumeric characters, periods, underscores and dashes.';
$lang['form_validation_latlong'] = 'The {field} must be between -180 and 180.';
$lang['form_validation_shield_factor'] = 'The {field} must be from 0 to 1.';
$lang['form_validation_unique'] = 'The {field} field is not unique. Please choose another.';

<?php

// Custom form validation messages
$lang['form_validation_alpha_dot_dash'] = 'The {field} field may only contain alphanumeric characters, periods, underscores and dashes.';
$lang['form_validation_is_numeric'] = 'The {field} must be a number.';
$lang['form_validation_latlong'] = 'The {field} must be between -180 and 180.';
$lang['form_validation_shield_factor'] = 'The {field} must be from 0 to 1.';
$lang['form_validation_unique'] = 'The {field} field is not unique. Please choose another.';

Add form validation message for is_numeric


<?php

echo "
\n";
echo 'display_errors = ' . ini_get('display_errors') . "\n";

if ( ini_get('display_errors') == 1 ) {
    echo("It is all good...\n");
    echo "
\n";
    return;
}

echo("YOU ARE IN VERY BAD SHAPE!!!!!!\n");
echo("You need to edit this file:\n\n");
echo(php_ini_loaded_file()."\n\n");
echo("And set\n\n");
echo("display_errors = On\n\n");
echo("Until you do this, you will be very very unhappy doing PHP development\n");
echo("in this PHP environment.\n");

echo "
\n";

<?php

echo "
\n";
echo "Checking some configuration file options...\n\n";
echo 'display_errors = ' . ini_get('display_errors') . "\n";

$good = 0;
if ( ini_get('display_errors') == 1 ) {
    echo("display_errors is set correctly...\n\n");
    $good ++;
} else {
    echo("WARNING: You need to edit your configuration file\n");
    echo("and set:\n\n");
    echo("display_errors = On\n\n");
}

// magic_quotes_gpc = off
$magic = get_magic_quotes_gpc();
echo 'magic_quotes_gpc = ' . ($magic == 1 ? "On" : "Off") . "\n";
if ( get_magic_quotes_gpc() == 0 ) {
    echo("magic_quotes_gpc is set correctly...\n\n");
    $good ++;
} else {
    echo("WARNING: You need to edit your configuration file\n");
    echo("and set:\n\n");
    echo("magic_quotes_gpc = off\n\n");
}

if ( $good == 2 ) {
    echo("
\n");
    return;
}

echo("YOUR CONFIGURATION FILE IS IN BAD SHAPE!!!!!!\n");
echo("You need to edit this file:\n\n");
echo(php_ini_loaded_file()."\n\n");
echo("Fix the issues identified above\n");
echo("Until you do this, you will be very unhappy doing PHP development\n");
echo("in this PHP environment.\n");

echo "
\n";

Add even more error checking...

Add even more error checking...


<?php
if (NULL !== @$urlParams[1]){
	include("pages/detail-encadrant.php");
} else {
?>

Liste des encadrants

	<?php
	$res = $db->query('SELECT * FROM Enseignant') or die(mysqli_error($db));
	while (NULL !== ($row = $res->fetch_array())){
		echo "";
		echo "
".$row['prenomEns']."
";
		echo "
".strtoupper($row['nomEns'])."
";
		echo "";
	}
	?>

<?php
}
?>

<?php
if (NULL !== @$urlParams[1]){
	include("pages/details-encadrant.php");
} else {
?>

Liste des encadrants

	<?php
	$res = $db->query('SELECT * FROM Enseignant') or die(mysqli_error($db));
	while (NULL !== ($row = $res->fetch_array())){
		echo "";
		echo "
".$row['prenomEns']."
";
		echo "
".strtoupper($row['nomEns'])."
";
		echo "";
	}
	?>

<?php
}
?>

Correct file name in include()

Correct file name in include()


<?php
/**
 * File: Config.php
 * User: zacharydubois
 * Date: 2015-12-30
 * Time: 20:33
 * Project: Digital-Footprint-Profile
 */

namespace dfp;

class Config {
    private
        $config,
        $DataStore;

    /**
     * Config constructor.
     *
     * Sets the file to the configuration and grabs the current configuration contents.
     */
    public function __construct() {
        // Create DataStore object.
        $this->DataStore = new DataStore();
        // Grab the current configuration.
        $this->DataStore->setFile(CONFIGURATION);
        $this->config = $this->DataStore->read();
    }

    /**
     * Retrieves Configuration Parameters
     *
     * Retrieves configuration options from the configuration array.
     *
     * @param string $option
     * @param string|null $param
     * @return array|string|bool
     */
    public function get($option, $param = null) {
        if ((!isset($this->config[$option]) && $param === null) || (!isset($this->config[$option][$param]) && $param !== null)) {
            // Make sure values actually exist.
            return false;
        }

        return $this->config[$option];
    }

    /**
     * Set Configuration
     *
     * Merges new values with existing.
     *
     * @param array $payload
     * @return true
     * @throws Exception
     */
    public function set(array $payload) {
        $config = array_merge($payload, $this->config);

        if (!$this->DataStore->write($config)) {
            throw new Exception("Failed to write config using config->set.");
        }

        return true;
    }
}

<?php
/**
 * File: Config.php
 * User: zacharydubois
 * Date: 2015-12-30
 * Time: 20:33
 * Project: Digital-Footprint-Profile
 */

namespace dfp;

class Config {
    private
        $config,
        $DataStore;

    /**
     * Config constructor.
     *
     * Sets the file to the configuration and grabs the current configuration contents.
     */
    public function __construct() {
        // Create DataStore object.
        $this->DataStore = new DataStore();
        // Grab the current configuration.
        $this->DataStore->setFile(CONFIGURATION);
        $this->config = $this->DataStore->read();
    }

    /**
     * Retrieves Configuration Parameters
     *
     * Retrieves configuration options from the configuration array.
     *
     * @param string $option
     * @param string $param
     * @return array|string|bool
     */
    public function get($option, $param) {
        if (!isset($this->config[$option][$param]) || $this->config[$option][$param] === '') {
            // Make sure values actually exist.
            return false;
        }

        return $this->config[$option][$param];
    }

    /**
     * Set Configuration
     *
     * Merges new values with existing.
     *
     * @param array $payload
     * @return true
     * @throws Exception
     */
    public function set(array $payload) {
        $config = array_merge($payload, $this->config);

        if (!$this->DataStore->write($config)) {
            throw new Exception("Failed to write config using config->set.");
        }

        return true;
    }
}

Make sure config returns proper value.

Make sure config returns proper value.


<?php
namespace Baum;

use Illuminate\Support\ServiceProvider;

class BaumServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('etrepat/baum');
	}

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

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

}

<?php
namespace Baum;

use Illuminate\Support\ServiceProvider;

class BaumServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('etrepat/baum');
	}

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

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

}

Remove comment from service provider file.


<?=$tinymce_script?>
<textarea <?=$attributes?>><?=$value?></textarea>
<script>setTimeout(function(){ tinymce.init(<?=$tinymce_config?>); }, 100)</script>

Add timeout to tinymce.init to fix issues with dynamically loaded items.


@extends('admin.layout')

@section('title')
  Installer | Complete
@stop

@section('content')

Success

Install complete.

Then you can login to the admin

@stop

@extends('admin.layout')

@section('title')
  Installer | Complete
@stop

@section('content')

Success

Install complete.

You can now login to the admin

@stop

Adjust the install complete message

Adjust the install complete message


<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mscorps extends Back_end {

    public $model = 'model_master_corps';

    public function __construct() {
        parent::__construct('kelola_pustaka_corps', 'Pustaka corps');
    }

    public function index() {
        parent::index();
        $this->set("bread_crumb", array(
            "#" => $this->_header_title
        ));
    }

    public function detail($id = FALSE) {
        parent::detail($id, array(
            "kode_corps","init_corps","ur_corps",
        ));

        $this->set("bread_crumb", array(
            "back_end/" . $this->_name => $this->_header_title,
            "#" => 'Pendaftaran ' . $this->_header_title
        ));
//        $this->add_jsfiles(array("avant/plugins/form-jasnyupload/fileinput.min.js"));
    }

    public function get_like() {
        $keyword = $this->input->post("keyword");

        $corps_found = $this->model_ref_corps->get_like($keyword);

        $this->to_json($corps_found);
    }
}

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mscorps extends Back_end {

    public $model = 'model_master_corps';

    public function __construct() {
        parent::__construct('kelola_pustaka_corps', 'Pustaka corps');
    }

    public function index() {
        parent::index();
        $this->set("bread_crumb", array(
            "#" => $this->_header_title
        ));
    }

    public function detail($id = FALSE) {
        parent::detail($id, array("kode_corps",
            "init_corps",
            "ur_corps",));

        $this->set("bread_crumb", array(
            "back_end/" . $this->_name => $this->_header_title,
            "#" => 'Pendaftaran ' . $this->_header_title
        ));
//        $this->add_jsfiles(array("avant/plugins/form-jasnyupload/fileinput.min.js"));
    }

    public function get_like() {
        $keyword = $this->input->post("keyword");

        $corps_found = $this->model_master_corps->get_like($keyword);

        $this->to_json($corps_found);
    }

}

Update Master Corps - Index

Update Master Corps - Index


<?php
/**
 * @link https://github.com/nezhelskoy/yii2-return-url
 * @copyright Copyright (c) 2014 Dmitry Nezhelskoy
 * @license "BSD-3-Clause"
 */

namespace nezhelskoy\returnUrl;

use Yii;
use yii\base\ActionFilter;

/**
 * ReturnUrl filter
 *
 * Keep current URL (if it's not an AJAX url) in session so that the browser may
 * be redirected back.
 *
 * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru>
 */
class ReturnUrl extends ActionFilter
{
    /**
     * This method is invoked right after an action is executed.
     * You may override this method to do some postprocessing for the action.
     * @param Action $action the action just executed.
     * @param mixed $result the action execution result
     * @return mixed the processed action result.
     */
    public function afterAction($action, $result)
    {
        if ( ! Yii::$app->request->getIsAjax()) {
            Yii::$app->user->setReturnUrl(Yii::$app->request->getUrl());
        }
        return $result;
    }
}

<?php
/**
 * @link https://github.com/nezhelskoy/yii2-return-url
 * @copyright Copyright (c) 2014 Dmitry Nezhelskoy
 * @license "BSD-3-Clause"
 */

namespace nezhelskoy\returnUrl;

use Yii;
use yii\base\ActionFilter;
use yii\helpers\Url;

/**
 * ReturnUrl filter
 *
 * Keep current URL (if it's not an AJAX url) in session so that the browser may
 * be redirected back.
 *
 * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru>
 */
class ReturnUrl extends ActionFilter
{

    public $visitedParam = 'visitedUrl';
    /**
     * This method is invoked right after an action is executed.
     * You may override this method to do some postprocessing for the action.
     * @param Action $action the action just executed.
     * @param mixed $result the action execution result
     * @return mixed the processed action result.
     */
    public function afterAction($action, $result)
    {
        if ( ! Yii::$app->request->getIsAjax()) {
            Url::remember(Yii::$app->request->getUrl(), $this->visitedParam);
        }
        return $result;
    }
}

Change implementation of store url in session


<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\State;
use Phug\Lexer\Token\ConditionalToken;

class ConditionalScanner extends ControlStatementScanner
{
    public function __construct()
    {
        parent::__construct(
            ConditionalToken::class,
            ['if', 'unless', 'else[ \t]*if', 'else']
        );
    }

    public function scan(State $state)
    {
        foreach (parent::scan($state) as $token) {
            if ($token instanceof ConditionalToken) {
                //Make sure spaces are replaced from `elseif`/`else if` to make a final keyword, "elseif"
                $token->setName(preg_replace('/[ \t]/', '', $token->getName()));

                if ($token->getName() === 'else' && !in_array($token->getSubject(), ['', false, null])) {
                    $state->throwException(
                        'The `else`-conditional statement can\'t have a subject',
                        $token
                    );
                }
            }

            yield $token;
        }
    }
}

<?php

namespace Phug\Lexer\Scanner;

use Phug\Lexer\State;
use Phug\Lexer\Token\ConditionalToken;

class ConditionalScanner extends ControlStatementScanner
{
    public function __construct()
    {
        parent::__construct(
            ConditionalToken::class,
            ['if', 'unless', 'else[ \t]*if', 'else']
        );
    }

    public function scan(State $state)
    {
        foreach (parent::scan($state) as $token) {
            if ($token instanceof ConditionalToken) {
                //Make sure spaces are replaced from `elseif`/`else if` to make a final keyword, "elseif"
                $token->setName(preg_replace('/[ \t]/', '', $token->getName()));

                if ($token->getName() === 'else' && !in_array($token->getSubject(), ['', false, null])) {
                    $state->throwException(
                        'The `else`-conditional statement can\'t have a subject'
                    );
                }
            }

            yield $token;
        }
    }
}

Fix Lexer [else with subject] exception

Fix Lexer [else with subject] exception


<?php

namespace Lmc\Steward\Component;

abstract class AbstractComponent
{
    /** @var \Lmc\Steward\Test\AbstractTestCaseBase */
    protected $tc;

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

    /**
     * @param \Lmc\Steward\Test\AbstractTestCaseBase $tc TestCase instance
     */
    public function __construct(\Lmc\Steward\Test\AbstractTestCaseBase $tc)
    {
        $this->tc = $tc;

        $reflection = new \ReflectionClass($this);
        $this->componentName = $reflection->getShortName();
    }

    public function __call($name, $arguments)
    {
        // Methods log() and warn() prepend componentName to message and call the same method on TestCase.
        if ($name == 'log' || $name == 'warn') {
            $arguments[0] = '[' . $this->componentName . '] ' . $arguments[0];
            call_user_method_array($name, $this->tc, $arguments);
        }
    }
}

<?php

namespace Lmc\Steward\Component;

abstract class AbstractComponent
{
    /** @var \Lmc\Steward\Test\AbstractTestCaseBase */
    protected $tc;

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

    /**
     * @param \Lmc\Steward\Test\AbstractTestCaseBase $tc TestCase instance
     */
    public function __construct(\Lmc\Steward\Test\AbstractTestCaseBase $tc)
    {
        $this->tc = $tc;

        $reflection = new \ReflectionClass($this);
        $this->componentName = $reflection->getShortName();
    }

    public function __call($name, $arguments)
    {
        // Methods log() and warn() prepend componentName to message and call the same method on TestCase.
        if ($name == 'log' || $name == 'warn') {
            $arguments[0] = '[' . $this->componentName . '] ' . $arguments[0];
            call_user_func_array([$this->tc, $name], $arguments);
        }
    }
}

Replace deprecated custom function call

Replace deprecated custom function call


<?php

class Palindrome
{
    public static function isPalindrome($word)
    {
        return strtolower(strrev($word)) == strtolower($word);
    }
}

echo Palindrome::isPalindrome('Deleveled');

<?php

/*
 * A palindrome is a word, phrase, or sequence that reads the same
 * backward as forward, e.g., madam or nurses run.
 */
class Palindrome
{
    public static function isPalindrome($word)
    {
        return strtolower(strrev($word)) == strtolower($word);
    }
}

echo Palindrome::isPalindrome('Deleveled');

Add extra line and algorithm description


<?php

/**
 * Game Server Monitor
 *
 * Posts notifications when one of the monitored servers has players on it
 *
 * @version 1.0
 */

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

$db = new SQLite3('data/gasemon.db');
$ini = parse_ini_file('config.ini');

$tweetBot = new gasemon\AhlTweetBot(
    $ini['tweetbot.cooldown'],
    $ini['tweetbot.consumerKey'],
    $ini['tweetbot.consumerSecret'],
    $ini['tweetbot.accessToken'],
    $ini['tweetbot.accessSecret']
);

$gm = new gasemon\ServerMonitor($db, $tweetBot, 'source');

$gm->runCheck();

<?php

/**
 * Game Server Monitor
 *
 * Posts notifications when one of the monitored servers has players on it
 *
 * @version 1.0
 */

chdir(__DIR__);

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

$db = new SQLite3('data/gasemon.db');
$ini = parse_ini_file('config.ini');

$tweetBot = new gasemon\AhlTweetBot(
    $ini['tweetbot.cooldown'],
    $ini['tweetbot.consumerKey'],
    $ini['tweetbot.consumerSecret'],
    $ini['tweetbot.accessToken'],
    $ini['tweetbot.accessSecret']
);

$gm = new gasemon\ServerMonitor($db, $tweetBot, 'source');

$gm->runCheck();

Change to current dir at start for relative paths


<?php

namespace Asvae\ApiTester\Http\Controllers;

use DateTime;
use Illuminate\Routing\Controller;

class AssetsController extends Controller
{
    const SECONDS_IN_YEAR = 60*60*24*365;

    public function index($file = '')
    {
        // Permit only safe characters in filename.
        if (! preg_match('%^([a-z_\-\.]+?)$%', $file)) {
            abort(404);
        }

        $contents = file_get_contents(__DIR__.'/../../../resources/assets/build/'.$file);
        $response = response($contents, 200, [
            'Content-Type' => $this->getFileContentType($file)
        ]);

        // Browser will cache files for 1 year.
        $response->setSharedMaxAge(static::SECONDS_IN_YEAR);
        $response->setMaxAge(static::SECONDS_IN_YEAR);
        $response->setExpires(new DateTime('+1 year'));

        return $response;
    }

    /**
     * Figure out appropriate "Content-Type" header
     * by filename.
     *
     * @param $file
     * @return mixed
     */
    protected function getFileContentType($file)
    {
        $array = explode('.', $file);
        $ext = end($array);

        $contentTypes = [
            'css' => 'text/css',
            'js'  => 'text/javascript',
            'svg' => 'image/svg+xml',
        ];

        return $contentTypes[$ext];
    }
}

<?php

namespace Asvae\ApiTester\Http\Controllers;

use DateTime;
use Illuminate\Routing\Controller;

class AssetsController extends Controller
{
    public function index($file = '')
    {
        // Permit only safe characters in filename.
        if (! preg_match('%^([a-z_\-\.]+?)$%', $file)) {
            abort(404);
        }

        $contents = file_get_contents(__DIR__.'/../../../resources/assets/build/'.$file);
        $response = response($contents, 200, [
            'Content-Type' => $this->getFileContentType($file)
        ]);

        // Browser will cache files for 1 year.
        $secondsInYear = 60*60*24*365;
        $response->setSharedMaxAge($secondsInYear);
        $response->setMaxAge($secondsInYear);
        $response->setExpires(new DateTime('+1 year'));

        return $response;
    }

    /**
     * Figure out appropriate "Content-Type" header
     * by filename.
     *
     * @param $file
     * @return mixed
     */
    protected function getFileContentType($file)
    {
        $array = explode('.', $file);
        $ext = end($array);

        $contentTypes = [
            'css' => 'text/css',
            'js'  => 'text/javascript',
            'svg' => 'image/svg+xml',
        ];

        return $contentTypes[$ext];
    }
}

Remove const expression to attain php 5.5 support


<?php

namespace Croogo\Core\Model\Behavior;

use Cake\Database\Query;
use Cake\ORM\Behavior;

class VisibilityBehavior extends Behavior
{

	public function findVisibilityRole(Query $query, array $options = [])
	{
		$query->where([
			'AND' => [
				[
					'OR' => [
						'Links.visibility_roles IS NULL',
						'Links.visibility_roles LIKE' => '%"' . $options['role_id'] . '"%',
					],
				],
			],
		]);

		return $query;
	}
}

<?php

namespace Croogo\Core\Model\Behavior;

use Cake\Database\Query;
use Cake\ORM\Behavior;

class VisibilityBehavior extends Behavior
{

	public function findVisibilityRole(Query $query, array $options = [])
	{
		$query->where([
			'AND' => [
				[
					'OR' => [
						$this->_table->alias() . '.visibility_roles IS NULL',
						$this->_table->alias() . '.visibility_roles LIKE' => '%"' . $options['role_id'] . '"%',
					],
				],
			],
		]);

		return $query;
	}
}

Use the table alias in the visibility behaviour


<?php

namespace Zipkin\Reporters\Http;

use BadFunctionCallException;
use RuntimeException;

final class CurlFactory implements ClientFactory
{
    private function __construct()
    {
    }

    /**
     * @return CurlFactory
     * @throws \BadFunctionCallException if the curl extension is not installed.
     */
    public static function create()
    {
        if (!function_exists('curl_init')) {
            throw new BadFunctionCallException('cURL is not enabled');
        }

        return new self();
    }

    /**
     * {@inheritdoc}
     */
    public function build(array $options = [])
    {
        /**
         * @param string $payload
         * @throws RuntimeException
         * @return void
         */
        return function ($payload) use ($options) {
            $handle = curl_init($options['endpoint_url']);
            curl_setopt($handle, CURLOPT_POST, 1);
            curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($handle, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($payload),
            ]);

            if (curl_exec($handle) === true) {
                $statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
                curl_close($handle);

                if ($statusCode !== 202) {
                    throw new RuntimeException(
                        sprintf('Reporting of spans failed, status code %d', $statusCode)
                    );
                }
            } else {
                throw new RuntimeException(sprintf(
                    'Reporting of spans failed: %s, error code %s',
                    curl_error($handle),
                    curl_errno($handle)
                ));
            }
        };
    }
}

<?php

namespace Zipkin\Reporters\Http;

use BadFunctionCallException;
use RuntimeException;

final class CurlFactory implements ClientFactory
{
    private function __construct()
    {
    }

    /**
     * @return CurlFactory
     * @throws \BadFunctionCallException if the curl extension is not installed.
     */
    public static function create()
    {
        if (!function_exists('curl_init')) {
            throw new BadFunctionCallException('cURL is not enabled');
        }

        return new self();
    }

    /**
     * {@inheritdoc}
     */
    public function build(array $options = [])
    {
        /**
         * @param string $payload
         * @throws RuntimeException
         * @return void
         */
        return function ($payload) use ($options) {
            $handle = curl_init($options['endpoint_url']);
            curl_setopt($handle, CURLOPT_POST, 1);
            curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($handle, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($payload),
            ]);
            curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

            if (curl_exec($handle) === true) {
                $statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
                curl_close($handle);

                if ($statusCode !== 202) {
                    throw new RuntimeException(
                        sprintf('Reporting of spans failed, status code %d', $statusCode)
                    );
                }
            } else {
                throw new RuntimeException(sprintf(
                    'Reporting of spans failed: %s, error code %s',
                    curl_error($handle),
                    curl_errno($handle)
                ));
            }
        };
    }
}

Set CURLOPT_RETURNTRANSFER to true so that the string value of the transfer is returned rather than outputting it directly.


<?php

namespace hiapi\Core\Auth;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

abstract class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->authenticate($request);

        return $handler->handle($request);
    }

    abstract public function authenticate(ServerRequestInterface $request);

    protected function getAccessToken(ServerRequestInterface $request): ?string
    {
        return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token');
    }

    protected function getBearerToken(ServerRequestInterface $request): ?string
    {
        $header = $request->getHeaderLine('Authorization');
        if (preg_match('/^Bearer\s+([a-fA-F0-9]{30,50})$/', $header, $matches)) {
            return $matches[1];
        }

        return null;
    }

    public function getParam(ServerRequestInterface $request, string $name): ?string
    {
        return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null;
    }
}

<?php

namespace hiapi\Core\Auth;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

abstract class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->authenticate($request);

        return $handler->handle($request);
    }

    abstract public function authenticate(ServerRequestInterface $request);

    protected function getAccessToken(ServerRequestInterface $request): ?string
    {
        return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token');
    }

    protected function getBearerToken(ServerRequestInterface $request): ?string
    {
        $header = $request->getHeaderLine('Authorization');
        if (preg_match('/^Bearer\s+([a-zA-Z0-9._-]{30,50})$/', $header, $matches)) {
            return $matches[1];
        }

        return null;
    }

    public function getParam(ServerRequestInterface $request, string $name): ?string
    {
        return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null;
    }
}

Allow more symbols in authorization token


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Symfony\Polyfill\Php55 as p;

if (PHP_VERSION_ID < 50500) {
    if (!function_exists('boolval')) {
        function boolval($val) { return p\Php55::boolval($val); }
    }
    if (!function_exists('json_last_error_msg')) {
        function json_last_error_msg() { return p\Php55::json_last_error_msg(); }
    }
    if (!function_exists('array_column')) {
        function array_column($array, $columnKey, $indexKey = null) { return p\Php55ArrayColumn::array_column($array, $columnKey, $indexKey); }
    }
    if (!function_exists('hash_pbkdf2')) {
        function hash_pbkdf2($algorithm, $password, $salt, $iterations, $length = 0, $rawOutput = false) { return p\Php55::hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, $rawOutput); }
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Symfony\Polyfill\Php55 as p;

if (PHP_VERSION_ID >= 50500) {
    return;
}

if (!function_exists('boolval')) {
    function boolval($val) { return p\Php55::boolval($val); }
}
if (!function_exists('json_last_error_msg')) {
    function json_last_error_msg() { return p\Php55::json_last_error_msg(); }
}
if (!function_exists('array_column')) {
    function array_column($array, $columnKey, $indexKey = null) { return p\Php55ArrayColumn::array_column($array, $columnKey, $indexKey); }
}
if (!function_exists('hash_pbkdf2')) {
    function hash_pbkdf2($algorithm, $password, $salt, $iterations, $length = 0, $rawOutput = false) { return p\Php55::hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, $rawOutput); }
}

Fix declaring extra constants when `intl` is loaded


<?php

require('json-rpc/json-rpc.php');

if (function_exists('xdebug_disable')) {
    xdebug_disable();
}

@mysql_connect('localhost', 'user', 'password');
@mysql_select_db('database_name');

class MysqlDemo {
  public function query($query) {
    if (preg_match("/create|drop/", $query)) {
      throw new Exception("Sorry you are not allowed to execute '" .
                          $query . "'");
    }
    if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) {
      throw new Exception("Sorry you can't execute '" . $query .
                          "' you are only allowed to select, insert, delete " .
                          "or update 'test' table");
    }
    if ($res = mysql_query($query)) {
      if ($res === true) {
        return true;
      }
      if (mysql_num_rows($res) > 0) {
        while ($row = mysql_fetch_row($res)) {
          $result[] = $row;
        }
        return $result;
      } else {
        return array();
      }
    } else {
      throw new Exception("MySQL Error: " . mysql_error());
    }
  }
}

handle_json_rpc(new MysqlDemo());

?>

<?php

require('json-rpc/json-rpc.php');

if (function_exists('xdebug_disable')) {
    xdebug_disable();
}

$link = new mysqli('localhost', 'user', 'password', 'db_name');

class MysqlDemo {
  public function query($query) {
    global $link;
    if (preg_match("/create|drop/", $query)) {
      throw new Exception("Sorry you are not allowed to execute '" .
                          $query . "'");
    }
    if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) {
      throw new Exception("Sorry you can't execute '" . $query .
                          "' you are only allowed to select, insert, delete " .
                          "or update 'test' table");
    }
    if ($res = $link->query($query)) {
      if ($res === true) {
        return true;
      }
      if ($res->num_rows > 0) {
        while ($row = $res->fetch_array(MYSQLI_NUM)) {
          $result[] = $row;
        }
        return $result;
      } else {
        return array();
      }
    } else {
      throw new Exception("MySQL Error: " . mysql_error());
    }
  }
}

handle_json_rpc(new MysqlDemo());

?>

Use MySQLi interface for example

Use MySQLi interface for example


<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Providers;

use CachetHQ\Cachet\Console\Commands\FixPermissionsCommand;
use Illuminate\Support\ServiceProvider;

class ConsoleServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('CachetHQ\Cachet\Console\Commands\FixPermissionsCommand', function ($app) {
            $storageDirectory = storage_path();
            $databaseDirectory = base_path('database');
            $databasePath = $app->config->get('database.connections.sqlite.database');
            $databaseDefault = $app->config->get('database.default');

            return new FixPermissionsCommand($storageDirectory, $databaseDirectory, $databasePath, $databaseDefault);
        });
    }
}

<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Providers;

use CachetHQ\Cachet\Console\Commands\FixPermissionsCommand;
use Illuminate\Support\ServiceProvider;

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

Remove service binding console service provider


<?php
namespace Listabierta\Bundle\MunicipalesBundle\Validator\Constraints;

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

class DNIValidator extends ConstraintValidator
{
	public function validate($value, Constraint $constraint)
	{
		// Check format
		if (0 === preg_match("/\d{1,8}[a-z]/i", $value))
		{
			$this->context->addViolationAtSubPath('dni', 'El DNI introducido no tiene el formato correcto (entre 1 y 8 números seguidos de una letra, sin guiones y sin dejar ningún espacio en blanco)', array(), NULL);

			return;
		}

		// Check letter with algorithm
		$dni_number = substr($value, 0, -1);
		$dni_letter  = strtoupper(substr($value, -1));
		if ($dni_letter != substr("TRWAGMYFPDXBNJZSQVHLCKE", strtr($dni_number, "XYZ", "012")%23, 1))
		{
			$this->context->addViolationAtSubPath('dni', 'La letra no coincide con el número del DNI. Comprueba que has escrito bien tanto el número como la letra', array(), NULL);
		}
	}
}

<?php
namespace Listabierta\Bundle\MunicipalesBundle\Validator\Constraints;

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

class DNIValidator extends ConstraintValidator
{
	public function validate($value, Constraint $constraint)
	{
		// Check format
		if (0 === preg_match("/\d{1,8}[a-z]/i", $value))
		{
			$this->context->addViolationAt('dni', 'El DNI introducido no tiene el formato correcto (entre 1 y 8 números seguidos de una letra, sin guiones y sin dejar ningún espacio en blanco)', array(), NULL);

			return;
		}

		// Check letter with algorithm
		$dni_number = substr($value, 0, -1);
		$dni_letter  = strtoupper(substr($value, -1));
		if ($dni_letter != substr("TRWAGMYFPDXBNJZSQVHLCKE", strtr($dni_number, "XYZ", "012")%23, 1))
		{
			$this->context->addViolationAt('dni', 'La letra no coincide con el número del DNI. Comprueba que has escrito bien tanto el número como la letra', array(), NULL);
		}
	}
}

Fix method in dni validator

Fix method in dni validator


<?php

namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_8;

use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class AddUniqueVersionIndex implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $auditTable = $schema->getTable('oro_audit');
        $auditTable->addUniqueIndex(['object_id', 'object_class', 'version'], 'idx_oro_audit_version');
    }
}

<?php

namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_8;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Connection;

use Oro\Bundle\MigrationBundle\Migration\ConnectionAwareInterface;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class AddUniqueVersionIndex implements Migration, ConnectionAwareInterface
{
    /** @var Connection */
    private $connection;

    /**
     * {@inheritdoc}
     */
    public function setConnection(Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $ids = $this->getDuplicates();
        $queries->addPreQuery(
            new ParametrizedSqlMigrationQuery(
                'DELETE FROM oro_audit WHERE id IN (:ids)',
                ['ids' => $ids],
                ['ids' => Connection::PARAM_STR_ARRAY]
            )
        );

        $auditTable = $schema->getTable('oro_audit');
        $auditTable->addUniqueIndex(['object_id', 'object_class', 'version'], 'idx_oro_audit_version');
    }

    /**
     * @return string[]
     */
    protected function getDuplicates()
    {
        $sql = 'SELECT MAX(id) AS id FROM oro_audit GROUP BY object_id, object_class, version HAVING COUNT(*) > 1';

        $result = [];
        $rows   = $this->connection->fetchAll($sql);
        foreach ($rows as $row) {
            $result[] = $row['id'];
        }

        return $result;
    }
}

BAP-13308: Upgrade CRM EE from 1.12 to 2.0 is out of service


<?php declare(strict_types = 1);

namespace Amp\Test;

use Amp;
use Amp\{ Deferred, Failure, Pause, Success };
use Interop\Async\Loop;

class WaitTest extends \PHPUnit_Framework_TestCase {
    public function testWaitOnSuccessfulPromise()
    {
        $value = 1;

        $promise = new Success($value);

        $result = Amp\wait($promise);

        $this->assertSame($value, $result);
    }

    public function testWaitOnFailedPromise()
    {
        $exception = new \Exception();

        $promise = new Failure($exception);

        try {
            $result = Amp\wait($promise);
        } catch (\Exception $e) {
            $this->assertSame($exception, $e);
            return;
        }

        $this->fail('Rejection exception should be thrown from wait().');
    }

    /**
     * @depends testWaitOnSuccessfulPromise
     */
    public function testWaitOnPendingPromise()
    {
        Loop::execute(function () {
            $value = 1;

            $promise = new Pause(100, $value);

            $result = Amp\wait($promise);

            $this->assertSame($value, $result);
        });
    }

    /**
     * @expectedException \Error
     */
    public function testPromiseWithNoResolutionPathThrowsException()
    {
        $promise = new Deferred;

        $result = Amp\wait($promise->getPromise());
    }
}

<?php declare(strict_types = 1);

namespace Amp\Test;

use Amp;
use Amp\{ Deferred, Failure, Pause, Success };
use Interop\Async\Loop;

class WaitTest extends \PHPUnit_Framework_TestCase {
    public function testWaitOnSuccessfulPromise()
    {
        $value = 1;

        $promise = new Success($value);

        $result = Amp\wait($promise);

        $this->assertSame($value, $result);
    }

    public function testWaitOnFailedPromise()
    {
        $exception = new \Exception();

        $promise = new Failure($exception);

        try {
            $result = Amp\wait($promise);
        } catch (\Exception $e) {
            $this->assertSame($exception, $e);
            return;
        }

        $this->fail('Rejection exception should be thrown from wait().');
    }

    /**
     * @depends testWaitOnSuccessfulPromise
     */
    public function testWaitOnPendingPromise()
    {
        Loop::execute(function () {
            $value = 1;

            $promise = new Pause(100, $value);

            $result = Amp\wait($promise);

            $this->assertSame($value, $result);
        });
    }

    /**
     * @expectedException \Error
     * @expectedExceptionMessage Loop emptied without resolving promise
     */
    public function testPromiseWithNoResolutionPathThrowsException()
    {
        $promise = new Deferred;

        $result = Amp\wait($promise->promise());
    }
}

Fix method name in wait() test

Fix method name in wait() test


<?php

return [
	"minute" => ":t minuut|:t minuten",
	"hour" => ":t uur",
	"day" => ":t dag|:t dagen",
	"week" => ":t week|:t weken ",
	"timeago" => ": geleden",
	"timeuntil" => "over :time"
];

Fix parse error in nl translations

Fix parse error in nl translations


<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = $_GET;
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = array_merge($_GET, $_POST);
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

ENH: Allow web API parameters to be passed as POST parameters in addition to the normal GET parameters