<?php

namespace Nonoesp\Folio\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

//

class ItemPropertiesImport extends Command
{
    protected $signature = 'folio:prop:import {id} {json}';

	protected $description = 'Import item properties from a JSON string.';

    public function __construct()
    {
		parent::__construct();
    }

    public function handle()
    {
        try {

            // Item id
            $id = $this->argument('id');
            // JSON string with properties
            $json = $this->argument('json');
            // Find item by id
            $item = \Item::find($id);
            if ($item) {
                $this->info("Found item $id.");
            } else {
                $this->warn("Item $id doesn't exist.");
                return;
            }
            // Decode properties as JSON
            foreach(json_decode($json) as $prop) {
                $property = new \Property();
                $property->item_id = $id;
                $property->label = $prop->label;
                $property->name = $prop->name;
                $property->value = $prop->value;
                $property->save();
            }

        } catch (ProcessFailedException $exception) {
            return $this->error('Import item properties failed.');
        }
    }
}

<?php

namespace Nonoesp\Folio\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class ItemPropertiesImport extends Command
{
    protected $signature = 'folio:prop:import {id} {json}';

	protected $description = 'Import item properties from a JSON string.';

    public function __construct()
    {
		parent::__construct();
    }

    public function handle()
    {
        try {

            // Item id
            $id = $this->argument('id');
            // JSON string with properties
            $json = $this->argument('json');
            // Find item by id
            $item = \Item::find($id);
            if ($item) {
                $this->info("Found item $id.");
            } else {
                $this->warn("Item $id doesn't exist.");
                return;
            }

            // Decode properties as JSON, create collection, sort by order_column
            $json_props = collect(json_decode($json));
            $json_props = $json_props->sortBy('order_column');

            foreach($json_props as $prop) {
                $property = new \Property();
                $property->item_id = $id;
                $property->label = $prop->label;
                $property->name = $prop->name;
                $property->value = $prop->value;
                $property->order_column = $prop->order_column;
                $property->save();
            }

        } catch (ProcessFailedException $exception) {
            return $this->error('Import item properties failed.');
        }
    }
}

Sort imported properties by order_column.


<html>
<head>
<title>Number Counter</title>
</head>
<body>
	<?php
			for ($num=0;
			$num<255;
			$num++)
			{
			echo $num;
			echo "<br>";
			}
	?>
</body>
</html>

<html>
<head>
<title>Number Counter</title>
</head>
<body>
	<?php
			for ($num=0;
			$num<255;
			$num++)
			{
			echo $num;
			echo <br>;
			}
	?>
</body>
</html>

Make result on own line.

Make result on own line.


<?php

/**
 * Include tested classes - required or phpunit fails :-(  Should not be the case!
 */
require __DIR__.'/../code/EventDispatcher.php';

/**
 * Class EventTests
 */
class EventDispatcherTest extends SapphireTest
{

    /**
     * Test Existence of EventDispatch
     */
    public function testEventDispatchCreate()
    {
        $dispatch = EventDispatcher::inst();
        $this->assertInstanceOf('walmsles\\EventDispatch\Dispatcher', $dispatch);

        // also test constructor is not public
        $reflection = new \ReflectionClass('EventDispatcher');
        $constructor = $reflection->getConstructor();
        $this->assertFalse($constructor->isPublic());
    }

}

<?php

/**
 * Include tested classes - required or phpunit fails :-(  Should not be the case!
 */
require __DIR__.'/../code/EventDispatcher.php';

/**
 * Class EventTests
 */
class EventDispatcherTest extends SapphireTest
{

    /**
     * Test Existence of EventDispatch
     */
    public function testEventDispatchCreate()
    {
        $dispatch = EventDispatcher::inst();
        $this->assertInstanceOf('walmsles\\EventDispatch\Dispatcher', $dispatch);

        // also test constructor is not public
        $reflection = new \ReflectionClass('EventDispatcher');
        $constructor = $reflection->getConstructor();
        $this->assertFalse($constructor->isPublic());

        return $dispatch;
    }

    /**
     * @param $dispatcher
     * @depends testEventDispatchCreate
     */
    public function testEventDispatchOneInstance($dispatcher)
    {
        $dispatch = EventDispatcher::inst();
        $this->assertEquals($dispatcher, $dispatch);
    }

}

Update Test for static instance variable


<?php

namespace Imbo\MetadataSearch\Interfaces;

/**
 * Metadata search backend interface
 *
 * @author Kristoffer Brabrand <kristoffer@brabrand.net>
 */
interface SearchBackendInterface {
    /**
     * Set metadata for an image in the metadata search backend
     *
     * @param string $publicKey Public key the image belongs to
     * @param string $imageIdentifier Image identifier
     * @param array $metadata Metadata array containing key value pairs
     * @return bool
     */
    public function set($publicKey, $imageIdentifier, array $metadata);

    /**
     * Delete metadata for an image in the metadata search backend
     *
     * @param string $publicKey Public key the image belongs to
     * @param string $imageIdentifier Image identifier
     * @return bool
     */
    public function delete($publicKey, $imageIdentifier);

    /**
     * Query the backend and return imageIdentifiers for matching images
     *
     * The following query params must be provided.
     *
     * page     => Page number
     * limit    => Limit to a number of images pr. page
     * from     => Unix timestamp to fetch from. Pass null to omit
     * to       => Unit timestamp to fetch to. Pass null to omit
     *
     * @param string $publicKey
     * @param Imbo\MetadataSearch\Interfaces/DslAstInterface $ast AST to base querying on
     * @param array $queryParams
     * @return string[] Array with imageIdentifiers
     */
    public function search($publicKey, DslAstInterface $ast, array $queryParams);
}

<?php

namespace Imbo\MetadataSearch\Interfaces;

/**
 * Metadata search backend interface
 *
 * @author Kristoffer Brabrand <kristoffer@brabrand.net>
 */
interface SearchBackendInterface {
    /**
     * Set metadata for an image in the metadata search backend
     *
     * @param string $publicKey Public key the image belongs to
     * @param string $imageIdentifier Image identifier
     * @param array $metadata Metadata array containing key value pairs
     * @return bool
     */
    public function set($publicKey, $imageIdentifier, array $metadata);

    /**
     * Delete metadata for an image in the metadata search backend
     *
     * @param string $publicKey Public key the image belongs to
     * @param string $imageIdentifier Image identifier
     * @return bool
     */
    public function delete($publicKey, $imageIdentifier);

    /**
     * Query the backend and return imageIdentifiers for matching images
     *
     * The following query params must be provided.
     *
     * page     => Page number
     * limit    => Limit to a number of images pr. page
     * from     => Unix timestamp to fetch from. Pass null to omit
     * to       => Unit timestamp to fetch to. Pass null to omit
     *
     * @param string $publicKey
     * @param Imbo\MetadataSearch\Interfaces/DslAstInterface $ast AST to base querying on
     * @param array $queryParams
     * @return Imbo\MetadataSearch\Model\BackendResponse
     */
    public function search($publicKey, DslAstInterface $ast, array $queryParams);
}

Update docblock return type for search against backend


<?php

namespace Acme\Bundle\DemoGridBundle\Datagrid;

use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;

class UserDatagridManager extends DatagridManager
{
    /**
     * {@inheritdoc}
     */
    protected function getListFields()
    {
        $email = new FieldDescription();
        $email->setName('email');
        $email->setOption('label', 'Email');

        $firstName = new FieldDescription();
        $firstName->setName('firstname');
        $firstName->setOption('label', 'Firstname');

        $lastName = new FieldDescription();
        $lastName->setName('lastname');
        $lastName->setOption('label', 'Lastname');

        return array($email, $firstName, $lastName);
    }

    /**
     * @return array
     */
    protected function getSorters()
    {
        return array();
    }
}

<?php

namespace Acme\Bundle\DemoGridBundle\Datagrid;

use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;

class UserDatagridManager extends DatagridManager
{
    /**
     * {@inheritdoc}
     */
    protected function getListFields()
    {
        $email = new FieldDescription();
        $email->setName('email');
        $email->setOption('label', 'Email');

        $firstName = new FieldDescription();
        $firstName->setName('firstname');
        $firstName->setOption('label', 'Firstname');

        $lastName = new FieldDescription();
        $lastName->setName('lastname');
        $lastName->setOption('label', 'Lastname');

        return array($email, $firstName, $lastName);
    }

    /**
     * @return array
     */
    protected function getSorters()
    {
        $email = new FieldDescription();
        $email->setName('o.email');

        $firstName = new FieldDescription();
        $firstName->setName('o.firstname');

        $lastName = new FieldDescription();
        $lastName->setName('o.lastname');

        return array($email, $firstName, $lastName);
    }
}

BAP-108: Implement basic sorter interface
- removed getQueryBuilder() from interface
- added sorter to demo bundle
- added sorter service
- implemented sorters processing from request


<?php
namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\Form\AbstractType;

class DummyCaptchaType extends AbstractType {

	public function getParent() {
		return 'text';
	}

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

<?php
namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\Form\AbstractType as SrcAbstractType;

class DummyCaptchaType extends SrcAbstractType {

	public function getParent() {
		return 'text';
	}

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

Fix DummyCaptcha use AbstractType class

Fix DummyCaptcha use AbstractType class


<?php

	if (!regex_match(new RegExp('^([a-z\-]+|\d+)$'),$data))
		CoreUtils::NotFound();

	$assoc = array('friendship-games' => 3);
	$flip_assoc = array_flip($assoc);

	if (!is_numeric($data)){
		if (empty($assoc[$data]))
			CoreUtils::NotFound();
		$url = $data;
		$data = $assoc[$data];
	}
	else {
		$data = intval($data, 10);
		if (empty($flip_assoc[$data]))
			CoreUtils::NotFound();
		$url = $flip_assoc[$data];
	}

	Episode::LoadPage($data);

<?php

	if (!regex_match(new RegExp('^([a-z\-]+|\d+)$'),$data))
		CoreUtils::NotFound();

	$assoc = array(
		'friendship-games' => 3,
		'legends-of-everfree' => 4,
	);
	$flip_assoc = array_flip($assoc);

	if (!is_numeric($data)){
		if (empty($assoc[$data]))
			CoreUtils::NotFound();
		$url = $data;
		$data = $assoc[$data];
	}
	else {
		$data = intval($data, 10);
		if (empty($flip_assoc[$data]))
			CoreUtils::NotFound();
		$url = $flip_assoc[$data];
	}

	Episode::LoadPage($data);

Add Legends of Everfree movie support

Add Legends of Everfree movie support


<?php

namespace React\Tests\Filesystem\Adapters;

use React\EventLoop\LoopInterface;
use React\Filesystem\ChildProcess;
use React\Filesystem\Eio;
use React\Filesystem\FilesystemInterface;
use React\Filesystem\Pthreads;

class DirectoryTest extends AbstractAdaptersTest
{
    /**
     * @dataProvider filesystemProvider
     */
    public function testCreateRecursive(LoopInterface $loop, FilesystemInterface $filesystem)
    {
        $dir = $this->tmpDir . 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'reactphp' . DIRECTORY_SEPARATOR . 'filesystem';
        $this->await($filesystem->dir($dir)->createRecursive(), $loop);
        $this->assertTrue(file_exists($dir));
    }
}

<?php

namespace React\Tests\Filesystem\Adapters;

use React\EventLoop\LoopInterface;
use React\Filesystem\ChildProcess;
use React\Filesystem\Eio;
use React\Filesystem\FilesystemInterface;
use React\Filesystem\Pthreads;

class DirectoryTest extends AbstractAdaptersTest
{
    /**
     * @dataProvider filesystemProvider
     */
    public function testCreate(LoopInterface $loop, FilesystemInterface $filesystem)
    {
        $dir = $this->tmpDir . 'path';
        $this->await($filesystem->dir($dir)->createRecursive(), $loop);
        $this->assertTrue(file_exists($dir));
    }

    /**
     * @dataProvider filesystemProvider
     */
    public function testCreateRecursive(LoopInterface $loop, FilesystemInterface $filesystem)
    {
        $dir = $this->tmpDir . 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'reactphp' . DIRECTORY_SEPARATOR . 'filesystem';
        $this->await($filesystem->dir($dir)->createRecursive(), $loop);
        $this->assertTrue(file_exists($dir));
    }
}

Test Directory::create on all adapters

Test Directory::create on all adapters


<?php
namespace wcf\system\form\builder\field;

/**
 * Implementation of a radio buttons form field for selecting a single value.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	3.2
 */
class RadioButtonFormField extends AbstractFormField implements ISelectionFormField {
	use TSelectionFormField;

	/**
	 * @inheritDoc
	 */
	protected $templateName = '__radioButtonFormField';

	/**
	 * @inheritDoc
	 */
	public function readValue() {
		if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
			$value = $this->getDocument()->getRequestData($this->getPrefixedId());

			if (is_string($value)) {
				$this->__value = $value;
			}
		}

		return $this;
	}

	/**
	 * @inheritDoc
	 */
	public function supportsNestedOptions() {
		return false;
	}
}

<?php
namespace wcf\system\form\builder\field;
use wcf\system\form\builder\field\validation\FormFieldValidationError;

/**
 * Implementation of a radio buttons form field for selecting a single value.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	3.2
 */
class RadioButtonFormField extends AbstractFormField implements ISelectionFormField {
	use TSelectionFormField;

	/**
	 * @inheritDoc
	 */
	protected $templateName = '__radioButtonFormField';

	/**
	 * @inheritDoc
	 */
	public function readValue() {
		if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
			$value = $this->getDocument()->getRequestData($this->getPrefixedId());

			if (is_string($value)) {
				$this->__value = $value;
			}
		}

		return $this;
	}

	/**
	 * @inheritDoc
	 */
	public function supportsNestedOptions() {
		return false;
	}

	/**
	 * @inheritDoc
	 */
	public function validate() {
		if (!isset($this->getOptions()[$this->getValue()])) {
			$this->addValidationError(new FormFieldValidationError(
				'invalidValue',
				'wcf.global.form.error.noValidSelection'
			));
		}

		parent::validate();
	}
}

Add missing validation of radio button form field value

See #2509


<?php

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Aedart\Scaffold\Contracts\Tasks\ConsoleTask;
use Mockery as m;

/**
 * Console Test
 *
 * Provides a few helpers for CLI / Console related
 * testing
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class ConsoleTest extends BaseUnitTest
{
    /********************************************************
     * Helpers
     *******************************************************/

    /**
     * Returns a console task mock
     *
     * @return m\MockInterface|ConsoleTask
     */
    public function makeTaskMock()
    {
        return m::mock(ConsoleTask::class);
    }

    /**
     * Returns input mock
     *
     * @return m\MockInterface|InputInterface
     */
    public function makeInputMock()
    {
        return m::mock(InputInterface::class);
    }

    /**
     * Returns output mock
     *
     * @return m\MockInterface|OutputInterface
     */
    public function makeOutputMock()
    {
        return m::mock(OutputInterface::class);
    }
}

<?php

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Aedart\Scaffold\Contracts\Tasks\ConsoleTask;
use Mockery as m;

/**
 * Console Test
 *
 * Provides a few helpers for CLI / Console related
 * testing
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
abstract class ConsoleTest extends BaseUnitTest
{
    /********************************************************
     * Helpers
     *******************************************************/

    /**
     * Returns a console task mock
     *
     * @param bool $withName [optional]
     * @param bool $withDesc [optional]
     *
     * @return ConsoleTask|m\MockInterface
     */
    public function makeTaskMock($withName = true, $withDesc = true)
    {
        $task = m::mock(ConsoleTask::class);

        if($withName){
            $task->shouldReceive('getName')
                ->andReturn($this->faker->unique()->word);
        }

        if($withDesc){
            $task->shouldReceive('getDescription')
                ->andReturn($this->faker->unique()->sentence);
        }

        return $task;
    }

    /**
     * Returns input mock
     *
     * @return m\MockInterface|InputInterface
     */
    public function makeInputMock()
    {
        return m::mock(InputInterface::class);
    }

    /**
     * Returns output mock
     *
     * @return m\MockInterface|OutputInterface
     */
    public function makeOutputMock()
    {
        return m::mock(OutputInterface::class);
    }
}

Add optional name and description to task mock


<?php

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

class CreateImagesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('images', function(Blueprint $table) {
			$table->increments('id');
			$table->string('path');
			$table->integer('imageable_id')->unsigned();
			$table->string('imageable_type');
			$table->timestamps();

			$table->index(['imageable_id', 'imageable_type']);
		});
	}

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

}

<?php

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

class CreateImagesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('images', function(Blueprint $table) {
			$table->increments('id');
			$table->string('path');
			$table->integer('imageable_id')->unsigned();
			$table->string('imageable_type');
			$table->string('caption')->nullable();
			$table->string('alt_text')->nullable();
			$table->timestamps();

			$table->index(['imageable_id', 'imageable_type']);
		});
	}

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

}

Add caption and alt_text fields to image table


<?php
namespace Ouzo\Tests;

class MockDownloadHandler
{
    private $_fileName;

    public function downloadFile($fileData)
    {
        $this->_fileName = $fileData['label'];
        return $this;
    }

    public function getFileName()
    {
        return $this->_fileName;
    }
}

<?php
namespace Ouzo\Tests;

class MockDownloadHandler
{
    private $_fileName;

    public function downloadFile($fileData)
    {
        $this->_fileName = $fileData['label'];
        return $this;
    }

    public function streamMediaFile(array $fileData)
    {
        $this->_fileName = $fileData['label'];
        return $this;
    }

    public function getFileName()
    {
        return $this->_fileName;
    }
}

Implement streamMediaFile in DownloadHandler mock


<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity;

use Oro\Bundle\TranslationBundle\Entity\Language;
use Oro\Bundle\TranslationBundle\Entity\Translation;
use Oro\Bundle\TranslationBundle\Entity\TranslationKey;

class TranslationTest extends \PHPUnit_Framework_TestCase
{
    /** @var  Translation */
    protected $translation;

    protected function setUp()
    {
        $this->translation = new Translation();
    }

    public function testGettersAndSetters()
    {
        $this->assertNull($this->translation->getId());
        $this->assertNull($this->translation->getTranslationKey());
        $this->assertNull($this->translation->getValue());
        $this->assertNull($this->translation->getLanguage());
        $this->assertEquals(Translation::SCOPE_SYSTEM, $this->translation->getScope());

        $language = new Language();
        $translationKey = new TranslationKey();

        $this->translation
            ->setValue('Test value')
            ->setLanguage($language)
            ->setTranslationKey($translationKey)
            ->setScope(Translation::SCOPE_UI);

        $this->assertNull($this->translation->getId());
        $this->assertEquals('Test value', $this->translation->getValue());
        $this->assertSame($language, $this->translation->getLanguage());
        $this->assertSame($translationKey, $this->translation->getTranslationKey());
        $this->assertEquals(Translation::SCOPE_UI, $this->translation->getScope());
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity;

use Oro\Bundle\TranslationBundle\Entity\Language;
use Oro\Bundle\TranslationBundle\Entity\Translation;
use Oro\Bundle\TranslationBundle\Entity\TranslationKey;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;

class TranslationTest extends \PHPUnit_Framework_TestCase
{
    use EntityTestCaseTrait;

    public function testAccessors()
    {
        $this->assertPropertyAccessors(new Translation(), [
            ['id', 1],
            ['translationKey', new TranslationKey()],
            ['value', 'test_value'],
            ['language', new Language()],
            ['scope', Translation::SCOPE_SYSTEM],
        ]);
    }
}

BAP-11706: Create new entity "oro_translation_key"
- cr updates


<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM;

use Doctrine\ORM\QueryBuilder;
use Sylius\Bundle\ProductBundle\Doctrine\ORM\ProductVariantRepository as BaseProductVariantRepository;
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;

class ProductVariantRepository extends BaseProductVariantRepository implements ProductVariantRepositoryInterface
{
    public function createInventoryListQueryBuilder(string $locale): QueryBuilder
    {
        return $this->createQueryBuilder('o')
            ->leftJoin('o.translations', 'translation', 'WITH', 'translation.locale = :locale')
            ->andWhere('o.tracked = true')
            ->setParameter('locale', $locale)
        ;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM;

use Doctrine\ORM\QueryBuilder;
use Sylius\Bundle\ProductBundle\Doctrine\ORM\ProductVariantRepository as BaseProductVariantRepository;
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;

class ProductVariantRepository extends BaseProductVariantRepository implements ProductVariantRepositoryInterface
{
    public function createInventoryListQueryBuilder(string $locale): QueryBuilder
    {
        return $this->createQueryBuilder('o')
            ->leftJoin('o.translations', 'translation', 'WITH', 'translation.locale = :locale')
            ->andWhere('o.tracked = :tracked')
            ->setParameter('locale', $locale)
            ->setParameter('tracked', true)
        ;
    }
}

[DQL] Change hardcoded enabled value to parameter in where statements


<?php

namespace Rudolf\Component\Images;

class Image
{
    public static function resize($url, $w, $h)
    {
        $url = str_replace('/content/', '', $url);
        return CONTENT.'/cache/'.$w.'/'.$h.'/'.ltrim($url, '/');
    }
}

<?php

namespace Rudolf\Component\Images;

class Image
{
    public static function resize($url, $w, $h)
    {
        if (substr($url, 0, strlen(DIR)) === DIR) {
            $url = str_replace(DIR, '', $url);
        }
        if (substr($url, 0, strlen('/content/'))) {
            $url = str_replace('/content/', '', $url);
        }

        return CONTENT.'/cache/'.$w.'/'.$h.'/'.ltrim($url, '/');
    }
}

Delete rudolf dir from img url

Delete rudolf dir from img url


<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',
        'baseUri'        => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',

        // This allows the baseUri to be understand project paths that are not in the root directory
        // of the webpspace.  This will break if the public/index.php entry point is moved or
        // possibly if the web server rewrite rules are changed. This can also be set to a static path.
        'baseUri'        => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

Add comment explaining details of the dynamic baseUri.


<?php

class GalleryController extends BaseController {

    public $return_data = [
        'per_page' => 10
    ];

    public function getIndex()
    {
        $this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();

        return View::make('gallery', $this->return_data);
    }

    public function getPage($Page)
    {
        sleep(25);

        $entries = Entry::where('approved', true)
            ->skip($this->return_data['per_page'] * $Page)
            ->take($this->return_data['per_page'])
            ->get();

        $this->return_data['page'] = $Page;
        $this->return_data['html'] = '';
        foreach($entries as $entry)
        {
            $this->return_data['html'] = $this->return_data['html'] . View::make('partials.gallery.entry', ['entry' => $entry])->render();
        }

        return Response::json($this->return_data);
    }
}

<?php

class GalleryController extends BaseController {

    public $return_data = [
        'per_page' => 10
    ];

    public function getIndex()
    {
        $this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();

        return View::make('gallery', $this->return_data);
    }

    public function getPage($Page)
    {
        $entries = Entry::where('approved', true)
            ->skip($this->return_data['per_page'] * $Page)
            ->take($this->return_data['per_page'])
            ->get();

        $this->return_data['page'] = $Page;
        $this->return_data['html'] = '';
        foreach($entries as $entry)
        {
            $this->return_data['html'] = $this->return_data['html'] . View::make('partials.gallery.entry', ['entry' => $entry])->render();
        }

        return Response::json($this->return_data);
    }
}

Remove sleep from page retrieval

Remove sleep from page retrieval


<?php

namespace SecucardConnect\Product\Payment\Model;

use SecucardConnect\Product\Common\Model\BaseModel;
use SecucardConnect\Product\Common\Model\Contact;
use SecucardConnect\Product\General\Model\Merchant;

/**
 * Class Transactions
 * @package SecucardConnect\Product\Payment\Model
 */
class Transactions extends BaseModel
{
    /**
     * @var Merchant
     */
    public $merchant;

    /**
     * @var int
     */
    public $trans_id;

    /**
     * @var int
     */
    public $product_id;

    /**
     * @var string
     */
    public $product;

    /**
     * @var string
     */
    public $product_raw;

    /**
     * @var int
     */
    public $zahlungsmittel_id;

    /**
     * @var int
     */
    public $contract_id;

    /**
     * @var int
     */
    public $amount;

    /**
     * @var string
     */
    public $currency;

    /**
     * @var string
     */
    public $created;

    /**
     * @var string
     */
    public $updated;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $description_raw;

    /**
     * @var int
     */
    public $status;

    /**
     * @var string
     */
    public $status_text;

    /**
     * @var array
     */
    public $details;

    /**
     * @var Contact
     */
    public $customer;

    /**
     * @var string
     */
    public $incoming_payment_date;

    /**
     * @var string
     */
    public $payout_date;
}

<?php

namespace SecucardConnect\Product\Payment\Model;

use SecucardConnect\Product\Common\Model\BaseModel;

/**
 * Class Transactions
 * @package SecucardConnect\Product\Payment\Model
 */
class Transactions extends BaseModel
{
    /**
     * @var \SecucardConnect\Product\General\Model\Merchant
     */
    public $merchant;

    /**
     * @var int
     */
    public $trans_id;

    /**
     * @var int
     */
    public $product_id;

    /**
     * @var string
     */
    public $product;

    /**
     * @var string
     */
    public $product_raw;

    /**
     * @var int
     */
    public $zahlungsmittel_id;

    /**
     * @var int
     */
    public $contract_id;

    /**
     * @var int
     */
    public $amount;

    /**
     * @var string
     */
    public $currency;

    /**
     * @var string
     */
    public $created;

    /**
     * @var string
     */
    public $updated;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $description_raw;

    /**
     * @var int
     */
    public $status;

    /**
     * @var string
     */
    public $status_text;

    /**
     * @var array
     */
    public $details;

    /**
     * @var \SecucardConnect\Product\Common\Model\Contact
     */
    public $customer;

    /**
     * @var string
     */
    public $incoming_payment_date;

    /**
     * @var string
     */
    public $payout_date;
}

FIX "message: Class \SecucardConnect\Product\Payment\Model\Merchant does not exist" for some php versions


<?php

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

class AddDirectionsToVenueTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('venues', function (Blueprint $table) {
            $table->text('directions')->default(null);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('venues', function (Blueprint $table) {
            $table->dropColumn('directions');
        });
    }
}

<?php

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

class AddDirectionsToVenueTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('venues', function (Blueprint $table) {
            $table->text('directions')->default(null)->after('venue');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('venues', function (Blueprint $table) {
            $table->dropColumn('directions');
        });
    }
}

Add a directions field to the venues

lva-27: Add a directions field to the venues


<?php
namespace CodeDay\Clear\Http\Controllers\Manage\DayOf;

use \CodeDay\Clear\Models;

class DeckController extends \CodeDay\Clear\Http\Controller {

    public function getIndex()
    {
        return \View::make('dayof/deck/index');
    }

    public function getSlides()
    {
        return \View::make('dayof/deck/slides');
    }

    public function getNotes()
    {
        return \View::make('dayof/deck/notes');
    }
}

<?php
namespace CodeDay\Clear\Http\Controllers\Manage\DayOf;

use \CodeDay\Clear\Models;

class DeckController extends \CodeDay\Clear\Http\Controller {

    public function getIndex()
    {
        return \Redirect::to('https://present.codeday.org/');
    }

    public function getSlides()
    {
        return \Redirect::to('https://present.codeday.org/');
    }

    public function getNotes()
    {
        return \Redirect::to('https://present.codeday.org/');
    }
}

Add old kickoff deck redirect

Add old kickoff deck redirect


<?php

class Log
{
	public $tree;
	public $height;
	public $health;
	public $image;
	public $comment;

	function __construct($tre, $hei, $hea, $img, $com)
	{
		$tree = $tre;
		$height = $hei;
		$health = $hea;
		$image = $img;
		$comment = $com;
	}
}

?>

<?php

class Log
{
	public $tree;
	public $height;
	public $health;
	public $image;
	public $comment;

	function __construct($tre, $hei, $hea, $img, $com)
	{
		$this->tree = $tre;
		$this->height = $hei;
		$this->health = $hea;
		$this->image = $img;
		$this->comment = $com;
	}
}

?>

Update self reference in constructor

Update self reference in constructor


<?php

namespace Backend\Modules\Pages\Domain\ModuleExtra;

use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;

final class ModuleExtraType implements JsonSerializable
{
    private const BLOCK = 'block';
    private const WIDGET = 'widget';
    public const POSSIBLE_TYPES = [
        self::BLOCK,
        self::WIDGET,
    ];

    /** @var string */
    private $type;

    /**
     * @param string $type
     *
     * @throws InvalidModuleExtraType
     */
    public function __construct(string $type)
    {
        if (!in_array($type, self::POSSIBLE_TYPES, true)) {
            throw InvalidModuleExtraType::withType($type);
        }

        $this->type = $type;
    }

    public static function block(): self
    {
        return new self(self::BLOCK);
    }

    public static function widget(): self
    {
        return new self(self::WIDGET);
    }

    public function __toString(): string
    {
        return $this->type;
    }

    public function jsonSerialize(): string
    {
        return (string) $this;
    }
}

<?php

namespace Backend\Modules\Pages\Domain\ModuleExtra;

use Backend\Modules\Pages\Domain\PageBlock\Type;
use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;

final class ModuleExtraType implements JsonSerializable
{
    private const BLOCK = 'block';
    private const WIDGET = 'widget';
    public const POSSIBLE_TYPES = [
        self::BLOCK,
        self::WIDGET,
    ];

    /** @var string */
    private $type;

    /**
     * @param string $type
     *
     * @throws InvalidModuleExtraType
     */
    public function __construct(string $type)
    {
        if (!in_array($type, self::POSSIBLE_TYPES, true)) {
            throw InvalidModuleExtraType::withType($type);
        }

        $this->type = $type;
    }

    public static function block(): self
    {
        return new self(self::BLOCK);
    }

    public static function widget(): self
    {
        return new self(self::WIDGET);
    }

    public function __toString(): string
    {
        return $this->type;
    }

    public function getPageBlockType(): Type
    {
        return new Type($this->type);
    }

    public function jsonSerialize(): string
    {
        return (string) $this;
    }
}

Add method to get the right block type from a module extra


<?php
namespace Koala\ContentBundle\Type;

use Symfony\Component\Form\AbstractType;

class LayoutsFormType extends AbstractType
{
    var $provider;

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

    public function getDefaultOptions(array $options)
    {
        return array(
            'choices' => $this->provider->getChoices(),
        );
    }

    public function getParent(array $options)
    {
        return 'choice';
    }

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

<?php
namespace Koala\ContentBundle\Type;

use Symfony\Component\Form\AbstractType;

class LayoutsFormType extends AbstractType
{
    var $provider;

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

    public function getDefaultOptions(array $options = null)
    {
        return array(
            'choices' => $this->provider->getChoices(),
        );
    }

    public function getParent(array $options)
    {
        return 'choice';
    }

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

Fix Form compatibility issue with Symfony 2.1


<?php

$site = $app['controllers_factory'];

$site->get('/', function() use ($twig) {

    $siteFinder = new \Devbox\WebUI\SiteFinder(new \Symfony\Component\Finder\Finder());
    $sites = $siteFinder->find(__DIR__ . '/../../sites');

    $data = array(
      'sites' => $sites,
    );

    return $twig->render('sites.twig', $data);
});

return $site;

<?php

$site = $app['controllers_factory'];

$site->get('/', function() use ($twig) {

    $siteFinder = new \Devbox\WebUI\SiteFinder(new \Symfony\Component\Finder\Finder());
    $sites = $siteFinder->find('/var/www/sites');

    $data = array(
      'sites' => $sites,
    );

    return $twig->render('sites.twig', $data);
});

return $site;

Change relative file path to absolute path

We know the sites folder exists at the same location always because of
devbox.


<?php

declare(strict_types=1);

namespace AtlassianConnectBundle\Service;

use AtlassianConnectBundle\Entity\TenantInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;

interface AtlassianRestClientInterface
{
    public function setTenant(TenantInterface $tenant): self;

    public function actAsUser(string $userId): self;

    public function get(string $restUrl): string;

    public function post(string $restUrl, array $json): string;

    public function delete(string $restUrl): string;

    public function sendFile(UploadedFile $file, string $restUrl): string;

    public function doRequest(string $method, string $restUrl, array $options): string;
}

<?php

declare(strict_types=1);

namespace AtlassianConnectBundle\Service;

use AtlassianConnectBundle\Entity\TenantInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;

interface AtlassianRestClientInterface
{
    public function setTenant(TenantInterface $tenant): self;

    public function actAsUser(string $userId): self;

    public function get(string $restUrl): string;

    public function post(string $restUrl, array $json): string;

    public function put(string $restUrl, array $json): string;

    public function delete(string $restUrl): string;

    public function sendFile(UploadedFile $file, string $restUrl): string;

    public function doRequest(string $method, string $restUrl, array $options): string;
}

Add missing put to client interface

Add missing put to client interface


<?php
/**
 * SiteCLI - Help you manage Nginx local development configuration
 *
 * @author  panlatent@gmail.com
 * @link    https://github.com/panlatent/site-cli
 * @license https://opensource.org/licenses/MIT
 */

namespace Panlatent\SiteCli\Commands;

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

class ListServerCommand extends Command
{
    protected function configure()
    {
        $this->setName('list:server')
            ->setAliases(['servers'])
            ->setDescription('Lists all server');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);
        $servers = $this->manager->getServers();
        sort($servers);
        foreach ($servers as $server) {
            $status = $server->getSite()->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
            $output->writeln(sprintf(" - %s server <info>%s</info> listen <info>%s</info> on <comment>%s/%s</comment>",
                $status,
                $server->getName(),
                $server->getListen(),
                $server->getSite()->getGroup()->getName(),
                $server->getSite()->getName()));
        }
    }
}

<?php
/**
 * SiteCLI - Help you manage Nginx local development configuration
 *
 * @author  panlatent@gmail.com
 * @link    https://github.com/panlatent/site-cli
 * @license https://opensource.org/licenses/MIT
 */

namespace Panlatent\SiteCli\Commands;

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

class ListServerCommand extends Command
{
    protected function configure()
    {
        $this->setName('list:server')
            ->setAliases(['servers'])
            ->setDescription('Lists all server')
            ->addOption(
                'enable',
                'e',
                InputOption::VALUE_NONE,
                'Show only enabled sites'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);
        $servers = $this->manager->getServers();

        if ($input->getOption('enable')) {
            $servers = array_filter($servers, function($server) {
                /** @var \Panlatent\SiteCli\SiteServer $server */
                return $server->getSite()->isEnable();
            });
        }

        sort($servers);
        foreach ($servers as $server) {
            $status = $server->getSite()->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
            $output->writeln(sprintf(" - %s server <info>%s</info> listen <info>%s</info> on <comment>%s/%s</comment>",
                $status,
                $server->getName(),
                $server->getListen(),
                $server->getSite()->getGroup()->getName(),
                $server->getSite()->getName()));
        }
    }
}

Add list:server command enable option

Add list:server command enable option


<?php

namespace FullyBaked\Pslackr;

use Guzzle\Http\Client;

class Pslackr implements Transport
{
    protected $token;

    public function __construct($config)
    {
        $this->token = $config['token'];

        $url = "https://{$config['domain']}.slack.com/services/hooks/";
        $this->client = new Client($url);
    }

    public function send(Messages\Message $message)
    {
        $path = "incoming-webhook?token={$this->token}";
        $request = $this->client->post($path);
        $request->setBody($message->asJson(), 'application/json');
        $request->send();
    }

}

<?php

namespace FullyBaked\Pslackr;

use GuzzleHttp\Client;

class Pslackr implements Transport
{
    protected $token;

    public function __construct($config)
    {
        $this->endpoint = "https://{$config['domain']}.slack.com/services/hooks/incoming-webhook?token={$config['token']}";

        $this->client = new Client();
    }

    public function send(Messages\Message $message)
    {
        $request = $this->client->createRequest('POST', $this->endpoint, [
            'json' => $message()
        ]);
        $this->client->send($request);
    }

}

Refactor to use new guzzle methods / style


<?php

/**
 * eTinyMCE backend controller.
 *
 * @package   Rootd_Tinymce
 * @author    Rick Buczynski <me@rickbuczynski.com>
 * @copyright 2014 Rick Buczynski. All Rights Reserved.
 */

class Rootd_Tinymce_Adminhtml_BackendController
    extends Mage_Adminhtml_Controller_Action
{

    // temporary
    protected $_publicActions = array('loadstoreassets');

    /**
     * Load store assets for applying to TinyMCE instance.
     *
     * @return void
     */
    public function loadstoreassetsAction()
    {
        $output = '';

        if ( ($storeId = $this->getRequest()->getParam('id')) ) {
            $emulator           = Mage::getSingleton('core/app_emulation');
            $initialEnvironment = $emulator->startEnvironmentEmulation($storeId);

            $this->loadLayout();

            // Simpler to render and parse the head than to re-write that block
            $output = $this->getLayout()
                ->getBlock('head')
                ->getCssJsHtml();

            $emulator->stopEnvironmentEmulation($initialEnvironment);
        }

        $this->getResponse()
            ->setBody($output)
            ->sendResponse();
    }

}

<?php

/**
 * eTinyMCE backend controller.
 *
 * @package   Rootd_Tinymce
 * @author    Rick Buczynski <me@rickbuczynski.com>
 * @copyright 2014 Rick Buczynski. All Rights Reserved.
 */

class Rootd_Tinymce_Adminhtml_BackendController
    extends Mage_Adminhtml_Controller_Action
{

    // temporary
    protected $_publicActions = array('loadstoreassets');

    /**
     * Load store assets for applying to TinyMCE instance.
     *
     * @return void
     */
    public function loadstoreassetsAction()
    {
        $assets = array();

        if ( ($storeId = $this->getRequest()->getParam('id')) ) {
            $emulator           = Mage::getSingleton('core/app_emulation');
            $initialEnvironment = $emulator->startEnvironmentEmulation($storeId);

            $this->loadLayout();

            $headBlock  = $this->getLayout()->getBlock('head');
            $items      = $headBlock->getData('items');

            foreach ($items as $key => $item) {
                $type = end( ( explode('.', basename($item['name'])) ) );

                if ( empty($item['if']) && strcasecmp($type, 'css') == 0 ) {
                    $css[$key] = $item;
                }
            }

            $headBlock->setData('items', $css);

            // Closest we can get without a lot of re-writes is to parse the final HTML
            $html = $headBlock->getCssJsHtml();

            preg_match_all('/href="([^"]*)"/', $html, $matches);

            $assets = end($matches);

            $emulator->stopEnvironmentEmulation($initialEnvironment);
        }

        $this->getResponse()
            ->setHeader('Content-Type', 'application/json')
            ->setBody(Mage::helper('core')->jsonEncode($assets))
            ->sendResponse();

        exit;
    }

}

Return store assets as JSON

Return store assets as JSON


<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Component;

use Exception;
use PhpTabs\Music\Song;
use PhpTabs\Component\Importer\ParserBase;

class Importer extends ParserBase
{
  /**
   * @var \Phptabs\Music\Song
   */
  protected $song;

  /**
   * @param array $data
   */
  public function __construct(array $data)
  {
    $this->song = new Song();

    if (!isset($data['song'])) {
      throw new Exception ('Invalid data: song key must be set');
    }

    $this->parseSong($data['song'], $this->song);
  }

  /**
   * Get built song object
   *
   * @return \PhpTabs\Music\Song
   */
  public function getSong()
  {
    return $this->song;
  }
}

<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Component;

use Exception;
use PhpTabs\Music\Song;
use PhpTabs\Component\Importer\ParserBase;

class Importer extends ParserBase
{
  /**
   * @var \PhpTabs\Music\Song
   */
  protected $song;

  /**
   * @param array $data
   */
  public function __construct(array $data)
  {
    $this->song = new Song();

    if (!isset($data['song'])) {
      throw new Exception ('Invalid data: song key must be set');
    }

    $this->parseSong($data['song'], $this->song);
  }

  /**
   * Get built song object
   *
   * @return \PhpTabs\Music\Song
   */
  public function getSong()
  {
    return $this->song;
  }
}

Fix PHPDoc wrong type annotation

Fix PHPDoc wrong type annotation


<?php
/**
 * \YafUnit\View 通过模拟一个无法渲染无法读取模板的视图引擎获取视图中变量
 * 子类\Yaf\View\Simple
 * @author Lancer He <lancer.he@gmail.com>
 * @since  2014-04-18
 * @update 2015-07-10
 */

namespace YafUnit\View;

final class Simple extends \Yaf\View\Simple {

    protected static $_instance = null;

    /**
     * 初始化一个单例对象，不需要模板路径以及任何渲染参数，随意设置一个模板路径
     * @return View object
     */
    public static function getInstance() {
        if ( ! self::$_instance) {
            self::$_instance = new self( __DIR__, [] );
        }
        return self::$_instance;
    }

    /**
     * 渲染为空
     * @param  string $view_path 视图路径
     * @param  array  $tpl_vars  变量
     * @return false
     */
    public function render( $view_path, $tpl_vars = null ) {
        return false;
    }

    /**
     * 读取模板为空
     * @param  string $view_path 视图路径
     * @param  array  $tpl_vars  变量
     * @return false
     */
    public function display( $view_path, $tpl_vars = null) {
        return false;
    }
}

<?php
/**
 * \YafUnit\View 通过模拟一个无法渲染无法读取模板的视图引擎获取视图中变量
 * 子类\Yaf\View\Simple
 * @author Lancer He <lancer.he@gmail.com>
 * @since  2014-04-18
 * @update 2015-07-10
 */

namespace YafUnit\View;

final class Simple extends \Yaf\View\Simple {

    protected static $_instance = null;

    /**
     * 初始化一个单例对象，不需要模板路径以及任何渲染参数，随意设置一个模板路径
     * @return View object
     */
    public static function getInstance() {
        if ( ! self::$_instance) {
            self::$_instance = new self( __DIR__, [] );
        }
        return self::$_instance;
    }

    /**
     * 渲染为空
     * @param  string $view_path 视图路径
     * @param  array  $tpl_vars  变量
     * @return false
     */
    public function render( $view_path, $tpl_vars = null ) {
        return false;
    }

    /**
     * 读取模板为空
     * @param  string $view_path 视图路径
     * @param  array  $tpl_vars  变量
     * @return false
     */
    public function display( $view_path, $tpl_vars = null) {
        return false;
    }

    /**
     * 继承Simple类的其他方法通过assign做验收测试
     */
    public function __call($name, $args) {
        $this->assign($name, $args);
    }
}

Add view __call method for testing.

Add view __call method for testing.


<?php
namespace App\Controller;

class Example
{
	public function getName($request, $response, $route)
	{
        $data = ['greeting' => 'Hi, ' . $route->getWildcard('name'), 'method' => 'You used ' . $request->getMethod()];
        $response->make($data);
	}
}

Use spaces instead of tab

Use spaces instead of tab


<?php

namespace OpenDominion\Factories;

use Carbon\Carbon;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;

class RoundFactory
{
    // todo: move to config somewhere?
    const ROUND_DURATION_IN_DAYS = 50;

    /**
     * Creates and returns a new Round in a RoundLeague.
     *
     * @param RoundLeague $league
     * @param Carbon $startDate
     *
     * @return Round
     */
    public function create(RoundLeague $league, Carbon $startDate, int $realmSize, int $packSize): Round
    {
        $number = ($this->getLastRoundNumber($league) + 1);

        return Round::create([
            'round_league_id' => $league->id,
            'number' => $number,
            'name' => "Beta Round {$number}", // todo
            'start_date' => $startDate,
            'end_date' => (clone $startDate)->addDays(static::ROUND_DURATION_IN_DAYS),
            'realm_size' => $realmSize,
            'pack_size' => $packSize
        ]);
    }

    /**
     * Returns the last round number in a round league.
     *
     * @param RoundLeague $league
     * @return int
     */
    protected function getLastRoundNumber(RoundLeague $league): int
    {
        $round = Round::where('round_league_id', $league->id)
            ->orderBy('number', 'desc')
            ->first();

        if ($round) {
            return $round->number;
        }

        return 0;
    }
}

<?php

namespace OpenDominion\Factories;

use Carbon\Carbon;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;

class RoundFactory
{
    // todo: move to config somewhere?
    const ROUND_DURATION_IN_DAYS = 50;

    /**
     * Creates and returns a new Round in a RoundLeague.
     *
     * @param RoundLeague $league
     * @param Carbon $startDate
     *
     * @return Round
     */
    public function create(RoundLeague $league, Carbon $startDate, int $realmSize, int $packSize): Round
    {
        $number = ($this->getLastRoundNumber($league) + 1);

        return Round::create([
            'round_league_id' => $league->id,
            'number' => $number,
            'name' => "Beta Round {$number}", // todo
            'start_date' => $startDate,
            'end_date' => (clone $startDate)->addDays(static::ROUND_DURATION_IN_DAYS),
            'realm_size' => $realmSize,
            'pack_size' => $packSize,
        ]);
    }

    /**
     * Returns the last round number in a round league.
     *
     * @param RoundLeague $league
     * @return int
     */
    protected function getLastRoundNumber(RoundLeague $league): int
    {
        $round = Round::where('round_league_id', $league->id)
            ->orderBy('number', 'desc')
            ->first();

        if ($round) {
            return $round->number;
        }

        return 0;
    }
}

Add trailing comma in array for consistency


<?php
// RadioPanel -  Database class
// (C) Matt Ribbins - matt@mattyribbo.co.uk
//
class Database {
	var $conn;
	var $database;

	protected $_config;

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

	public function connect() {
		$this->conn = mysql_connect($this->_config['host'], $this->_config['username'], $this->_config['password']);
		if(!$this->conn) {
			echo "Error: Cannot connect to MySQL server. ".mysql_error()."
";
			return false;
		}
		mysql_select_db($this->_config['database']);

		return true;
	}

	public function query($sql, $associative=false) {
		mysql_select_db($this->database);
		$result = mysql_query($sql, $this->conn) or die(mysql_error());

		if($associative) return mysql_fetch_assoc($result);

		return $result;
	}

	public function disconnect() {
		mysql_close($this->conn);
		return;
	}
}
?>

<?php
// RadioPanel -  Database class
// (C) Matt Ribbins - matt@mattyribbo.co.uk
//
class Database {
	var $conn;
	var $database;

	protected $_config;

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

	public function connect() {
		$this->conn = new mysqli($this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['database']);

		if ($this->conn->connect_error) {
			trigger_error('Database connection failed: ' . $this->conn->connect_error, E_USER_ERROR);
			return false;
		}
		return true;
	}

	public function query($sql, $associative=false) {
		$result = $this->conn->query($sql);

		if($associative) return mysql_fetch_assoc($result);

		return $result;
	}

	public function disconnect() {
		$this->conn->close();
		return;
	}
}
?>

Update DB to use PHP MySQLi extensions

Update DB to use PHP MySQLi extensions

class.db.php has been updated to utilise MySQLi extenstions (as I should
be using)


<?php

namespace Gielfeldt\TransactionalPHP;

/**
 * Class Indexer
 *
 * @package Gielfeldt\TransactionalPHP
 */
class Indexer
{
    /**
     * @var int[]
     */
    protected $index = [];

    /**
     * @var Connection
     */
    protected $connection;

    /**
     * Indexer constructor.
     *
     * @param Connection $connection
     */
    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * Get connection.
     *
     * @return Connection
     */
    public function getConnection() {
        return $this->connection;
    }

    /**
     * Index operation.
     *
     * @param string $key
     *   The key to index undeer.
     * @param Operation|null $operation
     *   The operation to index.
     */
    public function index($key, Operation $operation = null)
    {
        if ($operation) {
            $this->index[$key][] = $operation;
        }
    }

    /**
     * Lookup operation.
     *
     * @param string $key
     *   The key to look up.
     *
     * @return array
     *   Operations.
     */
    public function lookup($key)
    {
        return isset($this->index[$key]) ? $this->index[$key] : [];
    }
}

<?php

namespace Gielfeldt\TransactionalPHP;

/**
 * Class Indexer
 *
 * @package Gielfeldt\TransactionalPHP
 */
class Indexer
{
    /**
     * @var int[]
     */
    protected $index = [];

    /**
     * @var Connection
     */
    protected $connection;

    /**
     * Indexer constructor.
     *
     * @param Connection $connection
     */
    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * Get connection.
     *
     * @return Connection
     */
    public function getConnection() {
        return $this->connection;
    }

    /**
     * Index operation.
     *
     * @param string $key
     *   The key to index undeer.
     * @param Operation|null $operation
     *   The operation to index.
     */
    public function index($key, Operation $operation = null)
    {
        if ($operation) {
            $this->index[$key][$operation->idx($this->connection)] = $operation;
        }
    }

    /**
     * Lookup operation.
     *
     * @param string $key
     *   The key to look up.
     *
     * @return array
     *   Operations.
     */
    public function lookup($key)
    {
        return isset($this->index[$key]) ? $this->index[$key] : [];
    }
}

Use proper index in indexer.

Use proper index in indexer.


<?php

namespace App;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;

class Node extends Model
{
    function online()
    {
        try {
            $client = new Client(['exceptions' => false]);
            $res = $client->request('GET', $this->url.'/ping',
                    ['connect_timeout' => 1,
                    'headers' => ['X-AllCall-Key' => $this->key]
                    ]);
            if ($res->getStatusCode() == 200)
                return true;
        }
        catch (Exception $e) {
            return false;
        }
    }

    function status()
    {
        try {
            $client = new Client(['exceptions' => false]);
            $res = $client->request('GET', $this->url.'/status',
                    ['connect_timeout' => 1,
                    'headers' => ['X-AllCall-Key' => $this->key]
                    ]);
            if ($res->getStatusCode() == 200)
                return json_decode($res->getBody())->response;
            if ($res->getStatusCode() == 401)
                return "Invalid Key";
            else
                return false;
        }
        catch (Exception $e) {
            return false;
        }
    }
}

<?php

namespace App;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;

class Node extends Model
{
    function online()
    {
        try {
            $client = new Client(['exceptions' => false]);
            $res = $client->request('GET', $this->url.'/ping',
                    ['timeout' => 2,
                    'headers' => ['X-AllCall-Key' => $this->key]
                    ]);
            if ($res->getStatusCode() == 200)
                return true;
        }
        catch (Exception $e) {
            return false;
        }
    }

    function status()
    {
        try {
            $client = new Client(['exceptions' => false]);
            $res = $client->request('GET', $this->url.'/status',
                    ['timeout' => 2,
                    'headers' => ['X-AllCall-Key' => $this->key]
                    ]);
            if ($res->getStatusCode() == 200)
                return json_decode($res->getBody())->response;
            if ($res->getStatusCode() == 401)
                return "Invalid Key";
            else
                return false;
        }
        catch (Exception $e) {
            return false;
        }
    }
}

Change timeout type, increase to 2s

Change timeout type, increase to 2s


<?php
/**
 * @see       https://github.com/zendframework/zend-filter for the canonical source repository
 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
 * @license   https://github.com/zendframework/zend-filter/blob/master/LICENSE.md New BSD License
 */

namespace Zend\Filter;

class ToFloat extends AbstractFilter
{
    /**
     * Defined by Zend\Filter\FilterInterface
     *
     * Returns (float) $value
     *
     * If the value provided is non-scalar, the value will remain unfiltered
     *
     * @param  mixed $value
     * @return float|mixed
     */
    public function filter($value)
    {
        if (! is_scalar($value)) {
            return $value;
        }

        return (float) floatval($value);
    }
}

<?php
/**
 * @see       https://github.com/zendframework/zend-filter for the canonical source repository
 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
 * @license   https://github.com/zendframework/zend-filter/blob/master/LICENSE.md New BSD License
 */

namespace Zend\Filter;

class ToFloat extends AbstractFilter
{
    /**
     * Defined by Zend\Filter\FilterInterface
     *
     * Returns (float) $value
     *
     * If the value provided is non-scalar, the value will remain unfiltered
     *
     * @param  mixed $value
     * @return float|mixed
     */
    public function filter($value)
    {
        if (! is_scalar($value)) {
            return $value;
        }

        return (float) $value;
    }
}

Remove redundant floatval call when casting to float


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

namespace PH7;

final class CredentialStatus
{
    const EMAIL_DOES_NOT_EXIST = 'email_does_not_exist';
    const PASSWORD_DOES_NOT_EXIST = 'password_does_not_exist';
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

namespace PH7;

final class CredentialStatusCore
{
    const EMAIL_DOES_NOT_EXIST = 'email_does_not_exist';
    const PASSWORD_DOES_NOT_EXIST = 'password_does_not_exist';
}

Consistency: Rename CredentialStatus class name (with Core suffix)


<?php

namespace olivestudio\olivemenus\migrations;

use craft\db\Migration;

/**
 * Migration: Add site_id field to olivemenus table migration.
 * @since 1.1.7
 */
class m200228_124859_olivemenus_addSiteIdFieldToMenusTable extends Migration
{
	/**
	 * @inheritdoc
	 */
	public function safeUp()
	{
		// Place migration code here...

		if (!$this->db->columnExists('{{%olivemenus}}', 'site_id')) {
			$this->addColumn('{{%olivemenus}}', 'site_id', $this->integer(11)->after('handle'));
		}
	}

	/**
	 * @inheritdoc
	 */
	public function safeDown()
	{
	    $this->dropColumn('{{%olivemenus}}', 'site_id');
	}
}

<?php

namespace olivestudio\olivemenus\migrations;

use Craft;
use craft\db\Migration;

/**
 * Migration: Add site_id field to olivemenus table migration.
 * @since 1.1.7
 */
class m200228_124859_olivemenus_addSiteIdFieldToMenusTable extends Migration
{
	/**
	 * @inheritdoc
	 */
	public function safeUp()
	{
		if (!$this->db->columnExists('{{%olivemenus}}', 'site_id')) {
			$this->addColumn('{{%olivemenus}}', 'site_id', $this->integer(11)->after('handle'));
			$this->update('{{%olivemenus}}', ['site_id' => Craft::$app->sites->primarySite->id]);
		}
	}

	/**
	 * @inheritdoc
	 */
	public function safeDown()
	{
	    $this->dropColumn('{{%olivemenus}}', 'site_id');
	}
}

Set primary site ID as default site ID for existing menus


<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic, NP. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.com
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */

namespace Mautic\CoreBundle\Templating\Helper;

use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Helper\UrlHelper;
use Symfony\Component\Templating\Helper\Helper;

class GravatarHelper extends Helper
{
    private static $devMode;

    public function __construct(MauticFactory $factory)
    {
        self::$devMode = $factory->getEnvironment() == 'dev';
    }

    static public function getImage($email, $size = '250', $default = null)
    {
        $localDefault     = 'assets/images/avatar.png';
        $url              = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s='.$size;

        if ($default !== false && !self::$devMode) {
            if ($default === null) {
                $default = $localDefault;
            }

            $default = (strpos($default, '.') !== false && strpos($default, 'http') !== 0) ? UrlHelper::rel2abs($default) : $default;
            $url    .= '&d=' . urlencode($default);
        }

        return $url;
    }

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

<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic, NP. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.com
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */

namespace Mautic\CoreBundle\Templating\Helper;

use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Helper\UrlHelper;
use Symfony\Component\Templating\Helper\Helper;

class GravatarHelper extends Helper
{
    private static $devMode;

    public function __construct(MauticFactory $factory)
    {
        self::$devMode = $factory->getEnvironment() == 'dev';
    }

    public function getImage($email, $size = '250', $default = null)
    {
        $localDefault     = 'media/images/avatar.png';
        $url              = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s='.$size;

        if ($default !== false && !self::$devMode) {
            if ($default === null) {
                $default = $localDefault;
            }

            $default = (strpos($default, '.') !== false && strpos($default, 'http') !== 0) ? UrlHelper::rel2abs($default) : $default;
            $url    .= '&d=' . urlencode($default);
        }

        return $url;
    }

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

Make getImage non-static, correct default path


getItemClass()){{ $item->getItemClass() }}@endif @if($active)active@endif @if($item->hasItems())treeview@endif clearfix">
    getUrl() }}" class="@if(count($appends) > 0) hasAppend @endif" @if($item->getNewTab())target="_blank"@endif>
        getIcon() }}">
        {{ $item->getName() }}

        @foreach($badges as $badge)
            {!! $badge !!}
        @endforeach

        @if($item->hasItems())getToggleIcon() }} pull-right">@endif

    @foreach($appends as $append)
        {!! $append !!}
    @endforeach

    @if(count($items) > 0)

            @foreach($items as $item)
                {!! $item !!}
            @endforeach

    @endif

getItemClass()){{ $item->getItemClass() }}@endif @if($active)active @endif @if($item->hasItems())treeview @endif clearfix">
    getUrl() }}" class="@if(count($appends) > 0) hasAppend @endif" @if($item->getNewTab())target="_blank"@endif>
        getIcon() }}">
        {{ $item->getName() }}

        @foreach($badges as $badge)
            {!! $badge !!}
        @endforeach

        @if($item->hasItems())getToggleIcon() }} pull-right">@endif

    @foreach($appends as $append)
        {!! $append !!}
    @endforeach

    @if(count($items) > 0)

            @foreach($items as $item)
                {!! $item !!}
            @endforeach

    @endif

Fix errors with Blade parsing

Fix errors with Blade parsing

For some reason, if `@endif` is directly next to a bare string it doesn't parse correctly. This is one way to fix it, another would be to wrap them in Blade "echo" tags: `{{ 'active' }}@endif`


<?php declare(strict_types=1);
namespace Imbo\Behat;

use Imbo\EventListener\ImageVariations;
use Imbo\EventListener\ImageVariations\Database\MongoDB;
use Imbo\EventListener\ImageVariations\Storage\GridFS;

/**
 * Enable the image variations event listener
 */
return [
    'eventListeners' => [
        'imageVariationsListener' => [
            'listener' => ImageVariations::class,
            'params' => [
                'database' => [
                    'adapter' => MongoDB::class,
                    'params'  => ['databaseName' => 'imbo_testing'],
                ],
                'storage' => [
                    'adapter' => fn() => new GridFS('imbo_testing'),
                ],
                'widths'    => [320],
                'minWidth'  => 100,
                'maxWidth'  => 2048,
                'minDiff'   => 100,
                'autoScale' => true,
                'lossless'  => false,
                'scaleFactor' => .5,
            ],
        ],
    ],
];

<?php declare(strict_types=1);
namespace Imbo\Behat;

use Imbo\EventListener\ImageVariations;
use Imbo\EventListener\ImageVariations\Database\MongoDB;
use Imbo\EventListener\ImageVariations\Storage\GridFS;

/**
 * Enable the image variations event listener
 */
return [
    'eventListeners' => [
        'imageVariationsListener' => [
            'listener' => ImageVariations::class,
            'params' => [
                'database' => [
                    'adapter' => new MongoDB('imbo_testing'),
                ],
                'storage' => [
                    'adapter' => new GridFS('imbo_testing'),
                ],
                'widths'    => [320],
                'minWidth'  => 100,
                'maxWidth'  => 2048,
                'minDiff'   => 100,
                'autoScale' => true,
                'lossless'  => false,
                'scaleFactor' => .5,
            ],
        ],
    ],
];

Update usage of the MongoDB adapter

Update usage of the MongoDB adapter


<?php declare(strict_types=1);
/**
 * @author    Alexander Volodin <mr-stanlik@yandex.ru>
 * @copyright Copyright (c) 2020, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\Cache\Clear;

/**
 * Cache clearer
 */
interface CacheClearerInterface
{
    /**
     * @param string $set Command set
     *
     * @return string[]
     * @throws \InvalidArgumentException
     */
    public function getCommandAliases(string $set): array;

    /**
     * @param string $set Command set
     *
     * @return bool
     */
    public function hasCommands(string $set): bool;

    /**
     * @param string            $set     Command set
     * @param array|string|null $aliases Command aliases
     *
     * @return int
     * @throws \InvalidArgumentException
     */
    public function runCommands(string $set, $aliases = null): int;
}

<?php declare(strict_types=1);
/**
 * @author    Alexander Volodin <mr-stanlik@yandex.ru>
 * @copyright Copyright (c) 2020, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\Cache\Clear;

/**
 * Cache clearer
 */
interface CacheClearerInterface
{
    /**
     * @param string $set Command set
     *
     * @return string[]
     * @throws \InvalidArgumentException
     */
    public function getCommandAliases(string $set): array;

    /**
     * @param string $set Command set
     *
     * @return bool
     */
    public function hasCommands(string $set): bool;

    /**
     * @param string               $set     Command set
     * @param string[]|string|null $aliases Command aliases
     *
     * @return int
     * @throws \InvalidArgumentException
     */
    public function runCommands(string $set, $aliases = null): int;
}

Fix cache clearer doc block.

Fix cache clearer doc block.


<?php
/* $Id:$ */

// Wrapper code for opening a new window.
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of version 2 of the GNU General Public
//License as published by the Free Software Foundation.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

?>

<h2> Java SSH </h2>

If necessary re-enter the maint user and password. Once the applet has opened enter the IP address of
your PBX. Log in with the CentOS user name and password

<APPLET CODE="com.mindbright.application.MindTerm.class"
          ARCHIVE="/admin/modules/javassh/mindterm.jar" WIDTH=0 HEIGHT=0>
    <PARAM NAME="cabinets" VALUE="/admin/modules/javassh/mindterm.cab">
    <PARAM NAME="sepframe" value="true">
    <PARAM NAME="debug" value="false">
</APPLET>

</div>

<?php
/* $Id:$ */

// Wrapper code for opening a new window.
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of version 2 of the GNU General Public
//License as published by the Free Software Foundation.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

?>

<h2> Java SSH </h2>

If necessary re-enter the maint user and password. Once the applet has opened enter the IP address of
your PBX. You will then connect to the FreePBX server. You can then login as 'root' or 'asterisk', or
whatever user you have created.

<APPLET CODE="com.mindbright.application.MindTerm.class"
          ARCHIVE="/admin/modules/javassh/mindterm.jar" WIDTH=0 HEIGHT=0>
    <PARAM NAME="cabinets" VALUE="/admin/modules/javassh/mindterm.cab">
    <PARAM NAME="sepframe" value="true">
    <PARAM NAME="debug" value="false">
</APPLET>

</div>

Clean up wording, not worth a re-release.


<?php

namespace phpSmug\Tests;

use phpSmug\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldNotHaveToPassHttpClientToConstructor()
    {
        $client = new Client('I-am-not-a-valid-APIKey-but-it-does-not-matter-for-this-test');

        $this->assertInstanceOf('GuzzleHttp\Client', $client->getHttpClient());
    }

    /**
     * @test
     */
    public function shouldThrowExceptionIfNoApikey()
    {
        $client = new Client();
    }

    /**
     * @test
     */
    public function shouldHaveOptionsSetInInstance()
    {
        $APIKey = 'I-am-not-a-valid-APIKey-but-it-does-not-matter-for-this-test';
        $options = [
            'AppName' => 'Testing phpSmug',
            'verbosity' => 1,
            'shorturis' => true,
            ];
        $client = new Client($APIKey, $options);

        $this->assertEquals($client->APIKey, $APIKey);
        $this->assertEquals($client->AppName, $options['AppName']);
        $this->assertEquals($client->verbosity, $options['verbosity']);
        $this->assertEquals($client->shorturis, $options['shorturis']);
        $this->assertEquals($client->getRequestOptions()['headers']['User-Agent'], sprintf('Testing phpSmug using phpSmug/%s', $client::VERSION));
    }
}

<?php

namespace phpSmug\Tests;

use phpSmug\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldNotHaveToPassHttpClientToConstructor()
    {
        $client = new Client('I-am-not-a-valid-APIKey-but-it-does-not-matter-for-this-test');

        $this->assertInstanceOf('GuzzleHttp\Client', $client->getHttpClient());
    }

    /**
     * @test
     */
    public function shouldThrowExceptionIfNoApikey()
    {
        $client = new Client();
    }

    /**
     * @test
     */
    public function shouldHaveOptionsSetInInstance()
    {
        $APIKey = 'I-am-not-a-valid-APIKey-but-it-does-not-matter-for-this-test';
        $options = [
            'AppName' => 'Testing phpSmug',
            'OAuthSecret' => 'I-am-not-a-valid-OAuthSecret-but-it-does-not-matter-for-this-test',
            '_verbosity' => 1,
            '_shorturis' => true,
            ];
        $client = new Client($APIKey, $options);

        $this->assertEquals($client->APIKey, $APIKey);
        $this->assertEquals($client->AppName, $options['AppName']);
        $this->assertEquals($client->_verbosity, $options['_verbosity']);
        $this->assertEquals($client->_shorturis, $options['_shorturis']);
        $this->assertEquals($client->OAuthSecret, $options['OAuthSecret']);
        $this->assertEquals($client->getRequestOptions()['headers']['User-Agent'], sprintf('Testing phpSmug using phpSmug/%s', $client::VERSION));
    }
}

Update test to match new variable names

Update test to match new variable names


<?php

namespace React\Promise\Queue;

class SynchronousQueue implements QueueInterface
{
    private $queue = [];

    public function enqueue(callable $task)
    {
        if (1 === array_push($this->queue, $task)) {
            $this->drain();
        }
    }

    private function drain()
    {
        /** @var callable $task */
        while ($task = array_shift($this->queue)) {
            $task();
        }
    }
}

<?php

namespace React\Promise\Queue;

class SynchronousQueue implements QueueInterface
{
    private $queue = [];

    public function enqueue(callable $task)
    {
        if (1 === array_push($this->queue, $task)) {
            $this->drain();
        }
    }

    private function drain()
    {
        for ($i = key($this->queue); isset($this->queue[$i]); $i++) {
            $task = $this->queue[$i];

            $exception = null;

            try {
                $task();
            } catch (\Exception $exception) {
            }

            unset($this->queue[$i]);

            if ($exception) {
                throw $exception;
            }
        }

        $this->queue = [];
    }
}

Revert "Simplify queue draining code"

Revert "Simplify queue draining code"

This reverts commit cc6f1c3846a77f42c3d5cab013dd012bab2a682a.

Note: The task must be kept on the queue until after it is called.
Otherwise drain() will be called recursively.


<?php

namespace Bgy\OAuth2;

/**
 * @author Boris Guéry <guery.b@gmail.com>
 */
class AccessToken
{
    private $accessToken;
    private $expiresIn;
    private $clientId;
    private $resourceOwnerId;
    private $scopes;

    public function __construct($token, $expiresIn, $clientId, $resourceOwnerId, array $scopes = [])
    {
        $this->accessToken     = $token;
        $this->expiresIn       = $expiresIn;
        $this->clientId        = $clientId;
        $this->resourceOwnerId = $resourceOwnerId;
        $this->scopes          = $scopes;
    }

    public function getToken()
    {
        return $this->accessToken;
    }

    public function getExpiresIn()
    {
        return $this->expiresIn;
    }

    public function getScopes()
    {
        return $this->scopes;
    }

    public function getClientId()
    {
        return $this->clientId;
    }

    public function getResourceOwnerId()
    {
        return $this->resourceOwnerId;
    }
}

<?php

namespace Bgy\OAuth2;

use Bgy\OAuth2\Utils\Ensure;

/**
 * @author Boris Guéry <guery.b@gmail.com>
 */
class AccessToken
{
    private $accessToken;
    private $expiresAt;
    private $clientId;
    private $resourceOwnerId;
    private $scopes;

    public function __construct($token, \DateTimeImmutable $expiresAt, $clientId, ResourceOwner $resourceOwnerId = null, array $scopes = [])
    {
        Ensure::string($token);

        $this->accessToken     = $token;
        $this->expiresAt       = $expiresAt;
        $this->clientId        = $clientId;
        $this->resourceOwnerId = $resourceOwnerId;
        $this->scopes          = $scopes;
    }

    public function getToken()
    {
        return $this->accessToken;
    }

    public function getExpiresAt()
    {
        return $this->expiresAt;
    }

    public function getScopes()
    {
        return $this->scopes;
    }

    public function getClientId()
    {
        return $this->clientId;
    }

    public function getResourceOwnerId()
    {
        return $this->resourceOwnerId;
    }
}

Use a datetime object to set the expire date instead of a ttl


<?php
/** @var array $_ */
/** @var \OCP\IL10N $l */
script('spreed', ['admin/signaling-server']);
style('spreed', ['settings-admin']);
?>

<?php p($l->t('Signaling server')) ?>

<?php p($l->t('An external signaling server can optionally be used for larger installations. Leave empty to use the internal signaling server.')) ?>

	<div class="signaling-servers" data-servers="<?php p($_['signalingServers']) ?>">

Shared secret

		<input type="text" id="signaling_secret"
			   name="signaling_secret" placeholder="<?php p($l->t('Shared secret')) ?>" aria-label="<?php p($l->t('Shared secret')) ?>"/>

<?php
/** @var array $_ */
/** @var \OCP\IL10N $l */
script('spreed', ['admin/signaling-server']);
style('spreed', ['settings-admin']);
?>

<?php p($l->t('Signaling server')) ?>

<?php p($l->t('An external signaling server can optionally be used for larger installations. Leave empty to use the internal signaling server.')) ?>

	<div class="signaling-servers" data-servers="<?php p($_['signalingServers']) ?>">

<?php p($l->t('Shared secret')) ?>

		<input type="text" id="signaling_secret"
			   name="signaling_secret" placeholder="<?php p($l->t('Shared secret')) ?>" aria-label="<?php p($l->t('Shared secret')) ?>"/>

Make shared secret translatable again

Make shared secret translatable again

Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>


<?php

/**
 * @author Ben Rowe <ben.rowe.83@gmail.com>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 */

namespace Benrowe\Laravel\Config;

use Illuminate\Support\ServiceProvider;

/**
 * Service Provider for Config
 *
 * @package Benrowe\Laravel\Config;
 */
class ServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Boot the configuration component
     *
     * @return nil
     */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/config.php';
        $this->publishes([
            $configPath => $this->getConfigPath(),
        ], 'config');
    }

    /**
     * Register an instance of the component
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('config', function () {
            return new Config();
        });
    }

    /**
     * Define the services this provider will build & provide
     *
     * @return array
     */
    public function provides()
    {
        return [
            'Benrowe\Laravel\Config\Config',
            'config'
        ];
    }

    /**
     * Get the configuration destination path
     *
     * @return string
     */
    protected function getConfigPath()
    {
        return config_path('config.php');
    }
}

<?php

/**
 * @author Ben Rowe <ben.rowe.83@gmail.com>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 */

namespace Benrowe\Laravel\Config;

use Illuminate\Support\ServiceProvider;

/**
 * Service Provider for Config
 *
 * @package Benrowe\Laravel\Config;
 */
class ServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Boot the configuration component
     *
     * @return nil
     */
    public function boot()
    {
        # publish necessary files
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('config.php'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../migrations/' => database_path('migrations'),
        ], 'migrations');
    }

    /**
     * Register an instance of the component
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('config', function () {
            return new Config();
        });
    }

    /**
     * Define the services this provider will build & provide
     *
     * @return array
     */
    public function provides()
    {
        return [
            'Benrowe\Laravel\Config\Config',
            'config'
        ];
    }

    /**
     * Get the configuration destination path
     *
     * @return string
     */
    protected function getConfigPath()
    {
        return ;
    }
}

Add publishes for future migrations

Add publishes for future migrations


<?php
use \Magento\Framework\Component\ComponentRegistrar;

require_once dirname(__FILE__) . '/Gateway/Http/Lib/omise-php/lib/Omise.php';

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Omise_Payment', __DIR__);

<?php
use \Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Omise_Payment', __DIR__);

Remove a line that require Gateway/Http/Lib/omise-php lib


<?php

namespace Argentum\TranslationBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * TranslationDomainRepository
 *
 * @author     Vadim Borodavko <javer@argentum.ua>
 * @copyright  Argentum IT Lab, http://argentum.ua
 */
class TranslationDomainRepository extends EntityRepository
{
    /**
     * Returns a list of all domains.
     *
     * @return array
     */
    public function getAllDomains()
    {
        $result = $this->createQueryBuilder('d')
            ->select('d.name')
            ->getQuery()
            ->getArrayResult();
        $domains = array_map('current', $result);

        return $domains;
    }

    /**
     * Returns a domain by name.
     *
     * @param string $name
     *
     * @return TranslationDomain
     */
    public function getByName($name)
    {
        return $this->findOneBy(array('name' => $name));
    }
}

<?php

namespace Argentum\TranslationBundle\Entity;

use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityRepository;

/**
 * TranslationDomainRepository
 *
 * @author     Vadim Borodavko <javer@argentum.ua>
 * @copyright  Argentum IT Lab, http://argentum.ua
 */
class TranslationDomainRepository extends EntityRepository
{
    /**
     * Returns a list of all domains.
     *
     * @return array
     */
    public function getAllDomains()
    {
        try {
            $result = $this->createQueryBuilder('d')
                ->select('d.name')
                ->getQuery()
                ->getArrayResult();
            $domains = array_map('current', $result);
        } catch (DBALException $e) {
            $domains = array();
        }

        return $domains;
    }

    /**
     * Returns a domain by name.
     *
     * @param string $name
     *
     * @return TranslationDomain
     */
    public function getByName($name)
    {
        return $this->findOneBy(array('name' => $name));
    }
}

Handle non-existent translation_domain table to allow its creation

Fixes #2


<?php

namespace Knp\RadBundle\Doctrine;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

abstract class EntityRepository extends BaseEntityRepository
{
    public function __call($method, array $arguments = array())
    {
        if (0 === strpos($method, 'find')) {
            if (method_exists($this, $builder = 'build'.substr($method, 4))) {
                $qb = call_user_func_array(array($this, $builder), $arguments);

                return $qb->getQuery()->getResult();
            }
        }

        return parent::__call($method, $arguments);
    }

    protected function build()
    {
        return $this->createQueryBuilder($this->getAlias());
    }

    protected function buildOne($id)
    {
        return $this->build()->where($this->getAlias().'.id = '.intval($id));
    }

    protected function buildAll()
    {
        return $this->build();
    }

    protected function getAlias()
    {
        $reflection = new \ReflectionObject($this);

        return strtolower(
            preg_replace(array('/Repository$/', '/[a-z0-9]/'), '', $reflection->getShortName())
        );
    }
}

<?php

namespace Knp\RadBundle\Doctrine;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

abstract class EntityRepository extends BaseEntityRepository
{
    public function __call($method, $arguments)
    {
        if (0 === strpos($method, 'find')) {
            if (method_exists($this, $builder = 'build'.substr($method, 4))) {
                $qb = call_user_func_array(array($this, $builder), $arguments);

                return $qb->getQuery()->getResult();
            }
        }

        return parent::__call($method, $arguments);
    }

    protected function build()
    {
        return $this->createQueryBuilder($this->getAlias());
    }

    protected function buildOne($id)
    {
        return $this->build()->where($this->getAlias().'.id = '.intval($id));
    }

    protected function buildAll()
    {
        return $this->build();
    }

    protected function getAlias()
    {
        $reflection = new \ReflectionObject($this);

        return strtolower(
            preg_replace(array('/Repository$/', '/[a-z0-9]/'), '', $reflection->getShortName())
        );
    }
}

Make entity repo compatible with parent

Make entity repo compatible with parent


<?php

final class PhabricatorSearchDocumentTypeDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getBrowseTitle() {
    return pht('Browse Document Types');
  }

  public function getPlaceholderText() {
    return pht('Select a document type...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorSearchApplication';
  }

  public function loadResults() {
    $results = $this->buildResults();
    return $this->filterResultsAgainstTokens($results);
  }

  public function renderTokens(array $values) {
    return $this->renderTokensFromResults($this->buildResults(), $values);
  }

  private function buildResults() {
    $types =
      PhabricatorSearchApplicationSearchEngine::getIndexableDocumentTypes();

    $icons = mpull(
      PhabricatorPHIDType::getAllTypes(),
      'getTypeIcon',
      'getTypeConstant');

    $results = array();
    foreach ($types as $type => $name) {
      $results[$type] = id(new PhabricatorTypeaheadResult())
        ->setPHID($type)
        ->setName($name)
        ->setIcon(idx($icons, $type));
    }

    return $results;
  }

}

<?php

final class PhabricatorSearchDocumentTypeDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getBrowseTitle() {
    return pht('Browse Document Types');
  }

  public function getPlaceholderText() {
    return pht('Select a document type...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorSearchApplication';
  }

  public function loadResults() {
    $results = $this->buildResults();
    return $this->filterResultsAgainstTokens($results);
  }

  public function renderTokens(array $values) {
    return $this->renderTokensFromResults($this->buildResults(), $values);
  }

  private function buildResults() {
    $viewer = $this->getViewer();
    $types =
      PhabricatorSearchApplicationSearchEngine::getIndexableDocumentTypes(
        $viewer);

    $icons = mpull(
      PhabricatorPHIDType::getAllTypes(),
      'getTypeIcon',
      'getTypeConstant');

    $results = array();
    foreach ($types as $type => $name) {
      $results[$type] = id(new PhabricatorTypeaheadResult())
        ->setPHID($type)
        ->setName($name)
        ->setIcon(idx($icons, $type));
    }

    return $results;
  }

}

Remove unused apps from the DocumentType typeahead

Summary: Ref T10951. This diff removes uninstalled applications from the result set for DocumentType restults

Test Plan: Uninstall an application (diviner for example), then go to the document type search menu and ensure that the uninstalled application doesn't show up.

Reviewers: #blessed_reviewers, epriestley

Reviewed By: #blessed_reviewers, epriestley

Subscribers: epriestley

Maniphest Tasks: T10951

Differential Revision: https://secure.phabricator.com/D16445


<?php

spl_autoload_register(function($class)
{
	$file = __DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.str_replace('_', '/', $class).'.php';

	if (is_file($file))
	{
		require_once $file;
	}
});

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

Kohana::modules(array(
	'database'        => MODPATH.'database',
	'jam'             => __DIR__.'/../modules/jam',
	'jam-freezable' => __DIR__.'/..',
));

Kohana::$config
	->load('database')
		->set('default', array(
			'type'       => 'MySQL',
			'connection' => array(
				'hostname'   => 'localhost',
				'database'   => 'test-jam-freezable',
				'username'   => 'root',
				'password'   => '',
				'persistent' => TRUE,
			),
			'table_prefix' => '',
			'charset'      => 'utf8',
			'caching'      => FALSE,
		));

Kohana::$environment = Kohana::TESTING;

<?php

spl_autoload_register(function($class)
{
	$file = __DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.str_replace('_', '/', $class).'.php';

	if (is_file($file))
	{
		require_once $file;
	}
});

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

Kohana::modules(array(
	'database'        => MODPATH.'database',
	'jam'             => __DIR__.'/../modules/jam',
	'jam-freezable' => __DIR__.'/..',
));

Kohana::$config
	->load('database')
		->set('default', array(
			'type'       => 'PDO',
			'connection' => array(
				'dsn'        => 'mysql:dbname=test-jam-freezable;host=127.0.0.1',
				'username'   => 'root',
				'password'   => '',
				'persistent' => TRUE,
			),
			'table_prefix' => '',
			'charset'      => 'utf8',
			'caching'      => FALSE,
		));

Kohana::$environment = Kohana::TESTING;

Use PDO driver for unit tests so everything works on PHP 5.5


<?php

namespace ProcessWire\GraphQL;

class Settings {

  public static function module()
  {
    return \Processwire\wire('modules')->get('ProcessGraphQL');
  }

  public static function getLegalTemplates()
  {

    $legalTemplates = self::module()->legalTemplates;
    $templates = \ProcessWire\wire('templates')->find("name=" . implode('|', $legalTemplates));

    $user = \ProcessWire\wire('user');

    foreach ($templates as $template) {
      if (!$user->hasPermission('page-view', $template)) {
        $templates->remove($template);
      }
    }

    return $templates;
  }

  public static function getLegalFields()
  {
    $legalFields = self::module()->legalFields;
    $fields = \ProcessWire\wire('fields')->find("name=" . implode('|', $legalFields));
    return $fields;
  }

}

<?php

namespace ProcessWire\GraphQL;

class Settings {

  public static function module()
  {
    return \Processwire\wire('modules')->get('ProcessGraphQL');
  }

  public static function getLegalTemplates()
  {
    $legalTemplates = self::module()->legalTemplates;
    $templates = \ProcessWire\wire('templates')->find("name=" . implode('|', $legalTemplates));
    $user = \ProcessWire\wire('user');

    // Wierd behavior with ProcessWire. $user->hasPermission() does not
    // work if you do not load the required roles beforehand.
    \ProcessWire\wire('roles')->find("");

    foreach ($templates as $template) {
      // we serve templates with access control disabled
      if (!$template->useRoles) continue;

      // if enabled we serve only those that user has permission to view
      if (!$user->hasTemplatePermission('page-view', $template)) {
        $templates->remove($template);
      }
    }

    return $templates;
  }

  public static function getLegalFields()
  {
    $legalFields = self::module()->legalFields;
    $fields = \ProcessWire\wire('fields')->find("name=" . implode('|', $legalFields));
    return $fields;
  }

}

Fix the template permissions bug.

Fix the template permissions bug.