<?php namespace Purplapp\Adn;

use stdClass;
use GuzzleHttp\Message\Response;

trait DataContainerTrait
{
    private $data = [];

    private $dataEnvelope = [];

    public static function wrap($data)
    {
        if ($data instanceof stdClass) {
            return static::wrapObject($data);
        } elseif ($data instanceof Response) {
            return static::wrapResponse($data);
        } elseif (is_array($data)) {
            return static::wrapArray($data);
        }

        throw new InvalidArgumentException(gettype($data) . " is not a valid wrappable");
    }

    private static function wrapObject(stdClass $object)
    {
        return new static($object);
    }

    private static function wrapResponse(Response $response)
    {
        return new static($response->json(["object" => true])->data);
    }

    private static function wrapArray(array $array)
    {
        return new static((object) $array);
    }

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

        $this->init();
    }

    public function __get($key)
    {
        if (method_exists($this, $key)) {
            return $this->$key();
        }

        return $this->data->$key;
    }

    public function __isset($key)
    {
        return method_exists($this, $key) || isset($this->data->$key);
    }

    public function init()
    {
        // no-op
    }
}

<?php namespace Purplapp\Adn;

use stdClass;
use GuzzleHttp\Message\Response;

trait DataContainerTrait
{
    private $data = [];

    private $dataEnvelope = [];

    public static function wrap($data)
    {
        if ($data instanceof stdClass) {
            return static::wrapObject($data);
        } elseif ($data instanceof Response) {
            return static::wrapResponse($data);
        } elseif (is_array($data)) {
            return static::wrapArray($data);
        }

        throw new InvalidArgumentException(gettype($data) . " is not a valid wrappable");
    }

    private static function wrapObject(stdClass $object)
    {
        return new static($object);
    }

    private static function wrapResponse(Response $response)
    {
        $payload = $response->json(["object" => true]);

        // strip the envelope
        if (isset($payload->data) && isset($payload->meta)) {
            return new static($payload->data);
        }

        return new static($payload);
    }

    private static function wrapArray(array $array)
    {
        return new static((object) $array);
    }

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

        $this->init();
    }

    public function __get($key)
    {
        if (method_exists($this, $key)) {
            return $this->$key();
        }

        return $this->data->$key;
    }

    public function __isset($key)
    {
        return method_exists($this, $key) || isset($this->data->$key);
    }

    public function init()
    {
        // no-op
    }
}

Make the envelope stripping in wrap smarter


<?php
/*----------------------------------------------------------------------------*/

	namespace Apps\Wiki\Actors;

	class Location extends \Libs\Actor {
		public function execute(\Libs\DOM\Element $element) {
			parent::execute($element);

			ini_set('html_errors', true);

			$session = \Libs\Session::current();
			$settings = $session->app()->settings();
			$parameters = $session->parameters();

			$url = $parameters->{'document-url'}->get();
			$documents = (
				$url != ''
					? $documents = explode('/', $url)
					: array()
			);
			$path = '';

			foreach ($documents as $document) {
				$path = ltrim($path . '/' . $document, '/');
				$item = $element->ownerDocument->createElement('item');
				$item->setAttribute('path', $path);
				$item->setAttribute('name', str_replace('-', ' ', $document));
				$element->appendChild($item);
			}
		}
	}

/*----------------------------------------------------------------------------*/
?>

<?php
/*----------------------------------------------------------------------------*/

	namespace Apps\Wiki\Actors;

	class Location extends \Libs\Actor {
		public function execute(\Libs\DOM\Element $element) {
			parent::execute($element);

			ini_set('html_errors', true);

			$session = \Libs\Session::current();
			$settings = $session->app()->settings();
			$constants = $session->constants();
			$parameters = $session->parameters();
			$document = $element->ownerDocument;

			$url = $parameters->{'document-url'}->get();
			$files = (
				$url != ''
					? explode('/', $url)
					: array()
			);
			$path = '';

			foreach ($files as $file) {
				$path = $path . '/' . $file;
				$name = ucfirst(str_replace('-', ' ', $file));

				try {
					$xml = new \Libs\DOM\Document();
					$xml->loadHTMLFile(sprintf(
						'%s/docs%s.html',
						$constants->{'app-dir'},
						$path
					));
					$value = $xml->{'string(//h1[1])'};

					if ($value) $name = $value;
				}

				catch (\Exception $e) {
					// De-serialised name is fine.
				}

				$item = $document->createElement('item');
				$item->setAttribute('path', ltrim($path, '/'));
				$item->setAttribute('name', $name);
				$element->appendChild($item);
			}
		}
	}

/*----------------------------------------------------------------------------*/
?>

Load breadcrumb titles from documents if possible.


<?
/**
 * Belgian Police Web Platform - Districts Component
 *
 * @copyright	Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.police.be
 */
?>

<? $officers = @object('com:districts.model.districts_officers')->district($district->id)->getRowset(); ?>

<? if(count($officers)) : ?>

	<? foreach ($officers as $officer) : ?>
		<?= @template('com:districts.view.district.default_officer.html', array('officer' => @object('com:districts.model.officer')->set('id', $officer->districts_officer_id)->getRow())); ?>
	<? endforeach ?>

<? else : ?>

<?= @text('No neighbourhood officer found') ?>

<? endif ?>

	<?
        $contact = @object('com:contacts.model.contact')->set('id', $district->contacts_contact_id)->getRow();
        $contact->misc = null;
    ?>
    <?= @template('com:contacts.view.contact.hcard.html', array('contact' => $contact)); ?>

<?
/**
 * Belgian Police Web Platform - Districts Component
 *
 * @copyright	Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.police.be
 */
?>

<? $officers = @object('com:districts.model.districts_officers')->district($district->id)->getRowset(); ?>

<? if(count($officers)) : ?>

	<? foreach ($officers as $officer) : ?>
		<?= @template('com:districts.view.district.default_officer.html', array('officer' => @object('com:districts.model.officer')->id($officer->districts_officer_id)->getRow())); ?>
	<? endforeach ?>

<? else : ?>

<?= @text('No neighbourhood officer found') ?>

<? endif ?>

	<?
        $contact = @object('com:contacts.model.contact')->id($district->contacts_contact_id)->getRow();
        $contact->misc = null;
    ?>
    <?= @template('com:contacts.view.contact.hcard.html', array('contact' => $contact)); ?>

Update Nooku Framework, Model::set() has been removed


<?php

namespace Torann\GeoIP;

use Illuminate\Support\ServiceProvider;
use Torann\GeoIP\Console\UpdateCommand;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/config/geoip.php' => config_path('geoip.php'),
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['geoip'] = $this->app->share(function ($app) {
            return new GeoIP(
                $app->config->get('geoip', []),
                $app['session.store']
            );
        });

        $this->app['command.geoip.update'] = $this->app->share(function ($app) {
            return new UpdateCommand($app['geoip']);
        });

        $this->commands(['command.geoip.update']);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            'geoip',
            'command.geoip.update',
        ];
    }
}

<?php

namespace Torann\GeoIP;

use Illuminate\Support\ServiceProvider;
use Torann\GeoIP\Console\UpdateCommand;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->isLumen() === false) {
            $this->publishes([
                __DIR__ . '/config/geoip.php' => config_path('geoip.php'),
            ], 'config');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['geoip'] = $this->app->share(function ($app) {
            return new GeoIP(
                $app->config->get('geoip', []),
                $app['session.store']
            );
        });

        $this->app['command.geoip.update'] = $this->app->share(function ($app) {
            return new UpdateCommand($app['geoip']);
        });

        $this->commands(['command.geoip.update']);
    }

    /**
     * Check if package is running under Lumen app
     *
     * @return bool
     */
    protected function isLumen()
    {
        return str_contains($this->app->version(), 'Lumen') === true;
    }
}

Add Lumen check and tags to assets

Add Lumen check and tags to assets


<?php

namespace Ivory\GoogleMapBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories for the given environment
     *
     * @param string $environment
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);

            if(empty(self::$initialize))
                $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.'/'.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

<?php

namespace Ivory\GoogleMapBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories for the given environment
     *
     * @param string $environment
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);

            if(empty(self::$initialize))
                $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.'/'.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

Fix FileSystem class due to symfony update


<?php

class SimplePrivatePosts extends Plugin
{

	public function action_plugin_activation()
	{
		ACL::create_token('private', 'Permissions on posts marked as "private"');

		// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
		$anon = UserGroup::get('anonymous');
		if ( false != $anon ) {
			$anon->deny('private');
		}
	}

	public function action_plugin_deactivation( $plugin_file )
	{
		if ( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) {
			ACL::destroy_token('private');
		}
	}

	public function action_form_publish($form, $post)
	{
		if ( $post->content_type == Post::type('entry') ) {
			$form->settings->append('checkbox', 'private_post', 'null:null', _t('Private Post'), 'tabcontrol_checkbox');
			if ( $post->has_tokens('private') ) {
				$form->private_post->value = true;
			}
		}
	}

	public function action_publish_post($post, $form)
	{
		if ( $post->content_type == Post::type('entry') ) {
			if ( $form->private_post->value == true ) {
				$post->add_tokens('private');
			}
			else {
				$post->remove_tokens('private');
			}
		}
	}

}
?>

<?php

class SimplePrivatePosts extends Plugin
{

	public function action_plugin_activation()
	{
		ACL::create_token('private', 'Permission to read posts marked as "private"', 'Private Posts');

		// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
		$anon = UserGroup::get('anonymous');
		if ( false != $anon ) {
			$anon->deny('private');
		}
	}

	public function action_plugin_deactivation( $plugin_file )
	{
		if ( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) {
			ACL::destroy_token('private');
		}
	}

	public function action_form_publish($form, $post)
	{
		if ( $post->content_type == Post::type('entry') ) {
			$form->settings->append('checkbox', 'private_post', 'null:null', _t('Private Post'), 'tabcontrol_checkbox');
			if ( $post->has_tokens('private') ) {
				$form->private_post->value = true;
			}
		}
	}

	public function action_publish_post($post, $form)
	{
		if ( $post->content_type == Post::type('entry') ) {
			if ( $form->private_post->value == true ) {
				$post->add_tokens('private');
			}
			else {
				$post->remove_tokens('private');
			}
		}
	}

}
?>

Add the required group when creating the token. Clarify the description text.

git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@4019 653ae4dd-d31e-0410-96ef-6bf7bf53c507


<?php

namespace Kunstmaan\UtilitiesBundle\Twig;

use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig_Extension;

class UtilitiesTwigExtension extends Twig_Extension
{
    /**
     * @var SlugifierInterface
     */
    private $slugifier;

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

    /**
     * Returns a list of filters.
     *
     * @return array An array of filters
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('slugify', array($this, 'slugify')),
        );
    }

    /**
     * @param string $text
     *
     * @return string
     */
    public function slugify($text)
    {
        return $this->slugifier->slugify($text, '');
    }
}

<?php

namespace Kunstmaan\UtilitiesBundle\Twig;

use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig_Extension;

class UtilitiesTwigExtension extends Twig_Extension
{
    /**
     * @var SlugifierInterface
     */
    private $slugifier;

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

    /**
     * Returns a list of filters.
     *
     * @return array An array of filters
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('slugify', array($this, 'slugify')),
        );
    }

    /**
     * @param string $text
     *
     * @return string
     */
    public function slugify($text)
    {
        return $this->slugifier->slugify($text, '');
    }
}

Add public visibility to constructors

Add public visibility to constructors


<?php
namespace Neos\Flow\Persistence\Doctrine\Migrations;

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

/**
 * Adapt column naming to support PostgreSQL
 */
class Version20170718190551 extends AbstractMigration
{

    /**
     * @return string
     */
    public function getDescription()
    {
        return 'Adapt column naming to support PostgreSQL';
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE ttree_contentrepositoryimporter_domain_model_import CHANGE start starttime DATETIME NOT NULL, end endtime DATETIME DEFAULT NULL');
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE ttree_contentrepositoryimporter_domain_model_import CHANGE starttime start DATETIME NOT NULL, endtime end DATETIME DEFAULT NULL');
    }
}

<?php
namespace Neos\Flow\Persistence\Doctrine\Migrations;

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

/**
 * Adapt column naming to support PostgreSQL
 */
class Version20170718190551 extends AbstractMigration
{

    /**
     * @return string
     */
    public function getDescription()
    {
        return 'Adapt column naming to support PostgreSQL';
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE ttree_contentrepositoryimporter_domain_model_import CHANGE `start` `starttime` DATETIME NOT NULL, CHANGE `end` `endtime` DATETIME DEFAULT NULL');
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE ttree_contentrepositoryimporter_domain_model_import CHANGE `starttime` `start` DATETIME NOT NULL, CHANGE `endtime` `end` DATETIME DEFAULT NULL');
    }
}

BUGFIX: Fix MySQL migration, add missing CHNAGE token


<?php
return array (
  'app_version' => 'v3.6.0',
  'build_version' => '75',
  'hash_version' => 'ga2ffe77',
  'full_hash' => 'v3.6.0-75-ga2ffe77',
);

<?php
return array (
  'app_version' => 'v3.6.1-pre',
  'build_version' => '73',
  'hash_version' => 'ge587b2d',
  'full_hash' => 'v3.6.1-pre-73-ge587b2d',
);

Revert "Halp! Stuck in pre-commit loop hell. :("

This reverts commit 47c77fe042a66a6986e13e3fb621a1338bd1c590.


<?php

namespace Sonata\MediaBundle\Admin\Manager;

use Sonata\AdminBundle\Model\ORM\ModelManager;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;

/**
 * this method overwrite the default AdminModelManager to call
 * the custom methods from the dedicated media manager
 */
class DoctrineORMManager extends ModelManager
{
    protected $manager;

    public function __construct($entityManager, $manager)
    {
        parent::__construct($entityManager);

        $this->manager = $manager;
    }

    public function create($object)
    {
        $this->manager->save($object);
    }

    public function update($object)
    {
        $this->manager->save($object);
    }

    public function delete($object)
    {
        $this->manager->delete($object);
    }

    /**
     * Deletes a set of $class identified by the provided $idx array
     *
     * @param $class
     * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
     * @return void
     */
    public function batchDelete($class, ProxyQueryInterface $queryProxy)
    {
        foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
            $this->delete($object[0]);
        }
    }
}

<?php

namespace Sonata\MediaBundle\Admin\Manager;

use Sonata\DoctrineORMAdminBundle\Model\ModelManager;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;

/**
 * this method overwrite the default AdminModelManager to call
 * the custom methods from the dedicated media manager
 */
class DoctrineORMManager extends ModelManager
{
    protected $manager;

    public function __construct($entityManager, $manager)
    {
        parent::__construct($entityManager);

        $this->manager = $manager;
    }

    public function create($object)
    {
        $this->manager->save($object);
    }

    public function update($object)
    {
        $this->manager->save($object);
    }

    public function delete($object)
    {
        $this->manager->delete($object);
    }

    /**
     * Deletes a set of $class identified by the provided $idx array
     *
     * @param $class
     * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
     * @return void
     */
    public function batchDelete($class, ProxyQueryInterface $queryProxy)
    {
        foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
            $this->delete($object[0]);
        }
    }
}

Fix namespace to use DoctrineORMAdminBundle


<?php

namespace Zend\Romans\View\Helper;

use PHPUnit\Framework\TestCase;
use Zend\View\Helper\HelperInterface;

/**
 * Roman Test
 */
class RomanTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->helper = new Roman();
    }

    /**
     * Test Instance Of
     */
    public function testInstanceOf()
    {
        $this->assertInstanceOf(HelperInterface::class, $this->helper);
    }

    /**
     * Test Roman
     */
    public function testRoman()
    {
        $this->assertSame('N', ($this->helper)(0));
        $this->assertSame('I', ($this->helper)(1));

        $this->assertSame('CDLXIX', ($this->helper)(469));
        $this->assertSame('MCMXCIX', ($this->helper)(1999));
    }
}

<?php

namespace Zend\Romans\View\Helper;

use PHPUnit\Framework\TestCase;
use Zend\View\Helper\HelperInterface;

/**
 * Roman Test
 */
class RomanTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->helper = new Roman();
    }

    /**
     * Test Instance Of
     */
    public function testInstanceOf()
    {
        $this->assertInstanceOf(HelperInterface::class, $this->helper);
    }

    /**
     * Test Roman
     */
    public function testRoman()
    {
        $this->assertSame('N', ($this->helper)(0));
        $this->assertSame('I', ($this->helper)(1));

        $this->assertSame('CDLXIX', ($this->helper)(469));
        $this->assertSame('MCMXCIX', ($this->helper)(1999));
    }

    /**
     * Test Roman with Invalid Value
     */
    public function testRomanWithInvalidValue()
    {
        $this->assertNull(($this->helper)('-1'));
    }
}

Include test for invalid input

Include test for invalid input


<form method="post" action="<?= $this->u('twofactor', 'check', array('user_id' => $this->userSession->getId())) ?>" autocomplete="off">

    <?= $this->formCsrf() ?>
    <?= $this->formLabel(t('Code'), 'code') ?>
    <?= $this->formText('code', array(), array(), array('placeholder="123456"'), 'form-numeric') ?>

    <div class="form-actions">
        <input type="submit" value="<?= t('Check my code') ?>" class="btn btn-blue"/>
    </div>
</form>

<form method="post" action="<?= $this->u('twofactor', 'check', array('user_id' => $this->userSession->getId())) ?>" autocomplete="off">

    <?= $this->formCsrf() ?>
    <?= $this->formLabel(t('Code'), 'code') ?>
    <?= $this->formText('code', array(), array(), array('placeholder="123456"', 'autofocus'), 'form-numeric') ?>

    <div class="form-actions">
        <input type="submit" value="<?= t('Check my code') ?>" class="btn btn-blue"/>
    </div>
</form>

Add autofocus for the 2FA code

Add autofocus for the 2FA code


        <?php echo $group; ?>

        <?php foreach($categories as $category) { ?>
            <?php if($category['subCategory']) { ?>
            <a href="<?php echo $category['link']; ?>" class="list-group-item">
                <?php echo $category['name']; ?>

<?php echo $category['description']; ?>

            <?php } ?>

                    <?php

                    $questions = \humhub\modules\questionanswer\models\Question::find()
                        ->contentContainer($category['space'])
                        ->andFilterWhere(['post_type' => 'question'])
                        ->orderBy('created_at DESC')
                        ->limit(3)
                        ->all();

                    foreach($questions as $q) {
                        echo "
";
                        echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [
                            'id'=> $q['id'],
                            'sguid' => $category['space']->guid
                        ]));
                        echo "
";
                    }
                    ?>

        <?php } ?>

        <?php echo $group; ?>

        <?php foreach($categories as $category) { ?>
            <?php if($category['subCategory']) { ?>
            <a href="<?php echo $category['link']; ?>" class="list-group-item">
                <?php echo $category['name']; ?>

<?php echo $category['description']; ?>

            <?php } ?>

                    <?php

                    $questions = \humhub\modules\questionanswer\models\Question::find()
                        ->contentContainer($category['space'])
                        ->andFilterWhere(['post_type' => 'question'])
                        ->orderBy('created_at DESC')
                        ->limit(6)
                        ->all();

                    foreach($questions as $q) {
                        echo "
";
                        echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [
                            'id'=> $q['id'],
                            'sguid' => $category['space']->guid
                        ]));
                        echo "
";
                    }
                    ?>

        <?php } ?>

Increase number of posts to preview to 6


<?php

namespace adrianclay\git;

use adrianclay\git\References\ReferencesArray;
use PHPUnit\Framework\TestCase;

class RevisionResolverTest extends TestCase
{
    private $sha = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";

    public function testFullSHA()
    {
        $this->assertEqualSHA( $this->getResolver( [], $this->sha ) );
    }

    public function testHEAD()
    {
        $this->assertEqualSHA( $this->getResolver( [ References::HEAD => new SHA( $this->sha ) ], References::HEAD ) );
    }

    public function testMain()
    {
        $this->assertEqualSHA( $this->getResolver( [ 'refs/heads/main' => new SHA( $this->sha ) ], 'main' ) );
    }

    public function testOriginMain()
    {
        $references = [ 'refs/remotes/origin/main' => new SHA( $this->sha ) ];
        $this->assertEqualSHA( $this->getResolver( $references, 'origin/main' ) );
    }

    /**
     * @param SHAReference[] $references
     * @param string         $revision
     * @return RevisionResolver
     */
    private function getResolver( array $references, $revision )
    {
        return new RevisionResolver( new ReferencesArray( $references ), $revision );
    }

    /**
     * @param RevisionResolver $revisionResolver
     */
    private function assertEqualSHA( RevisionResolver $revisionResolver )
    {
        $this->assertEquals( $this->sha, $revisionResolver->getSHA() );
    }

}

<?php

namespace adrianclay\git;

use adrianclay\git\References\ReferencesArray;
use PHPUnit\Framework\TestCase;

class RevisionResolverTest extends TestCase
{
    private $sha = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";

    public function testFullSHA()
    {
        $this->assertEqualSHA( $this->getResolver( [], $this->sha ) );
    }

    public function testHEAD()
    {
        $this->assertEqualSHA( $this->getResolver( [ References::HEAD => new SHA( $this->sha ) ], References::HEAD ) );
    }

    public function testMain()
    {
        $this->assertEqualSHA( $this->getResolver( [ 'refs/heads/main' => new SHA( $this->sha ) ], 'main' ) );
    }

    public function testNumericRefIsDereferenced()
    {
        $this->assertEqualSHA( $this->getResolver( [ 'refs/heads/1111' => new SHA( $this->sha ) ], '1111' ) );
    }

    public function testOriginMain()
    {
        $references = [ 'refs/remotes/origin/main' => new SHA( $this->sha ) ];
        $this->assertEqualSHA( $this->getResolver( $references, 'origin/main' ) );
    }

    /**
     * @param SHAReference[] $references
     * @param string         $revision
     * @return RevisionResolver
     */
    private function getResolver( array $references, $revision )
    {
        return new RevisionResolver( new ReferencesArray( $references ), $revision );
    }

    /**
     * @param RevisionResolver $revisionResolver
     */
    private function assertEqualSHA( RevisionResolver $revisionResolver )
    {
        $this->assertEquals( $this->sha, $revisionResolver->getSHA() );
    }

}

Add a test for a numeric reference

Add a test for a numeric reference


<?php

declare(strict_types=1);

namespace Tests;

class PHPStanTest extends AbstractTestCase
{
    protected $phpStanPreviousDirectory = '.';

    protected function setUp(): void
    {
        parent::setUp();
        $this->phpStanPreviousDirectory = getcwd();
        chdir(__DIR__.'/../..');
    }

    protected function tearDown(): void
    {
        chdir($this->phpStanPreviousDirectory);
        parent::tearDown();
    }

    public function testAnalysesWithoutErrors(): void
    {
        if ($this->analyze(__DIR__.'/Fixture.php') === 0) {
            $this->assertTrue(true);
        }
    }

    private function analyze(string $file)
    {
        $output =  shell_exec(
            'vendor/bin/phpstan'
            . ' analyse'
            . ' --configuration="' . __DIR__ . '/../../extension.neon"'
            . ' --no-progress'
            . ' --no-interaction'
            . ' --level=0'
            . ' "' . $file . '"'
        );
        var_dump($output);

        return $output;
    }
}

<?php

declare(strict_types=1);

namespace Tests;

class PHPStanTest extends AbstractTestCase
{
    protected $phpStanPreviousDirectory = '.';

    protected function setUp(): void
    {
        parent::setUp();
        $this->phpStanPreviousDirectory = getcwd();
        chdir(__DIR__.'/../..');
    }

    protected function tearDown(): void
    {
        chdir($this->phpStanPreviousDirectory);
        parent::tearDown();
    }

    public function testAnalysesWithoutErrors(): void
    {
        if ($this->analyze(__DIR__.'/Fixture.php') === 0) {
            $this->assertTrue(true);
        }
    }

    private function analyze(string $file)
    {
        $output = shell_exec(implode(' ', [
            implode(DIRECTORY_SEPARATOR, ['.', 'vendor', 'bin', 'phpstan']),
            'analyse',
            '--configuration='.escapeshellarg(realpath(__DIR__.'/../../extension.neon')),
            '--no-progress',
            '--no-interaction',
            '--level=0',
            escapeshellarg(realpath($file)),
        ]));
        var_dump($output);

        return $output;
    }
}

Allow to run PHPStan tests on Windows

Allow to run PHPStan tests on Windows


<?php

use MarcBP\PingThis\Ping\NetworkPing;

class NetworkPingTest extends PHPUnit_Framework_TestCase
{
    public function testPingOk()
    {
        $ping = new NetworkPing('test', 0, '127.0.0.1');
        $ping->setMethod(NetworkPing::METHOD_SOCKET);
        $this->assertTrue($ping->ping());
    }

    public function testPingUnvalid()
    {
        $ping = new NetworkPing('test', 0, 'does.not.exist');
        $ping->setMethod(NetworkPing::METHOD_SOCKET);
        $this->assertFalse($ping->ping());
    }
}

<?php

use MarcBP\PingThis\Ping\NetworkPing;

class NetworkPingTest extends PHPUnit_Framework_TestCase
{
    public function testPingOk()
    {
        $ping = new NetworkPing('test', 0, 'google.com');
        $ping->setMethod(NetworkPing::METHOD_SOCKET);
        $ping->setPort(80);
        $this->assertTrue($ping->ping());
    }

    public function testPingUnvalid()
    {
        $ping = new NetworkPing('test', 0, 'does.not.exist');
        $ping->setMethod(NetworkPing::METHOD_SOCKET);
        $this->assertFalse($ping->ping());
    }
}

Make test work on travis

Make test work on travis


@if (App::environment() !== 'production')

This installation of OpenDominion is running on {{ App::environment() }} environment and is not meant for production purposes. Any data you register and actions you take on this instance might be wiped without notice.

@endif

@if (isset($selectedDominion) && $selectedDominion->isLocked())

This dominion is locked due to the round having ended. No actions can be performed and no ticks will be processed.

@endif

@if (!$errors->isEmpty())

        ×

One or more errors occurred:

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

@foreach (['danger', 'warning', 'success', 'info'] as $alert_type)
    @if (Session::has('alert-' . $alert_type))

            ×

{{ Session::get('alert-' . $alert_type) }}

    @endif
@endforeach

Add warning icons to some alerts

Add warning icons to some alerts


<?php

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

class AddCroppedImageColumnToItems extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('reportback_items', function (Blueprint $table) {
            $table->string('cropped_file_url')->nullable()->after('file_url');
        });
    }

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

<?php

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

class AddCroppedImageColumnToItems extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('reportback_items', function (Blueprint $table) {
            $table->string('edited_file_url')->nullable()->after('file_url');
        });
    }

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

Change cropped column to edited column to be more general about manipulations


<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-21
 * Time: 12:56 PM
 */

namespace ShortCirquit\LinkoScopeApi;

class GetLinksRequest
{
    public $authorId = null;
    public $maxResults = 100;
    public $offset = 0;
    public $sortDirection = 'desc';
    public $sortBy = 'score';
}

<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-21
 * Time: 12:56 PM
 */

namespace ShortCirquit\LinkoScopeApi;

class GetLinksRequest
{
    public $authorId = null;
    public $maxResults = 100;
    public $offset = 0;
    public $sortDirection = 'desc';
    public $sortBy = 'score';
    public $tags = [];
}

Add tag support in GetLinkRequest

Add tag support in GetLinkRequest

This field will allow filtering by a tag when listing Links


<?php
echo
	mb_str_pad($fields["id"], $lengths["id"])." | "
	.mb_str_pad($fields["filename"], $lengths["filename"])." | "
	.mb_str_pad($fields["mimetype"], $lengths["mimetype"])." | "
	.mb_str_pad($fields["date"], $lengths["date"])." | "
	.mb_str_pad($fields["hash"], $lengths["hash"])." | "
	.mb_str_pad($fields["filesize"], $lengths["filesize"])."\n";

foreach($query as $key => $item) {
	echo
		mb_str_pad($item["id"], $lengths["id"])." | "
		.mb_str_pad($item["filename"], $lengths["filename"])." | "
		.mb_str_pad($item["mimetype"], $lengths["mimetype"])." | "
		.date("r", $item["date"])." | "
		.$item["hash"]." | "
		.$item["filesize"]."\n";
}
?>

Total sum of your distinct uploads: <?php echo $total_size; ?>.

<?php
$dateformat = "r";
$lengths["date"] = max($lengths["date"], strlen(date($dateformat, time())));
echo
	mb_str_pad($fields["id"], $lengths["id"])." | "
	.mb_str_pad($fields["filename"], $lengths["filename"])." | "
	.mb_str_pad($fields["mimetype"], $lengths["mimetype"])." | "
	.mb_str_pad($fields["date"], $lengths["date"])." | "
	.mb_str_pad($fields["hash"], $lengths["hash"])." | "
	.mb_str_pad($fields["filesize"], $lengths["filesize"])."\n";

foreach($query as $key => $item) {
	echo
		mb_str_pad($item["id"], $lengths["id"])." | "
		.mb_str_pad($item["filename"], $lengths["filename"])." | "
		.mb_str_pad($item["mimetype"], $lengths["mimetype"])." | "
		.date($dateformat, $item["date"])." | "
		.$item["hash"]." | "
		.$item["filesize"]."\n";
}
?>

Total sum of your distinct uploads: <?php echo $total_size; ?>.

Fix alignment of date column in plain text view

This got broken by 2a6a1c63cb21015009fe4fd13f62cdac64e1fe36 and
05a4d686b578794c180ddfaf4945a9d7443f330e.

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>


<?php

/**
 * Landing CMS
 *
 * A simple CMS for Landing Pages.
 *
 * @package    Landing CMS
 * @author     Ilia Chernykh <landingcms@yahoo.com>
 * @copyright  2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
 * @license    https://opensource.org/licenses/LGPL-2.1  LGPL-2.1
 * @version    Release: 0.0.5
 * @link       https://github.com/Elias-Black/Landing-CMS
 */

// Connecting main classes
require_once('../_classes/index.php');

defined('CORE') OR die('403');

$data = array();

// Catching form submit
if( !empty($_POST) )
{
	$data = User::updatePassword();
}

// Render form of changing password
$content = Utils::render(
	'forms/password.php',
	 $data
);

// Printing page
echo Utils::renderIndex($content, $data);

<?php

/**
 * Landing CMS
 *
 * A simple CMS for Landing Pages.
 *
 * @package    Landing CMS
 * @author     Ilia Chernykh <landingcms@yahoo.com>
 * @copyright  2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
 * @license    https://opensource.org/licenses/LGPL-2.1  LGPL-2.1
 * @version    Release: 0.0.5
 * @link       https://github.com/Elias-Black/Landing-CMS
 */

// Connecting main classes
require_once('../_classes/index.php');

defined('CORE') OR die('403');

$data = isset($message) ? $message : array();

// Catching form submit
if( !empty($_POST) )
{
	$data = User::updatePassword();
}

// Render form of changing password
$content = Utils::render(
	'forms/password.php',
	 $data
);

// Printing page
echo Utils::renderIndex($content, $data);

Fix for display messages from User class.


<?php

// Loaded in the project itself
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    return require_once __DIR__ . '/../vendor/autoload.php';
}

// Loaded as a dependency
if (file_exists(__DIR__ . '/../../../../autoload.php')) {
    return require_once __DIR__ . '/../../../../autoload.php';
}

// Loaded in the project itself, when vendor isn't installed
if (file_exists(__DIR__ . '/../daux.phar')) {
    define('PHAR_DIR', __DIR__ . '/..');

    return require_once 'phar://' . __DIR__ . '/../daux.phar/vendor/autoload.php';
}

throw new Exception('Impossible to load Daux, missing vendor/ or daux.phar');

<?php

// Loaded as a dependency
if (file_exists(__DIR__ . '/../../../autoload.php')) {
    return require_once __DIR__ . '/../../../autoload.php';
}

// Loaded in the project itself
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    return require_once __DIR__ . '/../vendor/autoload.php';
}

// Loaded in the project itself, when vendor isn't installed
if (file_exists(__DIR__ . '/../daux.phar')) {
    define('PHAR_DIR', __DIR__ . '/..');

    return require_once 'phar://' . __DIR__ . '/../daux.phar/vendor/autoload.php';
}

throw new Exception('Impossible to load Daux, missing vendor/ or daux.phar');

Fix autoloading and prioritize getting it as a dependency


<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(Config::get('auth.table'))->onDelete('cascade');
            $table->timestamps();
        });
    }

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

}

<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
            $table->timestamps();
        });
    }

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

}

Use config helper & update config key

Use config helper & update config key


<?php

namespace Clue\React\Buzz\Message;

class HeaderBag
{
    private $headers;

    public static function factory($headers)
    {
        if (!($headers instanceof self)) {
            $headers = new self($headers);
        }
        return $headers;
    }

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

    public function getHeaderValues($search)
    {
        $search = strtolower($search);

        $ret = array();

        foreach ($this->headers as $key => $values) {
            if (strtolower($key) === $search) {
                if (is_array($values)) {
                    foreach ($values as $value) {
                        $ret []= $value;
                    }
                } else {
                    $ret []= $values;
                }
            }
        }

        return $ret;
    }

    public function getHeaderValue($search)
    {
        return reset($this->getHeaderValues($search));
    }
}

<?php

namespace Clue\React\Buzz\Message;

class HeaderBag
{
    private $headers;

    public static function factory($headers)
    {
        if (!($headers instanceof self)) {
            $headers = new self($headers);
        }
        return $headers;
    }

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

    public function getHeaderValues($search)
    {
        $search = strtolower($search);

        $ret = array();

        foreach ($this->headers as $key => $values) {
            if (strtolower($key) === $search) {
                if (is_array($values)) {
                    foreach ($values as $value) {
                        $ret []= $value;
                    }
                } else {
                    $ret []= $values;
                }
            }
        }

        return $ret;
    }

    public function getHeaderValue($search)
    {
        return reset($this->getHeaderValues($search));
    }

    public function getAll()
    {
        return $this->headers;
    }
}

Add getAll() accessor for all header fields


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => env('STORAGE_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path().'/app',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('S3_KEY'),
            'secret' => env('S3_SECRET'),
            'region' => 'us-east-1',
            'bucket' => env('S3_BUCKET'),
        ],

    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => env('STORAGE_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path().'/app',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY'),
            'secret' => env('AWS_SECRET_KEY'),
            'region' => 'us-east-1',
            'bucket' => env('S3_BUCKET'),
        ],

    ],

];

Use standardized S3 environment variables.


<?php

namespace JSON_Loader {

	/**
	 * Class Array_Generator
	 */
	class Array_Generator {

		var $generator_class;

		var $values;

		var $parent;

		var $args;

		/**
		 * @param string $generator_class
		 * @param array $values
		 * @param Generator $parent
		 * @param array $args
		 */
		function __construct( $generator_class, $values, $parent, $args ) {

			$this->generator_class = $generator_class;
			$this->values          = $values;
			$this->parent          = $parent;
			$this->args            = $args;

		}

		function execute() {

			$generator_class = $this->generator_class;

			foreach( $this->values as $index => $value ) {

				/**
				 * @var Generator $generator
				 */
				$generator = new $generator_class( $value, $this->parent, $this->args );

				$generator->generate( $value, $generator );

			}

		}

	}

}

<?php

namespace JSON_Loader {

	/**
	 * Class Array_Generator
	 */
	class Array_Generator {

		var $generator_class;

		var $values;

		var $parent;

		var $args;

		/**
		 * @param string $generator_class
		 * @param array $values
		 * @param Generator $parent
		 * @param array $args
		 */
		function __construct( $generator_class, $values, $parent, $args ) {

			$this->generator_class = $generator_class;
			$this->values          = $values;
			$this->parent          = $parent;
			$this->args            = $args;

		}

		function execute() {

			$generator_class = $this->generator_class;

			foreach( $this->values as $index => $value ) {

				if ( 0 < $index ) {
					/**
					 * @todo Yes, this is really screwy. We'd need to rearchitect to fix it eventually.
					 */
					$s = Util::get_state( $value );
					Util::get_state( $s->owner )->set_values( $s->values() );
				}

				Generator::generate( $value, new $generator_class( $value, $this->parent, $this->args ) );

			}

		}

	}

}

Fix generation error for array generators.


<?php

// don't run on CLI
if ( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) {
    return;
}

if ( !isset( $_SERVER['HTTP_HOST'] ) ) {
    return;
}
if ( strpos( $_SERVER['HTTP_HOST'], 'vvv.test' ) != false ) {
    return;
}

$is_vvv_tideways = false;

if ( file_exists( '/srv/config/tideways.json' ) && in_array( $_SERVER['HTTP_HOST'], json_decode( file_get_contents( '/srv/config/tideways.json' ) ) ) ) {
    $is_vvv_tideways = true;
}

if ( isset( $_REQUEST['enable-tideways'] ) && ( $_REQUEST['enable-tideways'] == true ) ) {
    $is_vvv_tideways = true;
}

if( ! $is_vvv_tideways ) {
    return;
}

if ( file_exists( '/srv/www/default/php-profiler/config.php' ) ) {
    include '/srv/www/default/php-profiler/config.php';
}

// Query monitor it will be disabled with TIdeways/XHGUI PHP Profiler
define( 'QM_DISABLED', true );

<?php

$is_vvv_tideways = false;

if ( empty( $_SERVER['REMOTE_ADDR'] ) and !isset( $_SERVER['HTTP_USER_AGENT'] ) and count( $_SERVER['argv']) > 0 ) {
    // CLI
    if ( isset( $_ENV['ENABLE_TIDEWAYS_CLI'] ) && $_ENV['ENABLE_TIDEWAYS_CLI'] === '1' ) {
        $is_vvv_tideways = true;
    }
} else {
    // Web requests:
    if ( !isset( $_SERVER['HTTP_HOST'] ) ) {
        return;
    }

    if ( strpos( $_SERVER['HTTP_HOST'], 'vvv.test' ) != false ) {
        return;
    }

    if ( file_exists( '/srv/config/tideways.json' ) && in_array( $_SERVER['HTTP_HOST'], json_decode( file_get_contents( '/srv/config/tideways.json' ) ) ) ) {
        $is_vvv_tideways = true;
    }

    if ( isset( $_REQUEST['enable-tideways'] ) && ( $_REQUEST['enable-tideways'] == true ) ) {
        $is_vvv_tideways = true;
    }
}

if( ! $is_vvv_tideways ) {
    return;
}

if ( file_exists( '/srv/www/default/php-profiler/config.php' ) ) {
    include '/srv/www/default/php-profiler/config.php';
}

// Disable Query monitor when using TIdeways/XHGUI PHP Profiler
define( 'QM_DISABLED', true );

Allow tideways to run if ENABLE_TIDEWAYS_CLI is defined as an environment variable


@extends('layouts.masterLayout')

@section('html_title', 'All Corporation Industry')

@section('page_content')

  @foreach (array_chunk($corporations, 2) as $corpSplitted)

      @foreach ($corpSplitted as $corp)

{{ $corp->corporationName }}

From character: {{ $corp->characterName }}

              corporationID }}_32.png" class="img-circle" />

             $corp->corporationID)) }}" class="small-box-footer">
              View Corporation Jobs

      @endforeach

  @endforeach

@stop

Fix a incorrectly named route

Fix a incorrectly named route


<?php

class SV_WordCountSearch_XenForo_DataWriter_DiscussionMessage_Post extends XFCP_SV_WordCountSearch_XenForo_DataWriter_DiscussionMessage_Post
{
    protected function _getFields()
    {
        $fields = parent::_getFields();
        $fields['xf_post_words'] = array
        (
            'post_id' => array('type' => self::TYPE_UINT,   'default' => array('xf_post', 'post_id'), 'required' => true),
            'word_count' => array('type' => self::TYPE_UINT, 'default' => 0)
        );
        return $fields;
    }

    protected function _messagePreSave()
    {
        parent::_messagePreSave();
        if ($this->isChanged('message'))
        {
            $this->set('word_count', $this->_getSearchModel()->getTextWordCount($this->get('message')));
        }
    }

    protected function _getSearchModel()
    {
        return $this->getModelFromCache('XenForo_Model_Search');
    }
}

<?php

class SV_WordCountSearch_XenForo_DataWriter_DiscussionMessage_Post extends XFCP_SV_WordCountSearch_XenForo_DataWriter_DiscussionMessage_Post
{
    protected function _getFields()
    {
        $fields = parent::_getFields();
        $fields['xf_post_words'] = array
        (
            'post_id' => array('type' => self::TYPE_UINT,   'default' => array('xf_post', 'post_id'), 'required' => true),
            'word_count' => array('type' => self::TYPE_UINT, 'default' => 0)
        );
        return $fields;
    }

    protected function _getExistingData($data)
    {
        $postData = parent::_getExistingData($data);
        if (isset($postData['xf_post']['word_count']))
        {
            $postData['xf_post_words'] = array('post_id' => $postData['xf_post']['post_id'], 'word_count' => $postData['xf_post']['word_count']);
            unset($postData['xf_post']['word_count']);
        }
        return $postData;
    }

    protected function _messagePostDelete()
    {
        parent::_messagePostDelete();
        $db = $this->_db;
        $post_id = $this->get('post_id');
        $postIdQuoted = $db->quote($post_id);

        $db->delete('xf_post_words', "post_id = $postIdQuoted");
    }

    protected function _messagePreSave()
    {
        parent::_messagePreSave();
        if ($this->isChanged('message'))
        {
            $this->set('word_count', $this->_getSearchModel()->getTextWordCount($this->get('message')));
        }
    }

    protected function _getSearchModel()
    {
        return $this->getModelFromCache('XenForo_Model_Search');
    }
}

Handle updates/deletes of linked tables correctly


<?php namespace Orchestra\Studio\Console;

class AuthControllerMakeCommand extends PublishCommand
{
    /**
     * Get actual namespace.
     *
     * @return string
     */
    protected function getNamespace()
    {
        return $this->laravel->getNamespace().'\Http\Controllers\Auth';
    }

    /**
     * Get publish files/paths.
     *
     * @return array
     */
    abstract protected function publishes()
    {
        $stub = __DIR__.'/../../stubs';

        return [
            "{$stub}/controllers/auth/authenticate.stub" => app_path('Http/Controllers/Auth/AuthenticateController.php'),
            "{$stub}/controllers/auth/deauthenticate.stub" => app_path('Http/Controllers/Auth/DeauthenticateController.php'),
            "{$stub}/controllers/auth/register.stub" => app_path('Http/Controllers/Auth/RegisterController.php'),

            "{$stub}/views/auth" => base_path('resources/views/auth'),
        ];
    }
}

<?php namespace Orchestra\Studio\Console;

class AuthControllerMakeCommand extends PublishCommand
{
    /**
     * Get actual namespace.
     *
     * @return string
     */
    protected function getNamespace()
    {
        return $this->laravel->getNamespace().'\Http\Controllers\Auth';
    }

    /**
     * Get publish files/paths.
     *
     * @return array
     */
    protected function publishes()
    {
        $stub = __DIR__.'/../../stubs';

        return [
            "{$stub}/controllers/auth/authenticate.stub" => app_path('Http/Controllers/Auth/AuthenticateController.php'),
            "{$stub}/controllers/auth/deauthenticate.stub" => app_path('Http/Controllers/Auth/DeauthenticateController.php'),
            "{$stub}/controllers/auth/register.stub" => app_path('Http/Controllers/Auth/RegisterController.php'),

            "{$stub}/views/auth" => base_path('resources/views/auth'),
        ];
    }
}

Remove abstract keyword on implementing method.

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


<?php
namespace Payum\AuthorizeNet\Aim\Action;

use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Convert;

class ConvertPaymentAction implements ActionInterface
{
    /**
     * {@inheritDoc}
     *
     * @param Convert $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();
        $divisor = pow(10, $payment->getCurrencyDigitsAfterDecimalPoint());

        $details = ArrayObject::ensureArrayObject($payment->getDetails());
        $details['amount'] = $payment->getTotalAmount() / $divisor;
        $details['invoice_num'] = $payment->getNumber();
        $details['description'] = $payment->getDescription();
        $details['email'] = $payment->getClientEmail();
        $details['cust_id'] = $payment->getClientId();

        $request->setResult((array) $details);
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof Convert &&
            $request->getSource() instanceof PaymentInterface &&
            $request->getTo() == 'array'
        ;
    }
}

<?php
namespace Payum\AuthorizeNet\Aim\Action;

use Payum\Core\Action\ActionInterface;
use Payum\Core\Action\GatewayAwareAction;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Convert;
use Payum\Core\Request\GetCurrency;

class ConvertPaymentAction extends GatewayAwareAction
{
    /**
     * {@inheritDoc}
     *
     * @param Convert $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();

        $this->gateway->execute($currency = new GetCurrency($payment->getCurrencyCode()));
        $divisor = pow(10, $currency->getIso4217()->getExp());

        $details = ArrayObject::ensureArrayObject($payment->getDetails());
        $details['amount'] = $payment->getTotalAmount() / $divisor;
        $details['invoice_num'] = $payment->getNumber();
        $details['description'] = $payment->getDescription();
        $details['email'] = $payment->getClientEmail();
        $details['cust_id'] = $payment->getClientId();

        $request->setResult((array) $details);
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof Convert &&
            $request->getSource() instanceof PaymentInterface &&
            $request->getTo() == 'array'
        ;
    }
}

[model] Add ability to get ISO4217 info. add a request and action for that. Simply payment interface.


<!DOCTYPE html>

        <title>EndofCodes Demo</title>
        <?php
            include 'helpers/html.php';
            includeStyle( "general" );
            includeStyle( "header" );
            includeStyle( "home" );
            includeStyle( "register" );
            includeStyle( "login" );
        ?>
        <meta charset="utf-8">

Endofcodes

Rules

                <?php
                    if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
                        ?>
<a href="index.php?resource=user&method=view&username=<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>">Profile
<?php
                    }
                ?>

Blog

                <?php
                    if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                        ?>
<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>
<?php
                    }
                    else {
                        ?>
Login
<?php
                    }
                ?>

<!DOCTYPE html>

        <title>EndofCodes Demo</title>
        <?php
            include 'helpers/html.php';
            includeStyle( "general" );
            includeStyle( "header" );
            includeStyle( "home" );
            includeStyle( "register" );
            includeStyle( "login" );
        ?>
        <meta charset="utf-8" />

Endofcodes

Rules

                <?php
                    if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
                        ?>
<a href="index.php?resource=user&method=view&username=<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>">Profile
<?php
                    }
                ?>

Blog

                <?php
                    if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                        ?>
<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>
<?php
                    }
                    else {
                        ?>
Login
<?php
                    }
                ?>

Add a forgoten close tag

Add a forgoten close tag


<?php
namespace Alt3\Swagger\Controller;

use Alt3\Swagger\Controller\AppController;
use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Network\Exception\NotFoundException;
use Cake\Routing\Router;

/**
 * UiController class responsible for serving the swagger-ui template page.
 *
 * @package Alt3\Swagger\Controller
 */
class UiController extends AppController
{

    /**
     * Index action used for setting template variables.
     *
     * @return void
     */
    public function index()
    {
        $this->set('config', static::$config['ui']);

        // make the first document autoload inside the UI
        $defaultDocument = key(static::$config['documents']);
        if (!$defaultDocument) {
            throw new \InvalidArgumentException("cakephp-swagger configuration file does not contain any documents");
        }

        $this->set('url', Router::url([
            'plugin' => 'Alt3/Swagger',
            'controller' => 'Docs',
            'action' => 'index',
            $defaultDocument
        ], true));
    }
}

<?php
namespace Alt3\Swagger\Controller;

use Alt3\Swagger\Controller\AppController;
use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Network\Exception\NotFoundException;
use Cake\Routing\Router;

/**
 * UiController class responsible for serving the swagger-ui template page.
 *
 * @package Alt3\Swagger\Controller
 */
class UiController extends AppController
{

    /**
     * Index action used for setting template variables.
     *
     * @return void
     */
    public function index()
    {
        $this->viewBuilder()->layout(false);

        $this->set('config', static::$config['ui']);

        // make the first document autoload inside the UI
        $defaultDocument = key(static::$config['documents']);
        if (!$defaultDocument) {
            throw new \InvalidArgumentException("cakephp-swagger configuration file does not contain any documents");
        }

        $this->set('url', Router::url([
            'plugin' => 'Alt3/Swagger',
            'controller' => 'Docs',
            'action' => 'index',
            $defaultDocument
        ], true));
    }
}

Disable Cake layout to prevent mangling swagger DOM


<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class WidgetServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('orchestra.widget', function ($app) {
            return new WidgetManager($app);
        });

        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('Orchestra\Widget', 'Orchestra\Support\Facades\Widget');
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $path = realpath(__DIR__.'/../../');

        $this->package('orchestra/widget', 'orchestra/widget', $path);
    }

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

<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class WidgetServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('orchestra.widget', function ($app) {
            return new WidgetManager($app);
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $path = realpath(__DIR__.'/../../');

        $this->package('orchestra/widget', 'orchestra/widget', $path);
    }

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

Remove alias from service provider.

Remove alias from service provider.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
/**
 * Dash
 *
 * @link      http://github.com/DASPRiD/Dash For the canonical source repository
 * @copyright 2013-2015 Ben Scholzen 'DASPRiD'
 * @license   http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
 */

namespace Dash;

/**
 * Config provider for the dependency config.
 */
class ConfigProvider
{
    public function __invoke()
    {
        return require __DIR__ . '/../config/dependencies.config.php';
    }
}

<?php
/**
 * Dash
 *
 * @link      http://github.com/DASPRiD/Dash For the canonical source repository
 * @copyright 2013-2015 Ben Scholzen 'DASPRiD'
 * @license   http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
 */

namespace Dash;

/**
 * Config provider for the dependency config.
 */
class ConfigProvider
{
    /**
     * @return array
     */
    public function __invoke()
    {
        return require __DIR__ . '/../config/dependencies.config.php';
    }
}

Add missing return type hint

Add missing return type hint


You have reached Kyle's website.

Enjoy one of my favorite TED talks

        <?php include_once "$docRoot/include/footer.php"; ?>

Use different TED talk - don't load insecure images.


<?php

namespace Rogue\Console\Commands;

use Illuminate\Console\Command;
use Rogue\Models\Post;

class DeletePosts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rogue:deleteposts
                            {ids* : A space-separated list of post ids to delete}
                            {--force : Whether or not to force delete these posts instead of soft delete (default)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete posts in Rogue by post id with an option to force delete';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ids = $this->argument('ids');

        $posts = Post::whereIn('id', $ids);

        if ($this->option('force')) {
            $posts->forceDelete();
        } else {
            $posts->delete();
        }

        $this->info('Posts Deleted!');
    }
}

<?php

namespace Rogue\Console\Commands;

use Rogue\Models\Post;
use Illuminate\Console\Command;
use Rogue\Managers\PostManager;

class DeletePosts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rogue:deleteposts
                            {ids* : A space-separated list of post ids to delete}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete posts in Rogue by post id with an option to force delete';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(PostManager $postManager)
    {
        // Post Manager Instance.
        $this->postManager = $postManager;

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ids = $this->argument('ids');

        $posts = Post::whereIn('id', $ids)->get();

        $posts->map(function($post, $key) {
            $this->postManager->destroy($post->id);
        });

        $this->info('Posts Deleted!');
    }
}

Delete posts through the posts manager so other services get the update


<?php

namespace Ivory\GoogleMapBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories
     *
     * @param string $environment
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);
            $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.'/'.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

<?php

namespace Ivory\GoogleMapBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories for the given environment
     *
     * @param string $environment
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);

            if(empty(self::$initialize))
                $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.'/'.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

Remove Emulation logs directory one time at the beggining of the test suite


  public function executeExport(sfWebRequest $request)
  {
    $this->doExport(array(
      'format' => $request->getParameter('format', 'csv'),
      'extension' => $request->getParameter('extension', 'csv'),
      'encoding' => $request->getParameter('encoding', 'utf-8'),
      'exportClass' => '<?php echo $this->getModuleName() ?>Export',
      'module' => $this->getDmModule()
    ));
  }

  public function executeExport(sfWebRequest $request)
  {
    $this->doExport(array(
      'format' => $request->getParameter('format', 'csv'),
      'extension' => $request->getParameter('extension', 'csv'),
      'encoding' => $request->getParameter('encoding', 'utf-8'),
      'exportClass' => '<?php echo $this->getModule()->getModel() ?>Export',
      'module' => $this->getDmModule()
    ));
  }

Fix export class name in generatedd admin modules


<?php

namespace EGALL\Transformer\Relationships;

use EGALL\Transformer\Relationship;

/**
 * ModelToCollectionRelationship Class
 *
 * @package EGALL\Transformer\Relationships
 * @author Erik Galloway <erik@mybarnapp.com>
 */
class ModelToCollectionRelationship extends Relationship
{

    /**
     * Transform a model to collection relationship.
     *
     * @return array
     */
    public function transform()
    {
        $model = $this->item->{$this->key};

        if ($this->isTransformable($model->first())) {

            return $this->transformCollection($model);

        }

        return $this->collectionToArray($model);
    }

    /**
     * Map a collection calling toArray() on each item.
     *
     * @param $model
     * @return array
     */
    protected function collectionToArray($model)
    {

        return $model->map(function($item) {

            return $item->toArray();

        })->toArray();

    }

    /**
     * Transform a transformable collection.
     *
     * @param $model
     * @return array
     */
    protected function transformCollection($model)
    {

        return $model->map(function($child) {

            if ($this->child) {

                return $child->transformer(true)->with($this->child)->transform();

            }

            return $child->transform();

        })->toArray();

    }
}

<?php

namespace EGALL\Transformer\Relationships;

use EGALL\Transformer\Relationship;

/**
 * ModelToCollectionRelationship Class
 *
 * @package EGALL\Transformer\Relationships
 * @author Erik Galloway <erik@mybarnapp.com>
 */
class ModelToCollectionRelationship extends Relationship
{

    /**
     * Transform a model to collection relationship.
     *
     * @return array
     */
    public function transform()
    {
        $model = $this->item->{$this->key};

        if (!$model->isEmpty() && $this->isTransformable($model->first())) {

            return $this->transformCollection($model);

        }

        return $this->collectionToArray($model);
    }

    /**
     * Map a collection calling toArray() on each item.
     *
     * @param $model
     * @return array
     */
    protected function collectionToArray($model)
    {

        return $model->map(function($item) {

            return $item->toArray();

        })->toArray();

    }

    /**
     * Transform a transformable collection.
     *
     * @param $model
     * @return array
     */
    protected function transformCollection($model)
    {

        return $model->map(function($child) {

            if ($this->child) {

                return $child->transformer(true)->with($this->child)->transform();

            }

            return $child->transform();

        })->toArray();

    }
}

Check if the model is empty first in collection relationship


<?php

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

namespace Symfony\Bridge\Monolog\Handler;

use Monolog\Logger;
use Monolog\Handler\TestHandler;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

/**
 * DebugLogger.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class DebugHandler extends TestHandler implements DebugLoggerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getLogs()
    {
        $records = array();
        foreach ($this->records as $record) {
            $records[] = array(
                'timestamp'    => $record['datetime']->getTimestamp(),
                'message'      => $record['message'],
                'priority'     => $record['level'],
                'priorityName' => $record['level_name'],
                'context'      => $record['context'],
            );
        }

        return $records;
    }

    /**
     * {@inheritdoc}
     */
    public function countErrors()
    {
        $cnt = 0;
        foreach (array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT) as $level) {
            if (isset($this->recordsByLevel[$level])) {
                $cnt += count($this->recordsByLevel[$level]);
            }
        }

        return $cnt;
    }
}

<?php

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

namespace Symfony\Bridge\Monolog\Handler;

use Monolog\Logger;
use Monolog\Handler\TestHandler;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

/**
 * DebugLogger.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class DebugHandler extends TestHandler implements DebugLoggerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getLogs()
    {
        $records = array();
        foreach ($this->records as $record) {
            $records[] = array(
                'timestamp'    => $record['datetime']->getTimestamp(),
                'message'      => $record['message'],
                'priority'     => $record['level'],
                'priorityName' => $record['level_name'],
                'context'      => $record['context'],
            );
        }

        return $records;
    }

    /**
     * {@inheritdoc}
     */
    public function countErrors()
    {
        $cnt = 0;
        $levels = array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT);
        if (defined('Monolog\Logger::EMERGENCY')) {
            $levels[] = Logger::EMERGENCY;
        }
        foreach ($levels as $level) {
            if (isset($this->recordsByLevel[$level])) {
                $cnt += count($this->recordsByLevel[$level]);
            }
        }

        return $cnt;
    }
}

Add support for Monolog 1.2.0

Add support for Monolog 1.2.0


<?php

namespace App\Listeners\VisitTransfer;

use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\VisitTransfer\ApplicationAccepted;

class NotifyTrainingDepartmentOfAcceptedApplication implements ShouldQueue
{
    public function __construct()
    {
        //
    }

    public function handle(ApplicationAccepted $event)
    {
        $application = $event->application;
        $application->facility->notify(new ApplicationAccepted($application));
    }
}

<?php

namespace App\Listeners\VisitTransfer;

use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\VisitTransfer\ApplicationAccepted;

class NotifyTrainingDepartmentOfAcceptedApplication implements ShouldQueue
{
    public function __construct()
    {
        //
    }

    public function handle(ApplicationAccepted $event)
    {
        $application = $event->application;
        $application->facility->notify(new \App\Notifications\ApplicationAccepted($application));
    }
}

Fix accepted application notification reference


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

/**
 * Provides default implementations of `INullableFormField` methods.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	3.2
 */
trait TNullableFormField {
	/**
	 * `true` if this field supports `null` as its value and `false` otherwise
	 * @var	bool
	 */
	protected $__nullable = false;

	/**
	 * Returns `true` if this field supports `null` as its value and returns `false`
	 * otherwise.
	 *
	 * Per default, fields do not support `null` as their value.
	 *
	 * @return	bool
	 */
	public function isNullable() {
		return $this->__nullable;
	}

	/**
	 * Sets whether this field supports `null` as its value and returns this field.
	 *
	 * @param	bool	$nullable		determines if field supports `null` as its value
	 * @return	static				this node
	 *
	 * @throws	\InvalidArgumentException	if the given value is no boolean
	 */
	public function nullable($nullable = true) {
		if (!is_bool($nullable)) {
			throw new \InvalidArgumentException("Given value is no bool, " . gettype($nullable) . " given.");
		}

		$this->__nullable = $nullable;

		return $this;
	}
}

Add missing newline at end of file

Add missing newline at end of file

See #2509


<?php

    return [
        'driver'=>'mysqli',
        'host'=>'localhost',
        'user'=>'root',
        'password'=>'',
        'database'=>'mangadb'
    ];

?>

<?php

    return [
        'driver'=>'mysqli',
        'host'=>'localhost',
        'user'=>'root',
        'password'=>'',
        'database'=>'mediadb'
    ];

?>

Change back database name to mediadb

Change back database name to mediadb


<?php if (isset($message)): ?>

					<?php foreach ($message[0] as $key => $value): ?>
						<?php echo $key ?>
					<?php endforeach ?>

				<?php foreach ($message as $users): ?>

						<?php foreach ($users as $user): ?>
							<?php echo $user ?>
						<?php endforeach ?>

				<?php endforeach ?>

<?php endif ?>

<?php if (isset($message)): ?>

					<?php foreach ($message[0] as $key => $value): ?>
						<?php echo $key ?>
					<?php endforeach ?>

				<?php foreach ($message as $users): ?>

						<?php foreach ($users as $cell): ?>
							<?php echo $cell ?>
						<?php endforeach ?>

				<?php endforeach ?>

<?php endif ?>

Update styling to accommodate for newly implemented columns


<?php

use Illuminate\Database\Migrations\Migration,
	Illuminate\Support\Facades\Event;

class OrchestraAuthCreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function($table)
		{
			$table->increments('id');

			$table->string('email', 100);
			$table->string('password', 60);

			Event::fire('orchestra.installer.schema: users', array($table));

			$table->string('fullname', 100)->nullable();
			$table->integer('status')->nullable();

			$table->timestamps();
			$table->softDeletes();

			$table->unique('email');
		});
	}

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

}

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Event;

class OrchestraAuthCreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function($table)
		{
			$table->increments('id');

			$table->string('email', 100);
			$table->string('password', 60);

			Event::fire('orchestra.install.schema: users', array($table));

			$table->string('fullname', 100)->nullable();
			$table->integer('status')->nullable();

			$table->timestamps();
			$table->softDeletes();

			$table->unique('email');
		});
	}

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

Tweak event fire to be consistent with v1.

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


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

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

	public function user_check()
	{
		$email = $_REQUEST['email'];
		$password = $_REQUEST['password'];

		$this->load->model('login_model');
		$r = $this->login_model->user_check_api($email,$password);
		$data['result'] = $r;

		$this->load->view('view_apiraw', $data);
	}

	public function get_hosts()
	{
		$this->load->model('api_model');
		$data['result'] = $this->api_model->get_hosts();
		$this->load->view('view_api', $data);
	}

	public function get_sites()
	{
		$this->load->model('api_model');
		$data['result'] = $this->api_model->get_sites();
		$this->load->view('view_api', $data);
	}

}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

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

	public function api_check()
	{
		$data['result'] = array('a' => 1);
		$this->load->view('view_apiraw', $data);
	}

	public function user_check()
	{
		$email = $_REQUEST['email'];
		$password = $_REQUEST['password'];

		$this->load->model('login_model');
		$r = $this->login_model->user_check_api($email,$password);
		$data['result'] = $r;

		$this->load->view('view_apiraw', $data);
	}

	public function get_hosts()
	{
		$this->load->model('api_model');
		$data['result'] = $this->api_model->get_hosts();
		$this->load->view('view_api', $data);
	}

	public function get_sites()
	{
		$this->load->model('api_model');
		$data['result'] = $this->api_model->get_sites();
		$this->load->view('view_api', $data);
	}

}

Change to API to include a validation check for Mobile App


<?php

namespace OpenConext\EngineBlockBundle\Authentication\Repository;

use Doctrine\ORM\EntityRepository;
use OpenConext\EngineBlock\Authentication\Value\CollabPersonId;
use OpenConext\EngineBlockBundle\Authentication\Entity\User;

/**
 *
 */
class UserRepository extends EntityRepository
{
    /**
     * @param User $user
     */
    public function save(User $user)
    {
        $this->getEntityManager()->persist($user);
        $this->getEntityManager()->flush();
    }

    /**
     * @param CollabPersonId $collabPersonId
     * @return null|User
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findByCollabPersonId(CollabPersonId $collabPersonId)
    {
        return $this
            ->createQueryBuilder('u')
            ->where('u.collabPersonId = :collabPersonId')
            ->setParameter('collabPersonId', $collabPersonId)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @param CollabPersonId $collabPersonId
     */
    public function deleteUserWithCollabPersonId(CollabPersonId $collabPersonId)
    {
        $queryBuilder = $this->getEntityManager()->createQueryBuilder();

        $queryBuilder
            ->delete($this->_entityName, 'u')
            ->where('u.collabPersonId = :collabPersonId')
            ->setParameter('collabPersonId', $collabPersonId)
            ->getQuery()
            ->execute();

        $this->getEntityManager()->flush();
    }
}

<?php

namespace OpenConext\EngineBlockBundle\Authentication\Repository;

use Doctrine\ORM\EntityRepository;
use OpenConext\EngineBlock\Authentication\Value\CollabPersonId;
use OpenConext\EngineBlockBundle\Authentication\Entity\User;

/**
 *
 */
class UserRepository extends EntityRepository
{
    /**
     * @param User $user
     */
    public function save(User $user)
    {
        $this->getEntityManager()->persist($user);
        $this->getEntityManager()->flush();
    }

    /**
     * @param CollabPersonId $collabPersonId
     * @return null|User
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findByCollabPersonId(CollabPersonId $collabPersonId)
    {
        return $this
            ->createQueryBuilder('u')
            ->where('u.collabPersonId = :collabPersonId')
            ->setParameter('collabPersonId', $collabPersonId->getCollabPersonId())
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @param CollabPersonId $collabPersonId
     */
    public function deleteUserWithCollabPersonId(CollabPersonId $collabPersonId)
    {
        $queryBuilder = $this->getEntityManager()->createQueryBuilder();

        $queryBuilder
            ->delete($this->_entityName, 'u')
            ->where('u.collabPersonId = :collabPersonId')
            ->setParameter('collabPersonId', $collabPersonId->getCollabPersonId())
            ->getQuery()
            ->execute();

        $this->getEntityManager()->flush();
    }
}

Use actual value in queries rather than object-cast-to-string


<?php

chdir(__DIR__);

$placeholders = null;
$placeholderPattern = '/\%\%([A-Z_]+)\%\%/i';
$config = file_get_contents('../wp-config.php');

preg_match_all($placeholderPattern, $config, $placeholders);

foreach ($placeholders[1] as $placeholder) {
  $env = getenv($placeholder);

  if ($env !== FALSE) {
    $config = str_replace(
      '%%' . $placeholder . '%%',
      $env,
      $config
    );
  }
}

file_put_contents('../wp-config.php', $config);

<?php

chdir(__DIR__);

$placeholders = null;
$placeholderPattern = '/\%\%([A-Z_]+)\%\%/i';
$config = file_get_contents('../wp-config.php');

// ClearDB MySQL custom handling
$clearDb = getenv('CLEARDB_DATABASE_URL');

if ($clearDb !== false) {
    $clearDb = strstr(substr($clearDb, strpos($clearDb, '://') + 3), '?', true);

    list($userAndPass, $hostAndDb) = explode('@', $clearDb);
    list($user, $pass) = explode(':', $userAndPass);
    list($host, $db) = explode('/', $hostAndDb);

    $config = str_replace('%%DB_USER%%', $user, $config);
    $config = str_replace('%%DB_PASSWORD%%', $pass, $config);
    $config = str_replace('%%DB_HOST%%', $host, $config);
    $config = str_replace('%%DB_NAME%%', $db, $config);
}

// Write basic config variables
preg_match_all($placeholderPattern, $config, $placeholders);

foreach ($placeholders[1] as $placeholder) {
  $env = getenv($placeholder);

  if ($env !== FALSE) {
    $config = str_replace(
      '%%' . $placeholder . '%%',
      $env,
      $config
    );
  }
}

// Write new config file
file_put_contents('../wp-config.php', $config);

Handle ClearDB specially when re-writing configuration


<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

use Doctrine\Common\Annotations\AnnotationRegistry;

include '../src/Go/Core/AspectKernel.php';
include 'DemoAspectKernel.php';

// Initialize demo aspect container
DemoAspectKernel::getInstance()->init(array(
    // Configuration for autoload namespaces
    'autoload' => array(
        'Go'               => realpath(__DIR__ . '/../src'),
        'TokenReflection'  => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'),
        'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/')
    ),
    // Default application directory
    'appDir' => __DIR__ . '/../demos',
    // Cache directory for Go! generated classes
    'cacheDir' => __DIR__ . '/cache',
    // Include paths for aspect weaving
    'includePaths' => array(),
    'debug' => true
));

AnnotationRegistry::registerFile('./Annotation/Cacheable.php');

<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

use Doctrine\Common\Annotations\AnnotationRegistry;

include '../src/Go/Core/AspectKernel.php';
include 'DemoAspectKernel.php';

// Initialize demo aspect container
DemoAspectKernel::getInstance()->init(array(
    // Configuration for autoload namespaces
    'autoload' => array(
        'Go'               => realpath(__DIR__ . '/../src'),
        'TokenReflection'  => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'),
        'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/'),
        'Dissect'          => realpath(__DIR__ . '/../vendor/jakubledl/dissect/src/'),
    ),
    // Default application directory
    'appDir' => __DIR__ . '/../demos',
    // Cache directory for Go! generated classes
    'cacheDir' => __DIR__ . '/cache',
    // Include paths for aspect weaving
    'includePaths' => array(),
    'debug' => true
));

AnnotationRegistry::registerFile('./Annotation/Cacheable.php');

Fix mised autoload dependency for dissect


<?php
/**
 * PunyApp:
 *   The puny developer framework for rapid compiling.
 */

class SampleModel extends PunyApp_Model {

  public function addUser($user_id, $email, $pass) {
    if ($this->isUserId($user_id)) {
      return false;
    }

    return $this->insert(array(
      'userId' => ':userId',
      'email' => ':email',
      'pass' => ':pass',
      'updateAt' => ':updateAt'
    ), array(
      ':userId' => $user_id,
      ':email' => $email,
      ':pass' => sha1($pass),
      ':updateAt' => PunyApp::now()
    ));
  }

  public function deleteUser($user_id) {
    return $this->delete(array('userId' => '?'), array($user_id));
  }

  public function getUser($user_id) {
    return $this->findOne(
      array('id', 'userId', 'email'),
      array('userId' => '?'),
      array($user_id)
    );
  }

  public function isUserId($user_id) {
    return $this->count(array('userId' => '?'), array($user_id)) > 0;
  }

  public function isUser($user_id, $pass) {
    return $this->count(array(
      'userId' => ':userId',
      'pass' => ':pass'
    ), array(
      ':userId' => $user_id,
      ':pass' => sha1($pass)
    )) > 0;
  }
}

<?php
/**
 * PunyApp:
 *   The puny developer framework for rapid compiling.
 */

class SampleModel extends PunyApp_Model {

  public function addUser($userid, $email, $pass) {
    if ($this->isUserId($userid)) {
      return false;
    }

    $sample = $this->newInstance();
    $sample->userid = $userid;
    $sample->email = $email;
    $sample->pass = sha1($pass);
    $sample->save();
  }

  public function deleteUser($userid) {
    return $this->delete(
      array('userid' => '?'),
      array($userid)
    );
  }

  public function getUser($userid) {
    return $this->findOne(
      array(
        'fields' => array('id', 'userid', 'email'),
        'where' => array('userid' => '?')
      ),
      array($userid)
    );
  }

  public function isUserId($userid) {
    return $this->has(
      array(
        'where' => array('userid' => '?')
      ),
      array($userid)
    );
  }

  public function hasUser($userid, $pass) {
    return $this->has(
      array(
        'where' => array(
          'userid' => ':userid',
          'pass' => ':pass'
        )
      ),
      array(
        ':userid' => $userid,
        ':pass' => sha1($pass)
      )
    );
  }
}

Add Model::newInstance() and create() methods example.