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

return array(
    'factories' => array(
        'BedRest.Dispatcher'                    => 'BedRest\Framework\Zend2\Service\DispatcherFactory',
        'BedRest.ResourceMetadataFactory'       => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory',
        'BedRest.ServiceMetadataFactory'        => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory',
        'BedRest.ContentNegotiator'             => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory',
        'BedRest.ContentNegotiationStrategy'    => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory',
        'BedRest.ExceptionStrategy'             => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory',
        'BedRest.Request'                       => 'BedRest\Framework\Zend2\Service\Request'
    )
);

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

return array(
    'factories' => array(
        'BedRest.Dispatcher'                    => 'BedRest\Framework\Zend2\Service\DispatcherFactory',
        'BedRest.ResourceMetadataFactory'       => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory',
        'BedRest.ServiceMetadataFactory'        => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory',
        'BedRest.ContentNegotiator'             => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory',
        'BedRest.ContentNegotiationStrategy'    => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory',
        'BedRest.ExceptionStrategy'             => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory',
        'BedRest.Request'                       => 'BedRest\Framework\Zend2\Service\RequestFactory'
    )
);

Fix for erroneous service definition

Fix for erroneous service definition


<?php

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

class UpdateTrackFilesWithFilesize extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('track_files', function (Blueprint $table) {
            $table->integer('filesize')->nullable()->unsigned();
        });
    }

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

Add filesize column to track_files

Add filesize column to track_files


<?php

	require_once(TOOLKIT . '/class.datasource.php');

	Class datasourceforum_code_source extends Datasource{

		public $dsParamROOTELEMENT = 'forum-code-source';
		public $dsParamORDER = 'desc';
		public $dsParamLIMIT = '1';
		public $dsParamREDIRECTONEMPTY = 'no';
		public $dsParamSORT = 'system:id';
		public $dsParamSTARTPAGE = '1';
		public $dsParamASSOCIATEDENTRYCOUNTS = 'no';

		public $dsParamFILTERS = array(
				'id' => '{$comment-id}',
		);

		public $dsParamINCLUDEDELEMENTS = array(
				'comment: formatted'
		);

		public function __construct(&$parent, $env=NULL, $process_params=true){
			parent::__construct($parent, $env, $process_params);
			$this->_dependencies = array();
		}

		public function about(){
			return array(
					 'name' => 'Forum: Code Source',
					 'author' => array(
							'name' => 'Stephen Bau',
							'website' => 'http://home/sym/sym-forum',
							'email' => 'bauhouse@gmail.com'),
					 'version' => '1.0',
					 'release-date' => '2010-04-02T19:18:58+00:00');
		}

		public function getSource(){
			return '3';
		}

		public function allowEditorToParse(){
			return true;
		}

		public function grab(&$param_pool=NULL){
			$result = new XMLElement($this->dsParamROOTELEMENT);

			try{
				include(TOOLKIT . '/data-sources/datasource.section.php');
			}
			catch(FrontendPageNotFoundException $e){
				// Work around. This ensures the 404 page is displayed and
				// is not picked up by the default catch() statement below
				FrontendPageNotFoundExceptionHandler::render($e);
			}
			catch(Exception $e){
				$result->appendChild(new XMLElement('error', $e->getMessage()));
				return $result;
			}

			if($this->_force_empty_result) $result = $this->emptyXMLSet();
			return $result;
		}
	}

Create Forum: Code Source data source

Create Forum: Code Source data source


<?php

namespace ForkCMS\Bundle\InstallerBundle\Console;

use Console\Core\PrepareForReinstallCommand;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;

/**
 * This command will install fork from the cli
 */
class InstallCommand extends ContainerAwareCommand
{
    /** @var InputInterface */
    private $input;

    /** @var OutputInterface */
    private $output;

    /** @var SymfonyStyle */
    private $formatter;

    /**
     * Configure the command options.
     */
    protected function configure()
    {
        $this
            ->setName('forkcms:install')
            ->setDescription('Installation of fork from the cli');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $this->formatter = new SymfonyStyle($input, $output);

        if ($this->isForkAlreadyInstalled() && !$this->isPreparedForReinstall()) {
            return 1;
        }

        return 0;
    }

    /**
     * @return bool
     */
    private function isForkAlreadyInstalled()
    {
        $filesystem = new Filesystem();
        $kernelDir = $this->getContainer()->getParameter('kernel.root_dir');

        $parameterFile = $kernelDir . '/config/parameters.yml';

        return $filesystem->exists($parameterFile);
    }

    /**
     * @return bool
     */
    private function isPreparedForReinstall()
    {
        $reinstallCommand = $this->getApplication()->find('forkcms:install:prepare-for-reinstall');

        $reinstallOutput = $reinstallCommand->run(
            new ArrayInput(['forkcms:install:prepare-for-reinstall']),
            $this->output
        );

        if ($reinstallOutput === PrepareForReinstallCommand::RETURN_DID_NOT_REINSTALL) {
            $this->formatter->error('This Fork has already been installed.');
            $this->formatter->note('Since you choose not to reinstall we can\'t do a clean install.');

            return false;
        }

        if ($reinstallOutput === PrepareForReinstallCommand::RETURN_DID_NOT_CLEAR_DATABASE) {
            $this->formatter->error('This Fork had already been installed.');
            $this->formatter->note(
                'Since you choose not to clear the database we can\'t do a clean install.' . PHP_EOL
                . 'Clear the database manually and run this command again.'
            );

            return false;
        }

        return $reinstallOutput === PrepareForReinstallCommand::RETURN_SUCCESS;
    }
}

Check if fork is already installed

Check if fork is already installed

Before we try to do a clean install we need to be sure that fork isn't installed already.
If it is installed we run the prepare for reinstall command


<?php
namespace M6Web\Bundle\ApcuBundle\CacheAdapters;

use M6Web\Bundle\GuzzleHttpBundle\Cache\CacheInterface;
use M6Web\Bundle\ApcuBundle\Apcu\Apcu as BaseApcu;

/**
 * Cache interface for the m6web guzzlehttp bundle
 */
class M6WebGuzzleHttp extends BaseApcu implements CacheInterface
{
    /**
     * {@inheritDoc}
     */
    public function has($key)
    {
        return $this->exists($key);
    }

    /**
     * {@inheritDoc}
     */
    public function get($key)
    {
        return $this->fetch($key);
    }

    /**
     * {@inheritDoc}
     */
    public function set($key, $value, $ttl = null)
    {
        return $this->store($key, $value, $ttl);
    }

    /**
     * {@inheritDoc}
     */
    public function remove($key)
    {
        return $this->delete($key);
    }

    /**
     * {@inheritDoc}
     */
    public function ttl($key)
    {
        $key   = $this->getFinalKey($key);
        $infos = apcu_cache_info();

        foreach ($infos['cache_list'] as $entry) {
            if ($entry['info'] == $key) {
                return $entry['ttl'];
            }
        }

        return false;
    }
}

Add M6Web Guzzlehttp cache interface

Add M6Web Guzzlehttp cache interface


<?php

use App\User;
use App\Business;
use App\Contact;
use App\Appointment;
use App\Service;
use App\Vacancy;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class VacancyUnitTest extends TestCase
{
    use DatabaseTransactions;

    protected $business;

    /**
     * @covers            \App\Vacancy::isHoldingAnyFor
     */
    public function testIsHoldingAnyFor()
    {
        /* Setup Stubs */
        $issuer = factory(User::class)->create();

        $business = factory(Business::class)->create();
        $business->owners()->save($issuer);

        $service = factory(Service::class)->make();
        $business->services()->save($service);

        $vacancy = factory(Vacancy::class)->make();
        $vacancy->service()->associate($service);
        $business->vacancies()->save($vacancy);

        $contact = factory(Contact::class)->create();
        $business->contacts()->save($contact);

        $appointment = factory(Appointment::class)->make();
        $appointment->business()->associate($business);
        $appointment->service()->associate($service);
        $appointment->contact()->associate($contact);
        $appointment->vacancy()->associate($vacancy);
        $appointment->save();

        /* Perform Test */
        $this->assertTrue($vacancy->isHoldingAnyFor($issuer));
    }

    /**
     * @covers            \App\Vacancy::isHoldingAnyFor
     */
    public function testIsNotHoldingAnyFor()
    {
        /* Setup Stubs */
        $issuer = factory(User::class)->create();

        $business = factory(Business::class)->create();
        $business->owners()->save($issuer);

        $service = factory(Service::class)->make();
        $business->services()->save($service);

        $vacancy = factory(Vacancy::class)->make();
        $vacancy->service()->associate($service);
        $business->vacancies()->save($vacancy);

        $contact = factory(Contact::class)->make();
        $contact->email = 'otheruser@timegrid.io';
        $business->contacts()->save($contact);
        $contact->save();

        $appointment = factory(Appointment::class)->make();
        $appointment->business()->associate($business);
        $appointment->service()->associate($service);
        $appointment->contact()->associate($contact);
        $appointment->vacancy()->associate($vacancy);
        $appointment->save();

        /* Perform Test */
        $this->assertFalse($vacancy->isHoldingAnyFor($issuer));
    }
}

Add unit tests (basic) for Vacancy

Add unit tests (basic) for Vacancy


<?php

namespace PhpAbac\Manager;

use PhpAbac\Model\PolicyRule;
use PhpAbac\Model\PolicyRuleAttribute;

use PhpAbac\Repository\PolicyRuleRepository;

class PolicyRuleManager {
    /** @var AbacManager **/
    protected $abacManager;
    /** @var PolicyRuleRepository **/
    protected $repository;

    /**
     * @param \PhpAbac\Manager\AbacManager $abacManager
     */
    public function __construct(AbacManager $abacManager) {
        $this->abacManager = $abacManager;

        $this->repository = new PolicyRuleRepository();
    }

    /**
     * @param string $name
     * @param array $attributes
     * @return PolicyRule
     */
    public function create($name, $attributes) {
        $policyRule =
            (new PolicyRule())
            ->setName($name)
        ;

        $nbAttributes = count($attributes);

        for($i = 0; $i < $nbAttributes; ++$i) {
            $policyRule->addPolicyRuleAttribute(
                $this->createPolicyRuleAttribute($attributes[$i])
            );
        }
    }

    /**
     * @param array $data
     * @throws \InvalidArgumentException
     * @return PhpAbac\Model\PolicyRuleAttribute
     */
    public function createPolicyRuleAttribute($data) {
        if(!isset($data['comparison'])) {
            throw new \InvalidArgumentException('The attribute must have a comparison');
        }
        if(!isset($data['value'])) {
            throw new \InvalidArgumentException('The attribute must have a value');
        }
        if(!isset($data['attribute'])) {
            throw new \InvalidArgumentException('The attribute must have a key "attribute"');
        }
        return
            (new PolicyRuleAttribute())
            ->setComparison($data['comparison'])
            ->setValue('value')
            ->setAttribute($this->abacManager->create(
                $data['attribute']['table'],
                $data['attribute']['column'],
                $data['attribute']['criteriaColumn']
            ))
        ;
    }
}

Add PolicyRule Manager with a create method


<?php

use Hubzero\Content\Migration\Base;

/**
 * Migration script for enabling digest plugins
 * Specifically the event, feedaggregator, and resource plugins
 **/
class Migration201603091905401ComNewsletter extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$elements = array('event','feedaggregator','resource');
		foreach ($elements as $element)
		{
			$this->addPluginEntry('newsletter', $element);
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$query = "DELETE FROM #__extensions WHERE type='plugin' AND folder='newsletter' AND (element = 'event' OR element='feedaggregator' OR element='resource');";
		$this->db->setQuery($query);
		$this->db->query();
	}
}

[PLG_NEWSLETTER_*] Install event, resource, feedaggregator plugins.


Update dependency configuration as App now composes the container


<?php
/**
 * @package plugins.quiz
 * @subpackage api.objects
 */
class KalturaQuestionSummary extends KalturaObject
{
	/**
	 *
	 * @var float
	 */
	public $percentage;

	private static $mapBetweenObjects = array
	(
		"version",
		"uiAttributes",
		"showResultOnAnswer",
		"showCorrectKeyOnAnswer",
		"allowAnswerUpdate",
		"showCorrectAfterSubmission",
	);

	/* (non-PHPdoc)
	 * @see KalturaObject::getMapBetweenObjects()
	 */
	public function getMapBetweenObjects()
	{
		return array_merge(parent::getMapBetweenObjects(), self::$mapBetweenObjects);
	}

	/* (non-PHPdoc)
	 * @see KalturaObject::toObject($object_to_fill, $props_to_skip)
	 */
	public function toObject($dbObject = null, $propsToSkip = array())
	{
		if (!$dbObject)
		{
			$dbObject = new kQuiz();
		}

		return parent::toObject($dbObject, $propsToSkip);
	}
}

Remove float issue in client creation

Remove float issue in client creation


<?php

namespace Test\AppBundle\API\Details;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

class TraitOfProjectTest extends WebTestCase
{
    const NICKNAME = 'detailsTraitOfProjectTestUser';
    const USERID = 'detailsTraitOfProjectTestUser';
    const PROVIDER = 'detailsTraitOfProjectTestUser';

    public function testExecute()
    {
        $container = static::createClient()->getContainer();
        $default_db = $container->getParameter('default_db');
        $projectListing = $container->get('app.api.webservice')->factory('listing', 'projects');
        $service = $container->get('app.api.webservice')->factory('details', 'traitOfProject');
        $session = new Session(new MockArraySessionStorage());
        $session->set('user',
            array(
                'nickname' => TraitOfProjectTest::NICKNAME,
                'id' => TraitOfProjectTest::USERID,
                'provider' => TraitOfProjectTest::PROVIDER,
                'token' => 'detailsTraitOfProjectTestToken'
            )
        );

        $results = $service->execute(new ParameterBag(array('dbversion' => $default_db, 'trait_type_id' => 1, 'internal_project_id' => 3)), null);
        $expected = array("error" => WebService::ERROR_NOT_LOGGED_IN);
        $this->assertEquals($expected, $results, 'User is not loggend in, return error message');

        $entries = $projectListing->execute(new ParameterBag(array('dbversion' => $default_db)), $session);
        $id = $entries['data'][0]['internal_project_id'];

        $results = $service->execute(new ParameterBag(array('dbversion' => $default_db, 'trait_type_id' => 1, 'internal_project_id' => $id)), $session);
        $expected = [
            "values" => [
                "forb/herb" => "4",
                "shrub" => "2",
                "subshrub" => "2"
            ],
            "trait_type_id" => 1,
            "name" => "PlantHabit",
            "ontology_url" => "eol.org/schema/terms/PlantHabit",
            "trait_format" => "categorical_free",
            "number_of_organisms" => 5
        ];
        $this->assertEquals($results, $expected, 'Example project, return trait details');

        $session->set('user', array('id' => 'noValidUserID', 'provider' => TraitOfProjectTest::PROVIDER));
        $results = $service->execute(new ParameterBag(array('dbversion' => $default_db, 'trait_type_id' => 1, 'internal_project_id' => $id)), $session);
        $expected = array("error" => OrganismsOfProject::ERROR_PROJECT_NOT_FOUND);
        $this->assertEquals($expected, $results, 'Project does not belong to user, return error message');

    }
}

Add test of details traitOfProject webservice


<?php
/**
 * Laravel IDE Helper Generator
 *
 * @author    Barry vd. Heuvel <barryvdh@gmail.com>, David Chang <davidchchang@gmail.com>
 * @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      https://github.com/barryvdh/laravel-ide-helper
 */

namespace ChefsPlate\ODM\Providers;

use ChefsPlate\ODM\Console\Commands\DoctrineModelsCommand;
use Illuminate\Support\ServiceProvider;

class IdeOdmHelperServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/ide-odm-helper.php';
        if (function_exists('config_path')) {
            $publishPath = config_path('ide-odm-helper.php');
        } else {
            $publishPath = base_path('config/ide-odm-helper.php');
        }
        $this->publishes([$configPath => $publishPath], 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $configPath = __DIR__ . '/../config/ide-odm-helper.php';
        $this->mergeConfigFrom($configPath, 'ide-helper');

        $this->app['command.ide-helper.doctrine-models'] = $this->app->share(
            function ($app) {
                return new DoctrineModelsCommand($app['files']);
            }
        );

        $this->commands('command.ide-helper.doctrine-models');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('command.ide-helper.doctrine-models');
    }
}

Create service provider for the IDE (ODM) helper


<?php

class CM_Console_Cli extends CM_Cli_Runnable_Abstract {

	public function interactive() {
		while ('exit' !== ($code = $this->_getInput()->read('php >'))) {
			$result = null;
			try {
				$code = '$result = ' . $code . ';';
				if (false !== eval($code)) {
					$this->_getOutput()->writeln(print_r($result, true));
				}
			} catch (Exception $e) {
				$this->_getOutput()->writeln($e->getMessage());
				$this->_getOutput()->writeln($e->getTraceAsString());
			}
		}
	}

	public static function getPackageName() {
		return 'console';
	}

}

Add console cli with basic interactive command


<?php

namespace Oro\Bundle\ApiBundle\Processor;

use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
use Oro\Component\ChainProcessor\ProcessorBag;

class DeleteListProcessor extends RequestActionProcessor
{
    /** @var ConfigProvider */
    protected $configProvider;

    /** @var MetadataProvider */
    protected $metadataProvider;

    /**
     * @param ProcessorBag     $processorBag
     * @param string           $action
     * @param ConfigProvider   $configProvider
     * @param MetadataProvider $metadataProvider
     */
    public function __construct(
        ProcessorBag $processorBag,
        $action,
        ConfigProvider $configProvider,
        MetadataProvider $metadataProvider
    ) {
        parent::__construct($processorBag, $action);
        $this->configProvider   = $configProvider;
        $this->metadataProvider = $metadataProvider;
    }

    /**
     * {@inheritdoc}
     */
    protected function createContextObject()
    {
        return new DeleteListContext($this->configProvider, $this->metadataProvider);
    }
}

<?php

namespace Oro\Bundle\ApiBundle\Processor;

use Oro\Component\ChainProcessor\ProcessorBag;

use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;

class DeleteListProcessor extends RequestActionProcessor
{
    /** @var ConfigProvider */
    protected $configProvider;

    /** @var MetadataProvider */
    protected $metadataProvider;

    /**
     * @param ProcessorBag     $processorBag
     * @param string           $action
     * @param ConfigProvider   $configProvider
     * @param MetadataProvider $metadataProvider
     */
    public function __construct(
        ProcessorBag $processorBag,
        $action,
        ConfigProvider $configProvider,
        MetadataProvider $metadataProvider
    ) {
        parent::__construct($processorBag, $action);
        $this->configProvider   = $configProvider;
        $this->metadataProvider = $metadataProvider;
    }

    /**
     * {@inheritdoc}
     */
    protected function createContextObject()
    {
        return new DeleteListContext($this->configProvider, $this->metadataProvider);
    }
}

BAP-9940: Create controller DELETE list action
 - fix cs


<?php

namespace FD\PrivateMessageBundle\Tests\DependencyInjection;

use FD\PrivateMessageBundle\DependencyInjection\FDPrivateMessageExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Class FDPrivateMessageExtensionTest.
 */
class FDPrivateMessageExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test load.
     */
    public function testLoad()
    {
        $container = new ContainerBuilder();
        $loader    = new FDPrivateMessageExtension();
        $config    = [];
        $loader->load($config, $container);

        $this->assertEquals('fd_private_message', $loader->getAlias());
    }
}

Add unit test to FDPrivateMessageExtension


<?php

namespace Caffeinated\Modules\Tests\Commands\Generators;

use Spatie\Snapshots\MatchesSnapshots;
use Caffeinated\Modules\Tests\BaseTestCase;

class CommandMakeModuleTest extends BaseTestCase
{
    use MatchesSnapshots;

    protected $finder;

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

        $this->finder = $this->app['files'];
    }

    /** @test */
    public function it_can_generate_module_with_custom_mapping()
    {
        $this->app['config']->set("modules.locations.{$this->default}.mapping", [
            'config'              => 'config',
            'Database/Factories'  => 'src/Database/Factories',
            'Database/Migrations' => 'src/Database/Migrations',
            'Database/Seeds'      => 'src/Database/Seeds',
            'Http/Controllers'    => 'src/Http/Controllers',
            'Http/Middleware'     => 'src/Http/Middleware',
            'Providers'           => 'src/Providers',
            'Resources/Lang'      => 'resources/lang',
            'Resources/Views'     => 'resources/views',
            'Routes'              => 'routes'
        ]);

        $this->artisan('make:module', ['slug' => 'custom', '--quick' => 'quick']);

        $this->assertDirectoryExists(module_path('custom').'/config');
        $this->assertDirectoryExists(module_path('custom').'/src/Database/Factories');
        $this->assertDirectoryExists(module_path('custom').'/src/Database/Migrations');
        $this->assertDirectoryExists(module_path('custom').'/src/Database/Seeds');
        $this->assertDirectoryExists(module_path('custom').'/src/Http/Controllers');
        $this->assertDirectoryExists(module_path('custom').'/src/Http/Middleware');
        $this->assertDirectoryExists(module_path('custom').'/src/Providers');
        $this->assertDirectoryExists(module_path('custom').'/resources/lang');
        $this->assertDirectoryExists(module_path('custom').'/resources/views');
        $this->assertDirectoryExists(module_path('custom').'/routes');
    }

    public function tearDown()
    {
        $this->finder->deleteDirectory(module_path('custom'));

        parent::tearDown();
    }
}

Add make:module test for custom mappings


<?php

/**
 * Mmi Framework (https://github.com/milejko/mmi.git)
 *
 * @link       https://github.com/milejko/mmi.git
 * @copyright  Copyright (c) 2010-2017 Mariusz Miłejko (mariusz@milejko.pl)
 * @license    https://en.wikipedia.org/wiki/BSD_licenses New BSD License
 */

namespace Mmi\Filter;

/**
 * Filtr puste teksty do null
 */
class EmptyStringToNull extends \Mmi\Filter\FilterAbstract
{

    /**
     * Zamienia pusty ciąg znaków na null
     * @param mixed $value wartość
     * @throws \Mmi\App\KernelException jeśli filtrowanie $value nie jest możliwe
     * @return mixed
     */
    public function filter($value)
    {
        return is_string($value) && mb_strlen($value) == 0 ? null : $value;
    }

}

Add filter empty string to null

Add filter empty string to null


<?php
/**
 * Nextcloud - passman
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Sander Brand <brantje@gmail.com>
 * @copyright Sander Brand 2016
 */

namespace OCA\Passman\Controller;

use PHPUnit_Framework_TestCase;

use OCP\AppFramework\Http\TemplateResponse;

class InternalControllerTest extends PHPUnit_Framework_TestCase {

	private $controller;
	private $userId = 'john';

	public function setUp() {
		$request = $this->getMockBuilder('OCP\IRequest')->getMock();

		$this->controller = new PageController(
			'passman', $request, $this->userId
		);
	}

	public function testGetAppVersion() {
		$result = $this->controller->generatePerson();
		$this->assertTrue($result instanceof JSONResponse);
	}
	public function testGeneratePerson() {
		$result = $this->controller->generatePerson();
		$this->assertTrue($result instanceof JSONResponse);
	}
}

Add test for internal controller

Add test for internal controller


<?php
namespace Neos\Flow\Tests\Unit\Cli;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Cli;
use Neos\Flow\Cli\ConsoleOutput;
use Neos\Flow\Tests\UnitTestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;

/**
 * Test cases for the CLI console output
 */
class ConsoleOutputTest extends UnitTestCase
{
    /**
     * @var Cli\ConsoleOutput
     */
    private $consoleOutput;

    /**
     * @var StreamOutput
     */
    private $output;

    /**
     * @var ArrayInput
     */
    private $input;

    /**
     * @return void
     */
    public function setUp()
    {
        $this->input = new ArrayInput(['test']);
        $this->output = new StreamOutput(fopen('php://memory', 'w', false));

        $this->consoleOutput = new ConsoleOutput();
        $this->consoleOutput->setOutput($this->output);
        $this->consoleOutput->setInput($this->input);
        $this->consoleOutput->getInput()->setInteractive(false);
    }

    /**
     * @test
     */
    public function outputSimpleOutput()
    {
        $string = 'simple output';
        $this->consoleOutput->output($string);
        $this->assertSame($string, $this->getDisplay());
    }

    /**
     * @test
     */
    public function questionWasAskedFallBackToDefaultAnswer()
    {
        $this->assertSame('Not Sure', $this->consoleOutput->ask('Enter your name', 'Not Sure'));
    }

    /**
     * @test
     */
    public function questionIsAskedAnswerIsNo()
    {
        $answer = $this->consoleOutput->ask('Is this a test?');
        \Neos\Flow\var_dump($this->getDisplay());

        $this->assertSame(false, $answer);
    }

    /**
     * @test
     */
    public function questionIsAskedAnswerIsYes()
    {

        $answer = $this->consoleOutput->askConfirmation('Are you lying?');
        $this->assertSame(true, $answer);
    }

    /**
     * @test
     */
    public function returnUserInput()
    {
        $answer = $this->consoleOutput->ask('Are you lying?');
        $this->assertSame(true, $answer);
    }

    /**
     * Gets the display returned by the last execution of the command.
     *
     * @param bool $normalize Whether to normalize end of lines to \n or not
     *
     * @return string The display
     */
    private function getDisplay($normalize = false)
    {
        rewind($this->output->getStream());

        $display = stream_get_contents($this->output->getStream());

        if ($normalize) {
            $display = str_replace(PHP_EOL, "\n", $display);
        }

        return $display;
    }
}

Implement unit tests for console ouput

WIP: Implement unit tests for console ouput


<?php

class GenerateMigrationCommandTest extends AcceptanceTestCase
{
    public function testExecute()
    {
        $output = $this->runConsole('g:migration test migration');
        $found = preg_match('/\d{14}_testmigration\.php/', $output, $matches);
        $this->assertSame(1, $found, 'Output must contain a valid generated migration name');

        $migrationsDir = OX_BASE_PATH . 'migration';
        $filename = reset($matches);
        $filepath = $migrationsDir . '/' . $filename;

        $this->assertFileExists($filepath);

        unlink($filepath);
    }
}

Create generate migration command acceptance test


<?php

$loader = require __DIR__.'/../../vendor/autoload.php';

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

// Configure any auth headers when instantiating the guzzle client. These will be passed in each request.
$headers = [
    'Authorization' => 'Token 23a65de8ea1f2b52defea12c0d7a9c11'
];
$client = new \GuzzleHttp\Client(['headers' => $headers]);
$serializer = \JMS\Serializer\SerializerBuilder::create()->build();

// The metadata registry holds information about the resource to use in the url and the identifier
$metadataRegistry = new \Tystr\RestOrm\Metadata\Registry();

// The request factory generates the request that will be sent to the API. Note that you must set the format to be used
// when serializing the models to build the request body.
$urlGenerator = new \Tystr\RestOrm\UrlGenerator\StandardUrlGenerator('https://example.com/api');
$requestFactory = new \Tystr\RestOrm\Request\Factory($metadataRegistry, $serializer, $urlGenerator, 'json');

// The response mapper maps api responses to objects
// Use the HalResponseMapper to correctly map HAL APIs
$responseMapper = new \Tystr\RestOrm\Response\HalResponseMapper();

// Instantiate a manager.
$class = 'Post';
$postManager = new \Tystr\RestOrm\Manager\Manager($client, $requestFactory, $responseMapper, $class);

// Find all posts
$posts = $manager->findAll();
foreach ($posts as $post) {
    // ...
}

// Find a single post by it's id
$post = $manager->findOneById('42');

// Modify an existing post
$post->title = 'New Title';
$manager->save($post);

// Delete a post
$manager->remove($post);

/**
 * @Tystr\RestOrm\Annotation\Resource("posts")
 */
class Post
{
    /**
     * @Tystr\RestOrm\Annotation\Id()
     * @JMS\Serializer\Annotation\Type("string")
     */
    public $id;

    /**
     * @JMS\Serializer\Annotation\Type("string")
     */
    public $title;

    /**
     * @JMS\Serializer\Annotation\Type("string")
     */
    public $body;

    /**
     * @JMS\Serializer\Annotation\Type("boolean")
     */
    public $published;

    /**
     * @JMS\Serializer\Annotation\Type("integer")
     */
    public $createdAt;

    /**
     * @JMS\Serializer\Annotation\Type("integer")
     */
    public $updatedAt;
}

Add a simple example to docs

Add a simple example to docs


<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20120814193114 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // skip if data is already in DB
        $stmt = $this->connection->query('SELECT COUNT(*) count FROM lecture_type');
        $row = $stmt->fetch();
        $this->skipIf($row['count'] > 0, 'lecture_type is not empty');

        // add data
        $types = array(
            'LECTURE_TYPE_VIDEO' => 'Видео',
            'LECTURE_TYPE_AUDIO' => 'Аудио',
            'LECTURE_TYPE_TEXT' => 'Текст',
        );
        foreach ($types as $key => $val) {
            $this->addSql("
                INSERT INTO lecture_type (id, name, code)
                VALUES(nextval('lecture_type_id_seq'::regclass), :name, :code)
                ",
                array(
                    'name' => $val,
                    'code' => $key
                )
            );
        }
    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs

    }
}

Add migration for lecture type

[*] Add migration for lecture type


<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20180426065050 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        //set the rate_group_id of a project to the one in its customer, if it is currently null
        $this->addSql("update projects p
  inner join customers c on p.customer_id = c.id
    set p.rate_group_id = coalesce(p.rate_group_id, c.rate_group_id)
where p.rate_group_id is null;");
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
    }
}

Set rateGroup on Projects that currently don't have one

As an addition to 1c304ea, we also try to set the rateGroup based on the
customer.


<?php
namespace KayStrobach\Menu;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "Fluid".                 *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Package\Package as BasePackage;
use TYPO3\Flow\Configuration\ConfigurationManager;

/**
 * The Fluid Package
 *
 */
class Package extends BasePackage {

	/**
	 * @var boolean
	 */
	protected $protected = TRUE;

	/**
	 * Invokes custom PHP code directly after the package manager has been initialized.
	 *
	 * @param \TYPO3\Flow\Core\Bootstrap $bootstrap The current bootstrap
	 * @return void
	 */
	public function boot(\TYPO3\Flow\Core\Bootstrap $bootstrap) {
		//register Configuration Type Menu
		$dispatcher = $bootstrap->getSignalSlotDispatcher();
		$dispatcher->connect('TYPO3\Flow\Configuration\ConfigurationManager', 'configurationManagerReady',
			function ($configurationManager) {
				$configurationManager->registerConfigurationType('Menus');
			}
		);
	}
}

?>

Add external file as menu

[TASK] Add external file as menu


<?php
/**
 * JBZoo Utils
 *
 * This file is part of the JBZoo CCK package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package   Utils
 * @license   MIT
 * @copyright Copyright (C) JBZoo.com,  All rights reserved.
 * @link      https://github.com/JBZoo/Utils
 * @author    Denis Smetannikov <denis@jbzoo.com>
 */

namespace JBZoo\Utils;

/**
 * Class Ob
 * @package JBZoo\Utils
 */
class Ob
{
    /**
     * Clean ll ob_* buffers
     */
    public static function clean()
    {
        while (@ob_end_clean()) {
            // noop
        }
    }
}

Add helper for ob_* functions

Add helper for ob_* functions


<?php

namespace Tests\Regis\Application\Model\Git;

use Regis\Application\Model\Git;

class DiffTest extends \PHPUnit_Framework_TestCase
{
    public function testGetAddedTextFilesExcludesBinaryFiles()
    {
        $binaryFile = $this->binaryFile();
        $textFile = $this->textFile();
        $diff = new Git\Diff($this->revisions(), [$binaryFile, $textFile]);

        $this->assertEquals([$textFile], iterator_to_array($diff->getAddedTextFiles()));
    }

    public function testGetAddedTextFilesExcludesRenamedFiles()
    {
        $renamedFile = $this->renamedFile();
        $textFile = $this->textFile();
        $diff = new Git\Diff($this->revisions(), [$renamedFile, $textFile]);

        $this->assertEquals([$textFile], iterator_to_array($diff->getAddedTextFiles()));
    }

    public function testGetAddedTextFilesExcludesDeletedFiles()
    {
        $deletedFile = $this->deletedFile();
        $textFile = $this->textFile();
        $diff = new Git\Diff($this->revisions(), [$deletedFile, $textFile]);

        $this->assertEquals([$textFile], iterator_to_array($diff->getAddedTextFiles()));
    }

    private function revisions(): Git\Revisions
    {
        return $this->getMockBuilder(Git\Revisions::class)->disableOriginalConstructor()->getMock();
    }

    private function binaryFile(): Git\Diff\File
    {
        $file = $this->getMockBuilder(Git\Diff\File::class)->disableOriginalConstructor()->getMock();
        $file->expects($this->any())
            ->method('isBinary')
            ->will($this->returnValue(true));

        return $file;
    }

    private function renamedFile(): Git\Diff\File
    {
        $file = $this->getMockBuilder(Git\Diff\File::class)->disableOriginalConstructor()->getMock();
        $file->expects($this->any())
            ->method('isRename')
            ->will($this->returnValue(true));

        return $file;
    }

    private function deletedFile(): Git\Diff\File
    {
        $file = $this->getMockBuilder(Git\Diff\File::class)->disableOriginalConstructor()->getMock();
        $file->expects($this->any())
            ->method('isDeletion')
            ->will($this->returnValue(true));

        return $file;
    }

    private function textFile(): Git\Diff\File
    {
        return $this->getMockBuilder(Git\Diff\File::class)->disableOriginalConstructor()->getMock();
    }
}

Add tests for the Model\Git\Diff class

Add tests for the Model\Git\Diff class


<?php

/**
 * This file contains a PHP Class autoloader, which
 * on class instantiation tries to load the required
 * source file automatically without the need to
 * explicitely use a "require" or "include" statement
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * PHP Class Autoloader
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
class Autoload
{

    /**
     * The include path used for class lookup
     * @var String
     */
    private static include_path;

    /**
     * Try to load the given class file from the include path
     *
     * @param String $class The Class name of the Class to load
     *
     * @return void
     */
    public static function load($class)
    {

    }

    /**
     * Add a path to the include path
     *
     * @param String $path New path that should be added to the include path
     *
     * @return void
     */
    public static function add_include_path($path)
    {

    }

}

?>

system: Add basic structure of an autoloader class


<?php
use PhpBrew\Testing\CommandTestCase;

class InstallCommandTest extends CommandTestCase
{
    /**
     * @outputBuffering enabled
     */
    public function testInstallCommandLatestMinorVersion() {
        $this->assertTrue($this->runCommand("phpbrew --quiet install 5.4")); // we will likely get 5.4.34 - 2014-11-02
    }

    /**
     * @outputBuffering enabled
     */
    public function testInstallCommand()
    {
        $this->assertTrue($this->runCommand("phpbrew --quiet install 5.4.29 +sqlite +intl +icu"));
    }

    /**
     * @outputBuffering enabled
     * @depends testInstallCommand
     */
    public function testCleanCommand()
    {
        $this->assertTrue($this->runCommand("phpbrew --quiet clean 5.4.29"));
    }

    /**
     * @outputBuffering enabled
     * @depends testInstallCommand
     */
    public function testInstallLikeCommand() {
        $this->assertTrue($this->runCommand("phpbrew --quiet install -d --like 5.4.29 5.5.18 +soap"));
    }

}

<?php
use PhpBrew\Testing\CommandTestCase;

class InstallCommandTest extends CommandTestCase
{
    /**
     * @outputBuffering enabled
     */
    public function testInstallCommandLatestMinorVersion() {
        $this->assertTrue($this->runCommand("phpbrew --quiet install 5.4")); // we will likely get 5.4.34 - 2014-11-02
    }

    /**
     * @outputBuffering enabled
     */
    public function testInstallCommand()
    {
        $this->assertTrue($this->runCommand("phpbrew --quiet install 5.4.29 +sqlite +intl +icu"));
    }

    /**
     * @outputBuffering enabled
     * @depends testInstallCommand
     */
    public function testListCommand()
    {
        $this->assertTrue($this->runCommand("phpbrew list -v -d"));
        $this->assertTrue($this->runCommand("phpbrew list --dir --variants"));
    }

    /**
     * @outputBuffering enabled
     * @depends testInstallCommand
     */
    public function testCleanCommand()
    {
        $this->assertTrue($this->runCommand("phpbrew --quiet clean 5.4.29"));
    }

    /**
     * @outputBuffering enabled
     * @depends testInstallCommand
     */
    public function testInstallLikeCommand() {
        $this->assertTrue($this->runCommand("phpbrew --quiet install -d --like 5.4.29 5.5.18 +soap"));
    }

}

Test list command after the installation


<?php

namespace Unit\lib\Dumper;

use Chris\Composer\AutoregisterClassmapPlugin\Dumper\AutoloadDumper;
use Neirda24\Bundle\ToolsBundle\Converter\ArrayToText;
use Phake;
use Phake_IMock;

class AutoloadDumperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string PATH_AUTOLOAD_PSR4
     */
    const PATH_AUTOLOAD_PSR4 = './vendor/composer/autoload_psr4.php';

    /**
     * @var string PATH_AUTOLOAD_PSR4_CHILD
     */
    const PATH_AUTOLOAD_PSR4_CHILD = './vendor/composer/autoload_psr4_child.php';

    /**
     * @var string VENDOR_DIR
     */
    const VENDOR_DIR = './vendor';

    /**
     * @var ArrayToText | Phake_IMock
     */
    protected $arrayToText;

    /**
     * @var AutoloadDumper
     */
    protected $dumper;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->arrayToText = Phake::mock(ArrayToText::class);
        $this->dumper      = new AutoloadDumper(self::VENDOR_DIR, $this->arrayToText);
    }

    /**
     * Test the method to dump the autoload_psr4
     */
    public function testDumpAutoloadPsr4()
    {
        Phake::when($this->arrayToText)->arrayToString(Phake::anyParameters())->thenReturn('"AppModule\\\Module\\\Bundle\\\TestBundle\\\" => "/path/to/module/",');

        $this->dumper->dumpAutoloadPsr4(array('namespace' => 'path'));

        Phake::verify($this->arrayToText)->arrayToString(Phake::anyParameters());

        unlink(self::PATH_AUTOLOAD_PSR4);

        rename(self::PATH_AUTOLOAD_PSR4_CHILD, self::PATH_AUTOLOAD_PSR4);
    }
}

Add test on the autoload dumper

[feature/AddTest] Add test on the autoload dumper


<?php
return array(
    'required' => "harus diisi",
    'equals' => "harus sama dengan '%s'",
    'different' => "harus berbeda dengan '%s'",
    'accepted' => "harus diterima (accepted)",
    'numeric' => "harus berupa nomor/angka",
    'integer' => "harus berupa nilai integer (0-9)",
    'length' => "harus lebih panjang dari %d",
    'min' => "harus lebih besar dari %s",
    'max' => "harus kurang dari %s",
    'in' => "berisi nilai/value yang tidak valid",
    'notIn' => "berisi nilai/value yang tidak valid",
    'ip' => "format alamat IP tidak benar",
    'email' => "format alamat email tidak benar",
    'url' => "bukan format URL yang benar",
    'urlActive' => "harus berupa domain aktif",
    'alpha' => "hanya boleh menggunakan huruf a-z",
    'alphaNum' => "hanya boleh menggunakan huruf a-z dan atau nomor 0-9",
    'slug' => "hanya boleh menggunakan huruf a-z, nomor 0-9, tanda minus (-), dan uderscore atau strip bawah (_)",
    'regex' => "berisi karakter yang tidak valid",
    'date' => "format tanggal tidak valid",
    'dateFormat' => "harus berupa tanggal dengan format '%s'",
    'dateBefore' => "tanggal harus sebelum tanggal '%s'",
    'dateAfter' => "tanggal harus sesudah tanggal '%s'",
    'contains' => "harus berisi %s",
    'boolean' => "harus berupa nilai boolean",
    'lengthBetween' => "harus diantara karakter %d dan %d",
    'creditCard' => "nomor kartu kredit harus valid",
    "lengthMin" => "minimal berisi %d karakter",
    "lengthMax" => "maksimal berisi %d karakter"
);

Add language for Bahasa Indonesia

Add language for Bahasa Indonesia


<?php

namespace Jadu\Pulsar\Twig\Extension;

/**
 * Base URL
 */
class BaseUrlExtension extends \Twig_Extension
{

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

    public function getGlobals()
    {
        return array(
            'base_url' => $this->getBaseUrl()
        );
    }

    public function getBaseUrl()
    {
        return "http://" . $_SERVER['HTTP_HOST'] . '/';
    }

}

Add an extension to register the base_url global within twig templates


<?php

namespace Tests\AppBundle\Command;

use AppBundle\API\Details\Organism;
use AppBundle\Command\ImportTraitEntriesCommand;
use AppBundle\Entity\TraitCategoricalEntry;
use AppBundle\Entity\TraitFormat;
use AppBundle\Entity\TraitType;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;

class ImportOrganismDBTest extends KernelTestCase
{
    /**
     * @var EntityManager
     */
    private $em;
    /**
     * @var CommandTester
     */
    private $commandTester;
    /**
     * @var Command
     */
    private $command;

    public function setUp()
    {
        self::bootKernel();
        $application = new Application(self::$kernel);

        $application->add(new ImportOrganismDBTest());

        $this->command = $application->find('app:import-organism-db');
        $this->commandTester = new CommandTester($this->command);
        $this->em = self::$kernel->getContainer()->get('app.orm')->getManagerForVersion('test');
    }

    public function testExecute()
    {
        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'file' => __DIR__ . '/files/emptyFile.tsv'
        ));
        // the output of the command in the console
        $output = $this->commandTester->getDisplay();
        $this->assertContains('Importer', $output);
    }

}

Add new php test for organism import

Add new php test for organism import


<?php

use Mdd\QueryBuilder\Conditions;
use Mdd\QueryBuilder\Types;
use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper;

class HelperTest extends PHPUnit_Framework_TestCase
{
    protected
        $escaper;

    protected function setUp()
    {
        $this->escaper = new SimpleEscaper();
    }

    public function testMixedHelper()
    {
        $condition = (new Conditions\Equal('name', new Types\String('rainbow')))
            ->or(
                (new Conditions\Equal('taste', new Types\String('burger')))
                ->and(new Conditions\Equal('rank', new Types\Integer(42)))
            );

        $this->assertSame($condition->toString($this->escaper), "name = 'rainbow' OR (taste = 'burger' AND rank = 42)");
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testNoParameterGiven()
    {
        $condition = new Conditions\Equal('taste', new Types\String('burger'));
        $condition->or();
    }

    /**
     * @expectedException \LogicException
     */
    public function testTypoInOrHelperName()
    {
        $condition = new Conditions\Equal('taste', new Types\String('burger'));
        $condition->ro(new Conditions\Equal('taste', new Types\String('vegetable')));
    }

    /**
     * @expectedException \LogicException
     */
    public function testTypoInAndHelperName()
    {
        $condition = new Conditions\Equal('taste', new Types\String('burger'));
        $condition->adn(new Conditions\Equal('taste', new Types\String('vegetable')));
    }
}

Add bonary condition Helper test

Add bonary condition Helper test


<?php
use Migrations\AbstractMigration;

class AddAttemptsToJobs extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('jobs');
        $table->addColumn('attempts', 'string', [
            'default' => null,
            'limit' => 255,
            'null' => false,
        ]);
        $table->update();
    }
}

Add missing migration for job attempts

Add missing migration for job attempts


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage View
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

namespace Zend\I18n\View\Helper;

use DateTime;
use IntlDateFormatter;
use Zend\View\Helper\AbstractHelper;
use Zend\I18n\Exception;

/**
 * View helper for formatting dates.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage View
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class DateFormat extends AbstractHelper
{
    /**
     * Formatter instances.
     *
     * @var array
     */
    protected $formatters = array();

    /**
     * Add a formatter.
     *
     * @param  string            $name
     * @param  IntlDateFormatter $formatter
     * @return DateFormat
     */
    public function addFormatter($name, IntlDateFormatter $formatter)
    {
        $this->formatters[$name] = $formatter;
        return $this;
    }

    /**
     * Format a date.
     *
     * @param  DateTime|integer|array $date
     * @param  string
     * @param  string $textDomain
     * @param  string $locale
     * @return string
     */
    public function __invoke($date, $formatterName)
    {
        if (!isset($this->formatters[$formatterName]) {
            throw new Exception\RuntimeException(sprintf(
                'No formatter with name %s found',
                $formatterName
            )));
        }

        return $this->formatters[$formatterName]
                    ->format($date);
    }
}

Add date format view helper

[zen-18] Add date format view helper


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Tests\Unit\Utilities\Page\Posts;

use Codeception\Util\Stub;
use GrottoPress\Jentil\Tests\Unit\TestCase;
use GrottoPress\Jentil\Utilities\Page\Posts\Posts;
use GrottoPress\Jentil\Utilities\Page\Posts\Singular;
use tad\FunctionMocker\FunctionMocker;

class SingularTest extends TestCase
{
    public function testPostType()
    {
        FunctionMocker::replace('get_post_type', 'tutorial');

        $singular = new Singular(Stub::makeEmpty(Posts::class));

        $this->assertSame('tutorial', $singular->postType());
    }
}

Add tests for singular page posts utility


<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;

/**
 * Sends notifications through Slack Webhooks
 *
 * @author Haralan Dobrev <hkdobrev@gmail.com>
 * @see    https://api.slack.com/incoming-webhooks
 */
class SlackWebhookHandler extends AbstractProcessingHandler
{
    /**
     * Slack Webhook token
     * @var string
     */
    private $webhookUrl;

    /**
     * Instance of the SlackRecord util class preparing data for Slack API.
     * @var SlackRecord
     */
    private $slackRecord;

    /**
     * @param  string      $webhookUrl             Slack Webhook URL
     * @param  string|null $channel                Slack channel (encoded ID or name)
     * @param  string      $username               Name of a bot
     * @param  bool        $useAttachment          Whether the message should be added to Slack as attachment (plain text otherwise)
     * @param  string|null $iconEmoji              The emoji name to use (or null)
     * @param  bool        $useShortAttachment     Whether the the context/extra messages added to Slack as attachments are in a short style
     * @param  bool        $includeContextAndExtra Whether the attachment should include context and extra data
     * @param  int         $level                  The minimum logging level at which this handler will be triggered
     * @param  bool        $bubble                 Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(
        $webhookUrl,
        $channel = null,
        $username = 'Monolog',
        $useAttachment = true,
        $iconEmoji = null,
        $useShortAttachment = false,
        $includeContextAndExtra = false,
        $level = Logger::CRITICAL,
        $bubble = true
    ) {
        parent::__construct($level, $bubble);

        $this->webhookUrl = $webhookUrl;

        $this->slackRecord = new SlackRecord(
            $channel,
            $username,
            $useAttachment,
            $iconEmoji,
            $useShortAttachment,
            $includeContextAndExtra,
            $this->formatter
        );
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        $postData = $this->slackRecord->getSlackData($record);
        $postString = json_encode($postData);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->webhookUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (defined('CURLOPT_SAFE_UPLOAD')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $postString));

        Curl\Util::execute($ch);
    }
}

Add a Slack Webhooks handler using the same SlackRecord util


<?php
require_once('Sprinkles.php');

print "PHP major version: " . php_major_version() . "<br />";

print($needs_unbollocks ? "PHP version thought to be pre-6. Needs unbollocks"
                        : "PHP version thought to be 6 or later. No need for unbollocks." );
?>

Test to see what version we think we are.

git-svn-id: e1a96f6b7015dfe5b5e86c875acd3ba0869cf04b@58 afa44554-0db9-64d6-dc80-ec3199b23f77


<?php

namespace FBN\GuideBundle\Tests\Utils;

use FBN\GuideBundle\Utils\Entity;
use FBN\GuideBundle\Entity\Article;

/**
 * Unitary tests for the methods defined inside Entity utility class.
 *
 */
class EntityTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test that article entity date publication comparisons are corrects.
     */
    public function testCompareDate()
    {
        $article1 = $this->createMock(Article::class);
        $article1->method('getDatePublication')
            ->willReturn(new \DateTime('2000-01-01'));

        $article2 = $this->createMock(Article::class);
        $article2->method('getDatePublication')
            ->willReturn(new \DateTime('2001-01-01'));

        $int = Entity::compareDate($article1, $article2);

        $this->assertEquals(1, $int);

        $int = Entity::compareDate($article2, $article1);

        $this->assertEquals(-1, $int);

        $int = Entity::compareDate($article2, $article2);

        $this->assertEquals(0, $int);
    }
}

Add unitary tests for methods defined in Entity utility class


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.3.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Test\TestCase;

use App\Application;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\MiddlewareStack;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\TestSuite\IntegrationTestCase;

/**
 * ApplicationTest class
 */
class ApplicationTest extends IntegrationTestCase
{

    /**
     * testMiddleware
     *
     * @return void
     */
    public function testMiddleware()
    {
        $app = new Application(dirname(dirname(__DIR__)) . '/config');
        $middleware = new MiddlewareStack();

        $middleware = $app->middleware($middleware);

        $this->assertInstanceOf(ErrorHandlerMiddleware::class, $middleware->get(0));
        $this->assertInstanceOf(AssetMiddleware::class, $middleware->get(1));
        $this->assertInstanceOf(RoutingMiddleware::class, $middleware->get(2));
    }
}

Add tests for Application class.

Add tests for Application class.


<?php
/**
 * @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
 *    Confidential and Proprietary. Any dissemination outside of Quicken Loans
 *    is strictly prohibited.
 */

namespace QL\Panthor\Twig;

use Mockery;
use PHPUnit_Framework_TestCase;

class LazyTwigTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testMissingTemplateThrowsException()
    {
        $env = Mockery::mock('Twig_Environment');
        $twig = new LazyTwig($env, new Context);

        $twig->render();
    }

    public function testRenderIsPassedThroughToRealTwig()
    {
        $realTwig = Mockery::mock('Twig_Template', ['render' => null]);
        $env = Mockery::mock('Twig_Environment');
        $env
            ->shouldReceive('loadTemplate')
            ->with('path/to/template/file')
            ->andReturn($realTwig)
            ->once();

        $twig = new LazyTwig($env, new Context, 'path/to/template/file');

        $twig->render();
    }

    public function testTemplateSetterOverridesConstructorTemplate()
    {
        $realTwig = Mockery::mock('Twig_Template', ['render' => null]);
        $env = Mockery::mock('Twig_Environment');
        $env
            ->shouldReceive('loadTemplate')
            ->with('real/file')
            ->andReturn($realTwig)
            ->once();

        $twig = new LazyTwig($env, new Context, 'path/to/template/file');
        $twig->setTemplate('real/file');

        $twig->render();
    }

    public function testContextIsMergedOnRenderIfProvided()
    {
        $realTwig = Mockery::mock('Twig_Template', ['render' => null]);
        $env = Mockery::mock('Twig_Environment', ['loadTemplate' => $realTwig]);
        $context = new Context;

        $twig = new LazyTwig($env, $context, 'path/to/template/file');
        $twig->render(['goobypls' => 'test']);

        $this->assertSame('test', $context->get('goobypls'));
    }

    public function testNonRenderMethodIsPassedThrough()
    {
        $realTwig = Mockery::mock('Twig_Template');
        $realTwig
            ->shouldReceive('testing')
            ->once();

        $env = Mockery::mock('Twig_Environment', ['loadTemplate' => $realTwig]);

        $twig = new LazyTwig($env, new Context, 'path/to/template/file');
        $twig->testing();
    }
}

Add test for lazy twig

Add test for lazy twig


<?php

    $configuration = [
        'settings' => [
            'displayErrorDetails' => true,
        ],
    ];

    // Create container
    $container = new \Slim\Container($configuration);

    // Register component on container
    $container['view'] = function ($c) {
        $view = new \Slim\Views\Twig('templates', [
            'cache' => 'cache',
            'auto_reload' => 'false'
        ]);
        $view->addExtension(new \Slim\Views\TwigExtension(
            $c['router'],
            $c['request']->getUri()
        ));

        return $view;
    };

    // Create app
    $app = new \Slim\App($container);

    // Render Twig template in route
    if (firstRunCheck()) {
        $app->get('/', function($request, $response, $args) {
            return $this->view->render($response, 'base.twig');
        });
    } else {
        $app->get('/', function($request, $response, $args) {
            return $this->view->render($response, 'firstrun.twig');
        });

        $app->post('/firstRun', function($request, $response, $args) {
            $userDetails = $request->getParsedBody();
            if(createAdminUser($userDetails)) {
                return $this->view->render($response, 'admin.twig');
            } else {
                return $this->view->render($response, 'error.twig');
            }
        });
    }

    // Run app

    $app->run();

    function firstRunCheck() {
        static $configFileExists = false;

        if (!$configFileExists) {
            if (file_exists('config.ini')) {
                $configFileExists = true;
            }
            return $configFileExists;
        } else {
            return $configFileExists;
        }
    }

    function createAdminUser($userDetails) {
        $config = new Config_Lite('config.ini');

        $config->set('admin', 'username', $userDetails['username'])
            ->set('admin', 'password', password_hash($userDetails['password'], PASSWORD_DEFAULT))
            ->set('admin', 'email', $userDetails['email'])
            ->set('admin', 'displayname', $userDetails['displayname']);

        $config->save();

        return true;
    }
?>

Add partial routes and functions for handling first run situation and app paintialisation


<?php
/**
 * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
 * @author Lukas Reschke <lukas@owncloud.com>
 * @author Michael Gapczynski <GapczynskiM@gmail.com>
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Victor Dubiniuk <dubiniuk@owncloud.com>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
style('lostpassword', 'resetpassword');
script('core', 'lostpassword');
?>

<form action="<?php print_unescaped($_['link']) ?>" id="reset-password" method="post">
	<fieldset>

			<?php p($l->t('New password')); ?>
			<input type="password" autocomplete="off" name="password" id="password" value="" placeholder="<?php p($l->t('New Password')); ?>" required />

		<input type="submit" id="submit" value="<?php p($l->t('Reset password')); ?>" />

			<img class="hidden" id="float-spinner" src="<?php p(\OCP\Util::imagePath('core', 'loading-dark.gif'));?>"/>

	</fieldset>
</form>

Fix AutoComplete Not Disabled for 'Password' Field vulnerability


<?php

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

class UpdateModelsReferenceInWebmentionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('webmentions', function (Blueprint $table) {
            DB::statement("UPDATE webmentions SET commentable_type = 'App\\Models\\Note' WHERE commentable_type = 'App\\Note'");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('webmentions', function (Blueprint $table) {
            DB::statement("UPDATE webmentions SET commentable_type = 'App\\Note' WHERE commentable_type = 'App\\Models\\Note'");
        });
    }
}

Update the database to use the right model namespace


<?php

interface Core_Lock_LockInterface
{
	const LOCK_TTL_SECONDS = 2.0;
	const LOCK_UNIQUE_ID = 'daemon_lock';

	public function set();
	public function check();
}

Add missing path seperator to File Lock Provider path


<?php

use App\Models\Revision;
use App\Models\Block;
use Illuminate\Database\Migrations\Migration;

/**
 * Migrates any block definitions not using the {name}-v{version} format for identifying regions.
 */
class MigrateDataToIncludeVersionsInDefinitions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
	{
		$count = $updated = 0;
		foreach (Revision::all() as $revision) {
			$json = $revision->blocks;
			$count++;
			if (!empty($json)) {
				$data = [];
				$changed = false;
				foreach ($json as $name => $sections) {
					if (!preg_match('/-v[0-9]+$/', $name)) {
						$name = $name . '-v1';
						$changed = true;
					}
					$data[$name] = $sections;
				}
				if($changed) {
					$revision->blocks = $data;
					$revision->save();
					$updated++;
				}
			}
		}
		echo "$updated of $count revisions updated to use {name}-v{version} syntax for identifying regions.\n";
		$updated = $count = 0;
		foreach (Block::all() as $block) {
			$count++;
			if (!preg_match('/-v[0-9]+$/', $block->region_name)) {
				$updated++;
				$block->region_name .= '-v1';
				$block->save();
			}
		}
		echo "$updated of $count blocks updated to use {name}-v{version} syntax for identifying regions.\n";
	}

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Migrate existing data to use {name}-v{version} syntax for referencing definitions.


<?php namespace src\twig;

use Slim\Slim;

class TwigExtension extends \Twig_Extension
{
    public function getName()
    {
        return 'slim-framework-skeleton';
    }

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('assetUrl', array($this, 'assetUrl')),
        );
    }

    public function assetUrl($file, $appName = 'default')
    {
        $req = Slim::getInstance($appName)->request();
        $uri = $req->getUrl() . $req->getRootUri();

        if ($file[0] === '/') {
            return $uri . $file;
        }

        return $uri . '/' . $file;
    }
}

Add custom twig extension class

Add custom twig extension class


<?php
namespace Bitrix24\Presets;

class UserFields
{
	const TYPE = 'type';
	const IS_REQUIRED = 'isRequired';
	const IS_READ_ONLY = 'isReadOnly';
	const IS_IMMUTABLE = 'isImmutable';
	const IS_MULTIPLE = 'isMultiple';
	const IS_DYNAMIC = 'isDynamic';
	const LIST_LABEL = 'listLabel';
	const FORM_LABEL = 'formLabel';
	const FILTER_LABEL = 'filterLabel';
}

Add presets for user fields data type structure


<?php
namespace Crud\Listener;

use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;

class SearchListener extends BaseListener
{

    /**
     * Settings
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => [
            'Crud.beforeLookup',
            'Crud.beforePaginate'
        ]
    ];

    /**
     * Returns a list of all events that will fire in the controller during its lifecycle.
     * You can override this function to add your own listener callbacks
     *
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'Crud.beforeLookup' => ['callable' => 'injectSearch'],
            'Crud.beforePaginate' => ['callable' => 'injectSearch']
        ];
    }

    /**
     * Inject search conditions to the qeury object.
     *
     * @param \Cake\Event\Event $event Event
     * @return void
     */
    public function injectSearch(Event $event)
    {
        if (!Plugin::loaded('Search')) {
            throw new RuntimeException(
                'You need to load the Search plugin in order to use the SearchListener.'
            );
        }

        if (!in_array($event->name, $this->config('enabled'))) {
            return;
        }

        $table = $this->_table();
        if (!method_exists($table, 'filterParams')) {
            throw new RuntimeException(sprintf(
                'Missing Search.Search behavior on %s',
                get_class($table)
            ));
        }

        $filterParams = $table->filterParams($this->_request()->query);
        $event->subject->query->find('search', $filterParams);
    }
}

<?php
namespace Crud\Listener;

use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;

class SearchListener extends BaseListener
{

    /**
     * Settings
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => [
            'Crud.beforeLookup',
            'Crud.beforePaginate'
        ]
    ];

    /**
     * Returns a list of all events that will fire in the controller during its lifecycle.
     * You can override this function to add your own listener callbacks
     *
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'Crud.beforeLookup' => ['callable' => 'injectSearch'],
            'Crud.beforePaginate' => ['callable' => 'injectSearch']
        ];
    }

    /**
     * Inject search conditions to the qeury object.
     *
     * @param \Cake\Event\Event $event Event
     * @return void
     */
    public function injectSearch(Event $event)
    {
        if (!Plugin::loaded('Search')) {
            throw new RuntimeException(
                'You need to load the Search plugin in order to use the SearchListener.'
            );
        }

        if (!in_array($event->name, $this->config('enabled'))) {
            return;
        }

        $table = $this->_table();
        if (!$table->behaviors()->hasMethod('filterParams')) {
            throw new RuntimeException(sprintf(
                'Missing Search.Search behavior on %s',
                get_class($table)
            ));
        }

        $filterParams = $table->filterParams($this->_request()->query);
        $event->subject->query->find('search', $filterParams);
    }
}

Fix check for missing behavior

Fix check for missing behavior

- The method exists on a behavior, and is proxied, so therefore `method_exists` is a bad check.
- You can't simply check for `hasBehavior('Search')` as a user can alias a behavior to another one.
- Since we are calling `filterParams` and that is the only dependency, simply checking if the method is in the `BehaviorRegistry::$methodMap` is enough.


<?php namespace Odoo\Client\Test;

use PhpXmlRpc\Value as xmlrpcval;
use Odoo\Client\OdooClient;

class FieldsViewsTest extends TestOdooClient
{
    public function testFieldsGetWithFieldFilter()
    {
        $filter = array(
            new xmlrpcval('name', xmlrpcval::$xmlrpcString),
            new xmlrpcval('code', xmlrpcval::$xmlrpcString),
            new xmlrpcval('phone_code', xmlrpcval::$xmlrpcString)
        );

        $fields = array(new xmlrpcval($filter, xmlrpcval::$xmlrpcArray));

        $client = new OdooClient($this->_host, $this->_port, $this->_db, $this->_username, $this->_password);
        $res = $client->fields_get($this->_model_name, $fields);

        $this->assertNotNull($res);
        $this->assertTrue(is_array($res));
        $this->assertArrayHasKey('code', $res);
        $this->assertArrayHasKey('phone_code', $res);
    }

    public function testFieldsGetWithoutFieldFilter()
    {
        $filter = array();

        $fields = array(new xmlrpcval($filter, xmlrpcval::$xmlrpcArray));

        $client = new OdooClient($this->_host, $this->_port, $this->_db, $this->_username, $this->_password);
        $res = $client->fields_get($this->_model_name, $fields);

        $this->assertNotNull($res);
        $this->assertTrue(is_array($res));
        $this->assertArrayHasKey('create_uid', $res);
        $this->assertArrayHasKey('code', $res);
        $this->assertArrayHasKey('display_name', $res);
        $this->assertArrayHasKey('name', $res);
        $this->assertArrayHasKey('__last_update', $res);
        $this->assertArrayHasKey('state_ids', $res);
        $this->assertArrayHasKey('image', $res);
        $this->assertArrayHasKey('write_uid', $res);
        $this->assertArrayHasKey('currency_id', $res);
        $this->assertArrayHasKey('address_format', $res);
        $this->assertArrayHasKey('phone_code', $res);
        $this->assertArrayHasKey('country_group_ids', $res);
        $this->assertArrayHasKey('write_date', $res);
        $this->assertArrayHasKey('create_date', $res);
        $this->assertArrayHasKey('id', $res);
    }
}

[ADD] Add new test cases for fields and views methods


<?php
/**
 * Mockery
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://github.com/padraic/mockery/master/LICENSE
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to padraic@php.net so we can send you a copy immediately.
 *
 * @category   Mockery
 * @package    Mockery
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2010-2014 Pádraic Brady (http://blog.astrumfutura.com)
 * @license    http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
 */

namespace test\Mockery;

use Mockery\Adapter\Phpunit\MockeryTestCase;

class MockingVariadicArgumentsTest extends MockeryTestCase
{

    public function setup()
    {
        $this->container = new \Mockery\Container;
    }

    public function teardown()
    {
        $this->container->mockery_close();
    }

    /** @test */
    public function shouldAllowMockingVariadicArguments()
    {
        $mock = $this->container->mock("test\Mockery\TestWithVariadicArguments");

        $mock->shouldReceive("foo")->andReturn("notbar");
        $this->assertEquals("notbar", $mock->foo());
    }
}

abstract class TestWithVariadicArguments
{
    public function foo(...$bar)
    {
        return $bar;
    }
}

Add a test for variadic arguments

Add a test for variadic arguments


<?php
/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Clastic\NodeBundle\Node;

use Clastic\NodeBundle\Entity\Node;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
trait NodeReferenceTrait
{
    /**
     * @var Node
     */
    private $node;

    /**
     * @return Node
     */
    public function getNode()
    {
        return $this->node;
    }

    /**
     * @param Node $node
     */
    public function setNode(Node $node)
    {
        $this->node = $node;
    }
}

[Node] Add trait to simplify NodeReference Entities.


<?php
namespace CdliAutogenUsernameTest;

use CdliAutogenUsername\Generator;

class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    public function testSingleFilterChain()
    {
        $gen = new Generator(array(
            'datasource' => 'test',
            'filters' => array(
                'test' => array(
                    'filter' => 'randomdigits',
                    'priority' => -100,
                    'options' => array( 'digits' => 5 )
                ),
            ),
        ));

        $mock = $this->getMock('CdliAutogenUsername\Datasource\DatasourceInterface');
        $gen->getDatasourceBroker()->register('test', $mock);

        var_dump($gen->generate());
    }
}

Add skeleton integration test class

Add skeleton integration test class


<?php

class FilenameFilterTest extends \Codeception\TestCase\Test
{
	public function testFilenameFilterClean()
	{
		$tests = array(

			// Illegal characters
			'foo*\.bar' => 'foo.bar',
			'foobar{baz}.jpg' => 'foobar(baz).jpg',
			'foobar^%.docx' => 'foobar_.docx',

			// Control characters
			'foobar' . chr(127) . '.gif' => 'foobar.gif',
			'foobar' . "\t\r\n" . '.gif' => 'foobar.gif',

			// Unicode whitepace characters
			'foobar' . html_entity_decode(' ') . ' space.gif' => 'foobar space.gif',
			'hello     world.png' => 'hello world.png',

			// Extra symbols
			'_foobar.jpg-' => 'foobar.jpg',
			'.htaccess' => 'htaccess',

			// PHP extension
			'foobar.php' => 'foobar.phps',
			'foobar.php.jpg' => 'foobar.php.jpg',

			// Overlong filenames
			str_repeat('f', 200) . '.' . str_repeat('b', 30) => str_repeat('f', 111) . '.' . str_repeat('b', 15),
			str_repeat('한글', 100) . '.hwp' => str_repeat('한글', 61) . '한.hwp',

		);

		foreach ($tests as $from => $to)
		{
			$result = Rhymix\Framework\Security\FilenameFilter::clean($from);
			$this->assertEquals($to, $result);
		}
	}
}

Add unit tests for FilenameFilter class

Add unit tests for FilenameFilter class


<?php
/**
 * © 2017 Procurios
 */
namespace Procurios\TDD\PhpunitAdapter\test;

use PHPUnit_Framework_ExpectationFailedException;
use Procurios\TDD\PhpunitAdapter\PhpunitAdapterTestCase;
use ReflectionObject;

/**
 *
 */
abstract class PhpunitAdapterTestCaseWithFailingMethods extends PhpunitAdapterTestCase
{
    /**
     * @dataProvider provideFailingMethods
     * @param string $failingMethod
     */
    public function testThatAssertionsCanFail($failingMethod)
    {
        try {
            $exceptionThrown = false;
            $testCase = new static($failingMethod);
            $testCase->runTest();
        } catch (PHPUnit_Framework_ExpectationFailedException $e) {
            $exceptionThrown = true;
        }

        $this->assertTrue($exceptionThrown);
    }

    /**
     * @return array
     */
    public function provideFailingMethods()
    {
        $failingMethods = array();

        $reflectionObject = new ReflectionObject($this);
        foreach ($reflectionObject->getMethods() as $reflectionMethod) {
            if (preg_match('(^let.*?Fail)', $reflectionMethod->getName())) {
                $failingMethods[] = array($reflectionMethod->getName());
            }
        }

        return $failingMethods;
    }
}

Add base test class that tests failing methods


<?php

class Empty_Taxonomy_Type extends Papi_Taxonomy_Type {

	/**
	 * Define our Taxonomy Type meta data.
	 *
	 * @return array
	 */
	public function meta() {
		return [
			'name'        => 'Empty taxonomy',
			'description' => 'This is a empty taxonomy',
			'template'    => 'pages/empty-taxonomy.php'
		];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
	}
}

Add empty taxonomy type test file

Add empty taxonomy type test file


<?php

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

namespace Chigi\Bundle\ChijiBundle\Project;

use Chigi\Chiji\Project\LessRoad;
use Chigi\Chiji\Project\UrlStampEnum;

/**
 * The less road for symfony bundle project only.
 *
 * @author 郷
 */
class BundleLessRoad extends LessRoad {

    public $bundleName = "";

    /**
     * Get the release format map.
     * @return array<typename==string>
     */
    protected function getReleaseFormatMap() {
        $map = parent::getReleaseFormatMap();
        $map['TWIG_CSS_LINK'] = '<link type="text/css" href="{{ asset("chiji/' . $this->bundleName . '/[LESS_FILE]") }}?[STAMP]" rel="stylesheet">';
        return $map;
    }

    protected function getUrlStampType() {
        return UrlStampEnum::HASH;
    }

}

ADD Lessroad for symfony .

ADD Lessroad for symfony .

Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>


<?php
/**
 * @package plugins.tagSearch
 * @relatedService TagService
 * @subpackage api.filters.base
 * @abstract
 */
abstract class KalturaTagBaseFilter extends KalturaRelatedFilter
{
	static private $map_between_objects = array
	(
		"tagEqual" => "_eq_tag",
		"tagStartsWith" => "_likex_tag",
		"taggedObjectTypeEqual" => "_eq_tagged_object_type",
		"instanceCountEqual" => "_eq_instance_count",
		"instanceCountIn" => "_in_instance_count",
		"instanceCountGreaterThanOrEqual" => "_gte_instance_count",
		"instanceCountLessThanOrEqual" => "_lte_instance_count",
		"createdAtGreaterThanOrEqual" => "_gte_created_at",
		"createdAtLessThanOrEqual" => "_lte_created_at",
	);

	static private $order_by_map = array
	(
		"+instanceCount" => "+instance_count",
		"-instanceCount" => "-instance_count",
		"+createdAt" => "+created_at",
		"-createdAt" => "-created_at",
	);

	public function getMapBetweenObjects()
	{
		return array_merge(parent::getMapBetweenObjects(), self::$map_between_objects);
	}

	public function getOrderByMap()
	{
		return array_merge(parent::getOrderByMap(), self::$order_by_map);
	}

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

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

	/**
	 * @var KalturaTaggedObjectType
	 */
	public $taggedObjectTypeEqual;

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

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

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

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

	/**
	 * @var time
	 */
	public $createdAtGreaterThanOrEqual;

	/**
	 * @var time
	 */
	public $createdAtLessThanOrEqual;
}

Add new fields for the TagFilter

Add new fields for the TagFilter


<?php

namespace mcordingley\Regression\Tests\Algorithm\GradientDescent\Schedule;

use mcordingley\Regression\Algorithm\GradientDescent\Schedule\Adagrad;
use PHPUnit_Framework_TestCase;

class AdagradTest extends PHPUnit_Framework_TestCase
{
    public function testStep()
    {
        $schedule = new Adagrad(0.01, 0.000001);
        $schedule->update([1.0]);
        static::assertEquals(0.0099999900000100009, $schedule->step(0));
    }
}

Test the Adagrad gradient schedule.

Test the Adagrad gradient schedule.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class CandidateStep4Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
			     ->add('job_experience', 'choice', array(
			     		'multiple' => TRUE,
			     		'expanded' => TRUE,
			     		'choices' => array(
			     				'1' => 'Actividades físicas o deportivas',
			     				'2' => 'Administración o gestión',
			     				'3' => 'Agraria o pesquera',
			     				'4' => 'Arte o artesanía',
			     				'5' => 'Comercio y marketing',
			     				'6' => 'Edificación, obra civil',
			     				'7' => 'Energía o agua',
			     				'8' => 'Mecánica, electricidad o electrónica',
			     				'9' => 'Hostelería y turismo',
			     				'10' => 'Informática o comunicaciones',
			     				'11' => 'Industria',
			     				'12' => 'Sanidad',
			     				'13' => 'Medio Ambiente',
			     				'14' => 'Educación o servicios a la comunidad',
			     				'15' => 'Transporte',
			     				'16' => 'Finanzas',
			     		),
			     ))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add candidate step 4 form type

Add candidate step 4 form type


<?php

require_once 'swiftmailer/lib/swift_required.php';

		if (isset($_POST['nojs'])) {
			$messageHTML = "Text of the message : " . urldecode($message)
					. "
Your Quote Summary

Item	Description	Price

" . $machinemodel . "

Item	Description	Price

" . $weighhopper . "

Item	Description	Price

" . $dischargefunnel . "

";
			$messageText = "Text of the message : " . urldecode($message)
					. "Your Quote Summary \r " . $machinemodel . " \n " . $weighhopper . " \n " . $dischargefunnel;
		} else {
			$to = $_POST['to'];
			$cc = $_POST['cc'];
			$message =  $_POST['message'];
			$quoteHTML = $_POST['quoteHTML'];
			$quoteText = $_POST['quoteText'];
			$messageHTML = urldecode($quoteHTML) . " \r " . urldecode($message);
			$messageText = urldecode($quoteText) . " \r " . urldecode($message);
		}

		// Create the Transport
		/*
		 $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
		 ->setUsername('your username')
		 ->setPassword('your password')
		 ;
		 */
		$transport = Swift_MailTransport::newInstance();
		// Create the Mailer using your created Transport
		$mailer = Swift_Mailer::newInstance($transport);

		// Create a message
		$emailMessage = Swift_Message::newInstance(
				'Logical Machines Quote Generator')
				->setBody($messageHTML, 'text/html')
				->addPart($messageText, 'text/plain')
				->setFrom(
						array('pete@spirelightmedia.com' => 'Logical Machines'))
				->setSender('pgjainsworth@gmail.com')
				->setReturnPath('pgjainsworth@gmail.com')
				->setBcc(array('pgjainsworth@gmail.com'))->setMaxLineLength(78)
				->setTo(array($to));
		if (!empty($cc)) {
			$emailMessage->setCc(array($cc));
		}

		if ($mailer->send($emailMessage)) {
			$response = "

Thank you. Your email has been successfully sent.

";
		} else {
			$errors['mailfail'] = true;
		}

?>

Split out email processing into a separate file.


<?php

namespace Enzyme\Axiom\Atoms;

use Enzyme\Axiom\Exceptions\AtomException;

/**
 * A wrapper around boolean values.
 */
class BooleanAtom implements AtomInterface
{
    /**
     * Holds the underlying value.
     *
     * @var string
     */
    protected $value;

    /**
     * Create a new boolean atom.
     *
     * @param mixed $value
     */
    public function __construct($value)
    {
        if (is_bool($value) === false) {
            throw new AtomException(get_class(), $value);
        }

        $this->value = (int) $value;
    }

    /**
     * @see AtomInterface
     */
    public function getValue()
    {
        return $this->value;
    }
}

Add new boolean atom type.

Add new boolean atom type.


<?php

namespace Gedmo\Mapping\Driver;

use Gedmo\Mapping\Driver\AnnotationDriverInterface;

/**
 * This is an abstract class to implement common functionality
 * for extension annotation mapping drivers.
 *
 * @author     Derek J. Lambert <dlambert@dereklambert.com>
 * @package    Gedmo.Mapping.Driver
 * @subpackage AnnotationDriverInterface
 * @link       http://www.gediminasm.org
 * @license    MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
abstract class AbstractAnnotationDriver implements AnnotationDriverInterface
{
    /**
     * Annotation reader instance
     *
     * @var object
     */
    protected $reader;

    /**
     * Original driver if it is available
     */
    protected $_originalDriver = null;

    /**
     * List of types which are valid for extension
     *
     * @var array
     */
    protected $validTypes = array();

    /**
     * {@inheritDoc}
     */
    public function setAnnotationReader($reader)
    {
        $this->reader = $reader;
    }

    /**
     * Passes in the mapping read by original driver
     *
     * @param $driver
     *
     * @return void
     */
    public function setOriginalDriver($driver)
    {
        $this->_originalDriver = $driver;
    }

    /**
     * @param object $meta
     *
     * @return array
     */
    public function getMetaReflectionClass($meta)
    {
        $class = $meta->getReflectionClass();
        if (!$class) {
            // based on recent doctrine 2.3.0-DEV maybe will be fixed in some way
            // this happens when running annotation driver in combination with
            // static reflection services. This is not the nicest fix
            $class = new \ReflectionClass($meta->name);
        }
        return $class;
    }
}

Refactor common code into abstract class.


<?php

namespace Oro\Bundle\CalendarBundle\Manager;

use Oro\Bundle\CalendarBundle\Entity\Attendee;
use Oro\Bundle\CalendarBundle\Entity\Repository\AttendeeRepository;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;

class AttendeeManager
{
    /** @var DoctrineHelper */
    protected $doctrineHelper;

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

    /**
     * @param string $id
     *
     * @return Attendee[]
     */
    public function loadAttendeesByCalendarEventId($id)
    {
        /** @var AttendeeRepository $attendeeRepository */
        $attendeeRepository = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:Attendee');

        return $attendeeRepository->getAttendeesByCalendarEventId($id);
    }
}

<?php

namespace Oro\Bundle\CalendarBundle\Manager;

use Oro\Bundle\CalendarBundle\Entity\Attendee;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;

class AttendeeManager
{
    /** @var DoctrineHelper */
    protected $doctrineHelper;

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

    /**
     * @param string $id
     *
     * @return Attendee[]
     */
    public function loadAttendeesByCalendarEventId($id)
    {
        return $this->doctrineHelper
            ->getEntityRepository('OroCalendarBundle:Attendee')
            ->getAttendeesByCalendarEventId($id);
    }
}

Fix review issues - minor fix

AEIV-665: Fix review issues
- minor fix


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Jtk\Notifications;

use Jivoo\Snippets\CometSnippet;
use Jivoo\Core\Json;

class NotificatonServer extends CometSnippet {

  protected $refreshRate = 1.0;

  protected function update() {
    $this->session->open();
    if (isset($this->session['jtk-notifications'])) {
      $notifications = $this->session['jtk-notifications'];
      if (is_array($notifications) and count($notifications) > 0) {
        unset($this->session['jtk-notifications']);
        $this->session->close();
        return Json::encodeResponse($notifications);
      }
    }
    $this->session->close();
    return null;
  }
}

Add comet server for future JTK notification system.


<?php

use App\Models\Attributes\Vehicle\VehicleCategory;

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * This is the vehicle category extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class VehicleCategoryExtractorTest extends AbstractVehicleExtractorTest
{
    public function testExtractVehicleValidCategory()
    {
        $text = [
            'ciclomotor da marca APRILIA'    => 'Ciclomotor',
            'veículo ligeiro de passageiros' => 'Automóvel ligeiro',
            'veículo pesado'                 => 'Automóvel pesado',
            'triciclo'                       => 'Triciclo',
            'tractor'                        => 'Tractor agrícola/florestal',
            'trator'                         => 'Tractor agrícola/florestal',
            'tractocarro'                    => 'Tractocarro',
            'tratocarro'                     => 'Tractocarro',
            'motocultivador'                 => 'Motocultivador',
            'moto-cultivador'                => 'Motocultivador',
            'reboque'                        => 'Reboque',
            'semi-reboque'                   => 'Reboque',
            'empilhador'                     => 'Máquina industrial',
        ];

        foreach ($text as $input => $expected) {
            $categoryId = $this->extractor->category($input);

            if ($this->assertNotNull($categoryId)) {
                $this->assertSame($expected, VehicleCategory::find($categoryId)->name);
            }
        }
    }
}

Test the vehicle category extractor

Test the vehicle category extractor


<?php

class ExamplesTest extends \PHPUnit_Framework_TestCase {

  public function testParsePhpLikeArrayExample() {
    $array_keyword = Parser::str('array');
    $comma = Parser::char(',');
    $identifier = Parser::satisfyChar(function ($c) { return ctype_alnum($c); });
    $item = Parser::many1($identifier);
    $items_list = Parser::product(
      Parser::many(Parser::product($item, $comma)),
      $item
    );
    $open = Parser::char('(');
    $close = Parser::char(')');
    $array = Parser::product(
      $array_keyword,
      Parser::product(Parser::product($open, $items_list), $close)
              ->or_(Parser::product($open, $close))
    );

    $t1 = 'array(lbas2d,aaa,aaaaa)';
    $t2 = 'array(a,a,a)';
    $t3 = 'array(9)';
    $t4 = 'array()';

    $test = function ($input) use ($array) {
      $this->assertEquals(
        new Good($input, strlen($input)),
        Parser::slice($array)->run($input),
        'PHP-like array example'
      );
    };

    $test($t1);
    $test($t2);
    $test($t3);
    $test($t4);

  }

}

Add example of parsing a php-like array.


<?php

require(__DIR__ . "/../vendor/autoload.php");
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TestModelHydrate
 *
 * @author guillaume
 */
$json = <<<EOF
{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}
EOF;
error_log($json);
$object = json_decode(trim($json));
error_log(json_last_error_msg());
error_log(print_r(Rad\Model\Model::hydrate($object), true));

Add Test for hydrate model

Add Test for hydrate model