<?php
require_once 'propel/runtime/lib/Propel.php';

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library')
)));

/*set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library/propel/runtime/lib')
)));*/

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

CC-5781: Upgrade script for new storage quota implementation

add propel to include path


<?php

class Algolia_Algoliasearch_Model_Resource_Fulltext_Collection extends Mage_CatalogSearch_Model_Resource_Fulltext_Collection
{

    /**
     * Add search query filter without preparing result since result table causes lots of lock contention.
     *
     * @param string $query
     * @throws Exception
     * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
     */
    public function addSearchFilter($query)
    {
        if ( ! Mage::helper('algoliasearch')->isEnabled() || Mage::helper('algoliasearch')->useResultCache()) {
            return parent::addSearchFilter($query);
        }

        // This method of filtering the product collection by the search result does not use the catalogsearch_result table
        try {
            $data = Mage::helper('algoliasearch')->getSearchResult($query, Mage::app()->getStore()->getId());
        } catch (Exception $e) {
            Mage::getSingleton('catalog/session')->addError(Mage::helper('algoliasearch')->__('Search failed. Please try again.'));
            $this->getSelect()->columns(['relevance' => new Zend_Db_Expr("e.entity_id")]);
            $this->getSelect()->where('e.entity_id = 0');
            return $this;
        }

        $sortedIds = array_reverse(array_keys($data));
        $this->getSelect()->columns(['relevance' => new Zend_Db_Expr("FIND_IN_SET(e.entity_id, '".implode(',',$sortedIds)."')")]);
        $this->getSelect()->where('e.entity_id IN (?)', $sortedIds);

        return $this;
    }

}

<?php

class Algolia_Algoliasearch_Model_Resource_Fulltext_Collection extends Mage_CatalogSearch_Model_Resource_Fulltext_Collection
{

    /**
     * Add search query filter without preparing result since result table causes lots of lock contention.
     *
     * @param string $query
     * @throws Exception
     * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
     */
    public function addSearchFilter($query)
    {
        if ( ! Mage::helper('algoliasearch')->isEnabled() || Mage::helper('algoliasearch')->useResultCache()) {
            return parent::addSearchFilter($query);
        }

        // This method of filtering the product collection by the search result does not use the catalogsearch_result table
        try {
            $data = Mage::helper('algoliasearch')->getSearchResult($query, Mage::app()->getStore()->getId());
        } catch (Exception $e) {
            Mage::getSingleton('catalog/session')->addError(Mage::helper('algoliasearch')->__('Search failed. Please try again.'));
            $this->getSelect()->columns(array('relevance' => new Zend_Db_Expr("e.entity_id")));
            $this->getSelect()->where('e.entity_id = 0');
            return $this;
        }

        $sortedIds = array_reverse(array_keys($data));
        $this->getSelect()->columns(array('relevance' => new Zend_Db_Expr("FIND_IN_SET(e.entity_id, '".implode(',',$sortedIds)."')")));
        $this->getSelect()->where('e.entity_id IN (?)', $sortedIds);

        return $this;
    }

}

Make code compatible with PHP <5.4 by removing short array syntax


<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;

class WidgetServiceProvider extends ServiceProvider {
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['orchestra.widget'] = $this->app->share(function($app)
		{
			return new WidgetManager($app);
		});
	}

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

<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;

class WidgetServiceProvider extends ServiceProvider {

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

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

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

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

Add provides since this service is deferred.


<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    /** @var array */
    protected $attributes = array('class' => 'pfbc-textarea');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    /** @var array */
    protected $attributes = array('class' => 'pfbc-textarea');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = !empty($this->attributes['value']) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : 0;

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

Remove unnecessary parentheses + change value to integer


<?php

namespace Doctrine\Tests\Common\Annotations;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\Cache\InMemoryCache;
use Doctrine\Common\Annotations\CachedReader;

class CachedReaderTest extends AbstractReaderTest
{
    protected function getReader()
    {
        return new CachedReader(new AnnotationReader(), new InMemoryCache());
    }
}

<?php

namespace Doctrine\Tests\Common\Annotations;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Cache\ArrayCache;

class CachedReaderTest extends AbstractReaderTest
{
    private $cache;

    protected function getReader()
    {
        $this->cache = new ArrayCache();
        return new CachedReader(new AnnotationReader(), $this->cache);
    }
}

Refactor Annotations to remove unnecessary caching layer, add FileCacheReader and modified CachedReader not to have a local map of annotations anymore


<?php namespace CodeZero\Encrypter;

use Illuminate\Contracts\Encryption\DecryptException as IlluminateDecryptException;
use Illuminate\Contracts\Encryption\Encrypter as IlluminateEncrypter;
use Illuminate\Encryption\Encrypter as DefaultIlluminateEncrypter;

class DefaultEncrypter implements Encrypter
{
    /**
     * Laravel's Encrypter
     *
     * @var IlluminateEncrypter
     */
    private $encrypter;

    /**
     * Create a new instance of LaravelEncrypter
     *
     * @param string $key
     * @param IlluminateEncrypter $encrypter
     */
    public function __construct($key, IlluminateEncrypter $encrypter = null)
    {
        $this->encrypter = $encrypter ?: new DefaultIlluminateEncrypter(md5($key));
    }

    /**
     * Encrypt a string
     *
     * @param string $string
     *
     * @return string
     */
    public function encrypt($string)
    {
        return $this->encrypter->encrypt($string);
    }

    /**
     * Decrypt an encrypted string
     *
     * @param string $payload
     *
     * @return string
     * @throws DecryptException
     */
    public function decrypt($payload)
    {
        try {
            $decrypted = $this->encrypter->decrypt($payload);
        } catch (IlluminateDecryptException $exception) {
            throw new DecryptException('Decryption failed.', 0, $exception);
        }

        return $decrypted;
    }
}

<?php namespace CodeZero\Encrypter;

use Illuminate\Contracts\Encryption\DecryptException as IlluminateDecryptException;
use Illuminate\Contracts\Encryption\Encrypter as IlluminateEncrypter;
use Illuminate\Encryption\Encrypter as DefaultIlluminateEncrypter;

class DefaultEncrypter implements Encrypter
{
    /**
     * Laravel's Encrypter
     *
     * @var IlluminateEncrypter
     */
    private $encrypter;

    /**
     * Create a new instance of LaravelEncrypter
     *
     * @param string $key
     * @param IlluminateEncrypter $encrypter
     */
    public function __construct($key, IlluminateEncrypter $encrypter = null)
    {
        $this->encrypter = $encrypter ?: new DefaultIlluminateEncrypter(md5($key), 'AES-256-CBC');
    }

    /**
     * Encrypt a string
     *
     * @param string $string
     *
     * @return string
     */
    public function encrypt($string)
    {
        return $this->encrypter->encrypt($string);
    }

    /**
     * Decrypt an encrypted string
     *
     * @param string $payload
     *
     * @return string
     * @throws DecryptException
     */
    public function decrypt($payload)
    {
        try {
            $decrypted = $this->encrypter->decrypt($payload);
        } catch (IlluminateDecryptException $exception) {
            throw new DecryptException('Decryption failed.', 0, $exception);
        }

        return $decrypted;
    }
}

Set default 32 bit cipher

Set default 32 bit cipher


<?php

if (file_exists($file = __DIR__.'/../vendor/.composer/autoload.php')) {
    $loader = require_once $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

spl_autoload_register(function($class) {
    if (0 === strpos($class, 'Jmikola\\WildcardEventDispatcherBundle\\')) {
        $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 2)).'.php';
        if (!stream_resolve_include_path($path)) {
            return false;
        }
        require_once $path;
        return true;
    }
});

<?php

if (file_exists($file = __DIR__.'/../vendor/autoload.php')) {
    $loader = require_once $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

spl_autoload_register(function($class) {
    if (0 === strpos($class, 'Jmikola\\WildcardEventDispatcherBundle\\')) {
        $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 2)).'.php';
        if (!stream_resolve_include_path($path)) {
            return false;
        }
        require_once $path;
        return true;
    }
});

Use new Composer autoload file

Use new Composer autoload file


<?php

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

class CreateImagesTable extends Migration {

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

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

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

}

<?php

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

class CreateImagesTable extends Migration {

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

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

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

}

Break name and path into separate fields


<?php

namespace Hub\Client\Model;

class Resource
{

    protected $type;
    protected $shares = array();

    public function getType()
    {
        return $this->type;
    }

    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    private $properties = array();

    public function addProperty(Property $property)
    {
        $this->properties[$property->getName()] = $property;
        return $this;
    }

    public function hasProperty($name)
    {
        return isset($this->properties[$name]);
    }

    public function getProperty($name)
    {
        return $this->properties[$name];
    }

    public function getPropertyValue($name)
    {
        return $this->getProperty($name)->getValue();
    }

    public function addPropertyValue($name, $value)
    {
        $name = (string)$name;
        $value = (string)$value;
        $property = new Property($name, $value);
        $this->addProperty($property);
        return $this;
    }

    public function addShare(Share $share)
    {
        $this->shares[] = $share;
        return $this;
    }

    public function getShares()
    {
        return $this->shares;
    }
}

<?php

namespace Hub\Client\Model;

class Resource
{

    protected $type;
    protected $shares = array();

    public function getType()
    {
        return $this->type;
    }

    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    private $properties = array();

    public function addProperty(Property $property)
    {
        $this->properties[$property->getName()] = $property;
        return $this;
    }

    public function hasProperty($name)
    {
        return isset($this->properties[$name]);
    }

    public function getProperty($name)
    {
        return $this->properties[$name];
    }

    public function getPropertyValue($name)
    {
        return $this->getProperty($name)->getValue();
    }

    public function addPropertyValue($name, $value)
    {
        $name = (string)$name;
        $value = (string)$value;
        $property = new Property($name, $value);
        $this->addProperty($property);
        return $this;
    }

    public function addShare(Share $share)
    {
        $this->shares[] = $share;
        return $this;
    }

    public function getShares()
    {
        return $this->shares;
    }

    private $sourceUrl;

    public function getSourceUrl()
    {
        return $this->sourceUrl;
    }

    public function setSourceUrl($sourceUrl)
    {
        $this->sourceUrl = $sourceUrl;
        return $this;
    }

    private $sourceJwt;

    public function getSourceJwt()
    {
        return $this->sourceJwt;
    }

    public function setSourceJwt($sourceJwt)
    {
        $this->sourceJwt = $sourceJwt;
        return $this;
    }
}

Add source elements url + jwt to resource model


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * AdminCandidacyRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AdminCandidacyRepository extends EntityRepository
{
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\NoResultException;

/**
 * AdminCandidacyRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AdminCandidacyRepository extends EntityRepository implements UserProviderInterface
{
	public function loadUserByUsername($username)
	{
		$q = $this
		->createQueryBuilder('u')
		->where('u.username = :username')
		->setParameter('username', $username)
		->getQuery();

		try
		{
			// The Query::getSingleResult() method throws an exception
			// if there is no record matching the criteria.
			$user = $q->getSingleResult();
		}
		catch (NoResultException $e)
		{
			$message = sprintf(
					'Unable to find an active admin MunicipalesBundle:AdminCandidacy object identified by "%s".',
					$username
			);
			throw new UsernameNotFoundException($message, 0, $e);
		}

		return $user;
	}

	/**
	 * {@inheritdoc}
	 */
	protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
	{
		$currentUser = $token->getUser();

		if ($currentUser instanceof UserInterface) {
			if ($currentUser->getPassword() !== $user->getPassword()) {
				throw new BadCredentialsException('The credentials were changed from another session.');
			}
		} else {
			if (!$presentedPassword = $token->getCredentials()) {
				throw new BadCredentialsException('The presented password cannot be empty.');
			}

			if (! $this->service->authenticate($token->getUser(), $presentedPassword)) {
				throw new BadCredentialsException('The presented password is invalid.');
			}
		}
	}

	public function refreshUser(UserInterface $user)
	{
		$class = get_class($user);
		if (!$this->supportsClass($class)) {
			throw new UnsupportedUserException(
					sprintf(
							'Instances of "%s" are not supported.',
							$class
					)
			);
		}

		return $this->find($user->getId());
	}

	public function supportsClass($class)
	{
		return $this->getEntityName() === $class
		|| is_subclass_of($class, $this->getEntityName());
	}
}

Implement authentication for admin candidacy repository


Use of env method instead of the getenv method


<?php
namespace Vanio\DomainBundle\Model;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileToUpload extends UploadedFile
{
    /** @var bool */
    private $temporary = false;

    public function __construct(string $path, string $originalName = null, string $mimeType = null, int $size = null)
    {
        parent::__construct($path, $originalName ?? self::resolveOriginalName($path), $mimeType, $size, null, true);
    }

    public static function temporary(
        string $path,
        string $originalName = null,
        string $mimeType = null,
        int $size = null
    ): self {
        $filesystem = new Filesystem;
        $target = tempnam(sys_get_temp_dir(), '');
        $filesystem->copy($path, $target, true);
        $self = new self($target, $originalName, $mimeType, $size);
        $self->temporary = true;

        return $self;
    }

    public function move($directory, $name = null): SymfonyFile
    {
        if ($this->temporary) {
            return parent::move($directory, $name);
        }

        $target = $this->getTargetFile($directory, $name);
        $filesystem = new Filesystem;
        $filesystem->copy($this->getPathname(), $target);

        return $target;
    }

    private static function resolveOriginalName(string $path): string
    {
        return basename(preg_replace('~\?.*$~', '', $path));
    }
}

<?php
namespace Vanio\DomainBundle\Model;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileToUpload extends UploadedFile
{
    /** @var bool */
    private $temporary = false;

    public function __construct(string $path, string $originalName = null, string $mimeType = null)
    {
        parent::__construct($path, $originalName ?? self::resolveOriginalName($path), $mimeType, null, true);
    }

    public static function temporary(
        string $path,
        string $originalName = null,
        string $mimeType = null
    ): self {
        $filesystem = new Filesystem;
        $target = tempnam(sys_get_temp_dir(), '');
        $filesystem->copy($path, $target, true);
        $self = new self($target, $originalName, $mimeType);
        $self->temporary = true;

        return $self;
    }

    public function move($directory, $name = null): SymfonyFile
    {
        if ($this->temporary) {
            return parent::move($directory, $name);
        }

        $target = $this->getTargetFile($directory, $name);
        $filesystem = new Filesystem;
        $filesystem->copy($this->getPathname(), $target);

        return $target;
    }

    private static function resolveOriginalName(string $path): string
    {
        return basename(preg_replace('~\?.*$~', '', $path));
    }
}

Remove deprecated parameter size in UploadedFile constructor call.


@extends('layout.master')

@section('title',  trans('cachet.subscriber.subscribe'). " | ". $siteTitle))

@section('description', trans('cachet.meta.description.subscribe', ['app' => $siteTitle]))

@section('content')

@include('partials.errors')

{{ trans('cachet.subscriber.subscribe') }}

                <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <input class="form-control" type="email" name="email" placeholder="email@example.com">

                    <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
                </form>

@stop

@extends('layout.master')

@section('title',  trans('cachet.subscriber.subscribe'). " | ". $siteTitle)

@section('description', trans('cachet.meta.description.subscribe', ['app' => $siteTitle]))

@section('content')

@include('partials.errors')

{{ trans('cachet.subscriber.subscribe') }}

                <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <input class="form-control" type="email" name="email" placeholder="email@example.com">

                    <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
                </form>

@stop

Remove extra parenthesis on subscribe page


<?php

declare(strict_types=1);

namespace BaseReality\Service;

class DeploySiteNotifier
{

    public static $knownFullnames = [
//        "Danack/BaseReality",
        "Danack/Blog",
        "Danack/docs",
        "Danack/example",
        "Danack/Imagick-demos",
        "Danack/OpenSourceFees",
        "Danack/TierJigDocs",
        "PHPOpenDocs/PHPOpenDocs",
        "PHPOpenDocs/Sadness",
    ];

    public function pushBuildNotification($fullName, $type)
    {
        if (in_array($fullName, DeploySiteNotifier::$knownFullnames, true) === true) {
            $filename = preg_replace('#[^a-zA-Z0-9]#iu', '', $fullName) . '.json';
            $fullFilename = __DIR__ . '/../../../var/github_push/' . $filename;
            $data = [
                'event' => $type,
                'name' => $fullName
            ];

            @mkdir(dirname($fullFilename), 0755, true);
            file_put_contents($fullFilename, json_encode($data, JSON_PRETTY_PRINT));
        }
    }

}

<?php

declare(strict_types=1);

namespace BaseReality\Service;

class DeploySiteNotifier
{

    public static $knownFullnames = [
//        "Danack/BaseReality",
        "Danack/Blog",
        "Danack/docs",
        "Danack/example",
//        "Danack/Imagick-demos",
        "Imagick/ImagickDemos",
        "Danack/OpenSourceFees",
        "Danack/TierJigDocs",
        "PHPOpenDocs/PHPOpenDocs",
        "PHPOpenDocs/Sadness",
    ];

    public function pushBuildNotification($fullName, $type)
    {
        if (in_array($fullName, DeploySiteNotifier::$knownFullnames, true) === true) {
            $filename = preg_replace('#[^a-zA-Z0-9]#iu', '', $fullName) . '.json';
            $fullFilename = __DIR__ . '/../../../var/github_push/' . $filename;
            $data = [
                'event' => $type,
                'name' => $fullName
            ];

            @mkdir(dirname($fullFilename), 0755, true);
            file_put_contents($fullFilename, json_encode($data, JSON_PRETTY_PRINT));
        }
    }

}

Update imagick demos to be correct.

Update imagick demos to be correct.


<?php
ini_set('display_errors', 1);

return array(
    'modules' => array(
        'Application',
        'ZF\DevelopmentMode',
        'AssetManager',
        'ZfcBase',
        'ZfcUser',
        'ScnSocialAuth',
        'EdpGithub',
        'Application',
        'User',
        'EdpModuleLayouts',
        'ZfModule',
        'EdpMarkdown',
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

<?php
ini_set('display_errors', 1);

return array(
    'modules' => array(
        'ZF\DevelopmentMode',
        'AssetManager',
        'ZfcBase',
        'ZfcUser',
        'ScnSocialAuth',
        'EdpGithub',
        'Application',
        'User',
        'EdpModuleLayouts',
        'ZfModule',
        'EdpMarkdown',
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Fix: Remove duplicate entry in array of modules


<?php

/*
 * This file is part of the CrossContainerExtension package.
 *
 * (c) Kamil Kokot <kamil@kokot.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FriendsOfBehat\CrossContainerExtension;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\KernelInterface;

final class KernelBasedContainerAccessor implements ContainerAccessor
{
    /**
     * @var KernelInterface
     */
    private $kernel;

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

    /**
     * {@inheritdoc}
     */
    public function getService($id)
    {
        $container = $this->kernel->getContainer();

        if (!$container instanceof Container) {
            throw new \DomainException('Could not get the parameters of kernel\'s container.');
        }

        return (new ContainerBasedContainerAccessor($container))->getService($id);
    }

    /**
     * {@inheritdoc}
     */
    public function getParameters()
    {
        $container = $this->kernel->getContainer();

        if (!$container instanceof Container) {
            throw new \DomainException('Could not get the parameters of kernel\'s container.');
        }

        return (new ContainerBasedContainerAccessor($container))->getParameters();
    }
}

<?php

/*
 * This file is part of the CrossContainerExtension package.
 *
 * (c) Kamil Kokot <kamil@kokot.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FriendsOfBehat\CrossContainerExtension;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\KernelInterface;

final class KernelBasedContainerAccessor implements ContainerAccessor
{
    /**
     * @var KernelInterface
     */
    private $kernel;

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

    /**
     * {@inheritdoc}
     */
    public function getService($id)
    {
        $container = $this->kernel->getContainer();

        if (!$container instanceof Container) {
            throw new \DomainException('Could not get the services of kernel\'s container.');
        }

        return (new ContainerBasedContainerAccessor($container))->getService($id);
    }

    /**
     * {@inheritdoc}
     */
    public function getParameters()
    {
        $container = $this->kernel->getContainer();

        if (!$container instanceof Container) {
            throw new \DomainException('Could not get the parameters of kernel\'s container.');
        }

        return (new ContainerBasedContainerAccessor($container))->getParameters();
    }
}

Fix typo in the message of an exception

Fix typo in the message of an exception


<?php

namespace MssPhp\Schema\Request;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlList;

class SearchSpecial {
    /**
    * @Type("array<integer>")
    * @XmlList(inline = true, entry="offer_id")
     */
    public $offer_id;

    /**
     * @Type("DateTime<'Y-m-d'>")
     */
    public $date_from;

    /**
     * @Type("DateTime<'Y-m-d'>")
     */
    public $date_to;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="theme")
     */
    public $theme;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="poi_id")
     */
    public $poi_id;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="poi_cat")
     */
    public $poi_cat;

    /**
     * @Type("MssPhp\Schema\Request\Validity")
     */
    public $validity;

    /**
     * @Type("integer")
     */
    public $typ;

    /**
     * @Type("integer")
     */
    public $premium;
}

<?php

namespace MssPhp\Schema\Request;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlList;

class SearchSpecial {
    /**
    * @Type("array<integer>")
    * @XmlList(inline = true, entry="offer_id")
     */
    public $offer_id;

    /**
     * @Type("DateTime<'Y-m-d'>")
     */
    public $date_from;

    /**
     * @Type("DateTime<'Y-m-d'>")
     */
    public $date_to;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="theme")
     */
    public $theme;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="poi_id")
     */
    public $poi_id;

    /**
     * @Type("array<integer>")
     * @XmlList(inline = true, entry="poi_cat")
     */
    public $poi_cat;

    /**
     * @Type("MssPhp\Schema\Request\Validity")
     */
    public $validity;

    /**
     * @Type("integer")
     */
    public $typ;

    /**
     * @Type("integer")
     */
    public $premium;

    /**
     * @Type("integer")
     */
    public $status;
}

Add search special status property

Add search special status property


<?php

function handleGitHubPushEvent($payload)
{
   $config = getUserConfig($payload['repository']['full_name'].'/'.$payload['commits'][0]['id']);
}

function getUserConfig($commitpath)
{
   $defaultconfig = Config::get('userconfig');

   $config = yaml_parse_url("https://raw.githubusercontent.com/".$commitpath."/.redports.yml");
   if($config === false)
      return $defaultconfig;

   foreach($config as $key => $value)
   {
      if(isset($defaultconfig[$key]))
      {
         if(gettype($defaultconfig[$key]) == gettype($value))
            $defaultconfig[$key] = $value;
         else
         {
            if(settype($value, gettype($defaultconfig[$key])))
               $defaultconfig[$key] = $value;
         }
      }
   }

   return $defaultconfig;
}

<?php

function handleGitHubPushEvent($payload)
{
   $config = getUserConfig($payload['repository']['full_name'].'/'.$payload['commits'][0]['id']);
}

function getUserConfig($commitpath)
{
   $defaultconfig = Config::get('userconfig');

   $file = file_get_contents("https://raw.githubusercontent.com/".$commitpath."/.redports.json");
   if($file === false)
      return $defaultconfig;

   $config = json_decode($file, true);

   foreach($config as $key => $value)
   {
      if(isset($defaultconfig[$key]))
      {
         if(gettype($defaultconfig[$key]) == gettype($value))
            $defaultconfig[$key] = $value;
         else
         {
            if(settype($value, gettype($defaultconfig[$key])))
               $defaultconfig[$key] = $value;
         }
      }
   }

   return $defaultconfig;
}

Convert yaml to json config

Convert yaml to json config


<?php

function sqlToJson($sql) {
	$json = array();
	while ($row = mysql_fetch_assoc($sql)) {
		$json[] = $row;
	}
	echo json_encode($json);
}

?>

<?php

function sqlToJson($sql) {
	$json = array();
	while ($row = mysql_fetch_assoc($sql)) {
		$json[] = $row;
	}
	echo json_encode($json, JSON_NUMERIC_CHECK);
}

?>

Convert to JSON integers, not strings (B14)


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShopAssignment extends Model
{
    //
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShopAssignment extends Model
{
    protected $fillable = [
        'shop_id',
        'user_id',
        'roles_id'
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }
    public function roles()
    {
        return $this->hasMany('App\Role');
    }
    public function shops()
    {
        retrun $this->hasMany('App\Shop')
    }
}

feat(shopassignment): Create relationship for shopassignment table

Create relationship for shopassignment table

see #138


<?php

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

namespace Composer\Test\Util;

use Composer\Util\ErrorHandler;
use Composer\TestCase;

/**
 * ErrorHandler test case
 */
class ErrorHandlerTest extends TestCase
{
    /**
     * Test ErrorHandler handles notices
     */
    public function testErrorHandlerCaptureNotice()
    {
        $this->setExpectedException('\ErrorException', 'Undefined index: baz');

        ErrorHandler::register();

        $array = array('foo' => 'bar');
        $array['baz'];
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerCaptureWarning()
    {
        $this->setExpectedException('\ErrorException', 'array_merge(): Argument #2 is not an array');

        ErrorHandler::register();

        array_merge(array(), 'string');
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerRespectsAtOperator()
    {
        ErrorHandler::register();

        @trigger_error('test', E_USER_NOTICE);
    }
}

<?php

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

namespace Composer\Test\Util;

use Composer\Util\ErrorHandler;
use Composer\TestCase;

/**
 * ErrorHandler test case
 */
class ErrorHandlerTest extends TestCase
{
    /**
     * Test ErrorHandler handles notices
     */
    public function testErrorHandlerCaptureNotice()
    {
        $this->setExpectedException('\ErrorException', 'Undefined index: baz');

        ErrorHandler::register();

        $array = array('foo' => 'bar');
        $array['baz'];
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerCaptureWarning()
    {
        $this->setExpectedException('\ErrorException', 'array_merge');

        ErrorHandler::register();

        array_merge(array(), 'string');
    }

    /**
     * Test ErrorHandler handles warnings
     */
    public function testErrorHandlerRespectsAtOperator()
    {
        ErrorHandler::register();

        @trigger_error('test', E_USER_NOTICE);
    }
}

Check only part of the error message as it's different in hhvm


<?php

namespace EGALL\Transformer\Traits;

use EGALL\Transformer\Transformer;

/**
 * TransformableModel Class
 *
 * @package EGALL\Transformer\Traits
 * @author Erik Galloway <erik@mybarnapp.com>
 */
trait TransformableModel
{

    /**
     * Transform the model to an array.
     *
     * @return array
     */
    public function transform()
    {

        return $this->transformer()->transform();

    }

    /**
     * Get the model's transformer.
     *
     * @param bool $nested
     * @return \EGALL\Transformer\Transformer
     */
    public function transformer($nested = false)
    {

        $transformer = $this->transformerClass();

        return new $transformer($this, $nested);

    }

    /**
     * Get the transformer class.
     *
     * Transformer class can be setting a transformer
     * property or by overriding the transformer method.
     *
     * @return string
     */
    protected function transformerClass()
    {

        if (property_exists($this, 'transformer')) {

            return $this->transformer;

        }

        return Transformer::class;
    }
}

<?php

namespace EGALL\Transformer\Traits;

use EGALL\Transformer\Transformer;

/**
 * TransformableModel Class
 *
 * @package EGALL\Transformer\Traits
 * @author Erik Galloway <erik@mybarnapp.com>
 */
trait TransformableModel
{

    /**
     * Transform the model to an array.
     *
     * @return array
     */
    public function transform()
    {

        return $this->transformer()->transform();

    }

    /**
     * Get the model's transformer.
     *
     * @param bool $nested
     * @return \EGALL\Transformer\Transformer
     */
    public function transformer($nested = false)
    {

        $transformer = $this->transformerClass();

        return new $transformer($this, $nested);

    }

    /**
     * Get the transformer class.
     *
     * Transformer class can be setting a transformer
     * property or by overriding the transformer method.
     *
     * @return string
     */
    protected function transformerClass()
    {

        if (class_exists($default = $this->getDefaultTransformerNamespace())){

            return $default;
        }

        if (property_exists($this, 'transformer')) {

            return $this->transformer;

        }

        return Transformer::class;
    }

    /**
     * Get the default transformer class for the model.
     *
     * @return string
     */
    protected function getDefaultTransformerNamespace()
    {

        $parts = explode('\\', get_class($this));

        $class = array_last($parts);

        array_forget($parts, array_last(array_keys($parts)));

        return $this->makeTransformer($class, implode('\\', $parts));

    }

    /**
     * Make the default transformer class namespace.
     *
     * @param string $class
     * @param string $namespace
     * @return string
     */
    protected function makeTransformer($class, $namespace)
    {

        return $namespace . '\\Transformers\\' . $class . 'Transformer';
    }
}

Allow the tranformable model trait to find the transformers with setting the property


<?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;

class Response extends \Symfony\Component\HttpFoundation\Response {

	public function send() {
        $cleared = Cookie::getClearedCookies();
        foreach($cleared as $cookie) {
            $this->headers->clearCookie($cookie);
        }
		$cookies = Cookie::getCookies();
		foreach($cookies as $cookie) {
			$this->headers->setCookie($cookie);
		}

		$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
		if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
			$this->headers->set('X-Frame-Options', $x_frame_options);
		}

		parent::send();
	}
}

<?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;

class Response extends \Symfony\Component\HttpFoundation\Response {

	public function send() {
        $cleared = Cookie::getClearedCookies();
        foreach($cleared as $cookie) {
            $this->headers->clearCookie($cookie);
        }
		$cookies = Cookie::getCookies();
		foreach($cookies as $cookie) {
			$this->headers->setCookie($cookie);
		}

		if ($this->headers->has('X-Frame-Options') === false) {
			$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
			if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
				$this->headers->set('X-Frame-Options', $x_frame_options);
			}
		}

		parent::send();
	}
}

Check if the x-frame-options header is already set

Former-commit-id: 5121dd2f802162895e09676b855a50fb7f09155f
Former-commit-id: 587564af563a41e838051cc40f67c2415e7a893a


<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\ORM\QueryBuilder;

interface DictionaryValueListProviderInterface
{
    /**
     * Checks whether the provider supports a given entity
     *
     * @param string $className The FQCN of an entity
     *
     * @return bool TRUE if this provider supports the given entity; otherwise, FALSE
     */
    public function supports($className);

    /**
     * Gets a query builder for getting dictionary item values for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return QueryBuilder
     */
    public function getValueListQueryBuilder($className);

    /**
     * Returns the configuration of the entity serializer for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return array
     */
    public function getSerializationConfig($className);

    /**
     * Gets a list of entity classes supported by this provider
     *
     * @return string[]
     */
    public function getSupportedEntityClasses();
}

<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\ORM\QueryBuilder;

interface DictionaryValueListProviderInterface
{
    /**
     * Checks whether the provider supports a given entity
     *
     * @param string $className The FQCN of an entity
     *
     * @return bool TRUE if this provider supports the given entity; otherwise, FALSE
     */
    public function supports($className);

    /**
     * Gets a query builder for getting dictionary item values for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return QueryBuilder
     */
    public function getValueListQueryBuilder($className);

    /**
     * Gets the configuration of the entity serializer for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return array
     */
    public function getSerializationConfig($className);

    /**
     * Gets a list of entity classes supported by this provider
     *
     * @return string[]
     */
    public function getSupportedEntityClasses();
}

OEE-620: Create REST API resource to get dictionary/enum items. Fix CS


<?php namespace Lecturize\Taxonomies;

use Illuminate\Support\ServiceProvider;

class TaxonomiesServiceProvider extends ServiceProvider
{
    protected $migrations = [
        'CreateTaxonomiesTable' => 'create_taxonomies_table'
    ];

     /**
     * @inheritdoc
      */
     public function boot()
     {
        $this->handleConfig();
        $this->handleMigrations();
     }

     /**
     * @inheritdoc
      */
     public function register()
     {
         //
     }

     /**
     * @inheritdoc
      */
     public function provides()
     {
          return [];
     }

    /**
     * Publish and merge the config file.
     *
     * @return void
     */
    private function handleConfig()
    {
        $configPath = __DIR__ . '/../config/config.php';

        $this->publishes([$configPath => config_path('lecturize.php')]);

        $this->mergeConfigFrom($configPath, 'lecturize');
    }

    /**
     * Publish migrations.
     *
     * @return void
     */
    private function handleMigrations()
    {
        foreach ($this->migrations as $class => $file) {
            if (! class_exists($class)) {
                $timestamp = date('Y_m_d_His', time());

                $this->publishes([
                    __DIR__ .'/../database/migrations/'. $file .'.php.stub' =>
                        database_path('migrations/'. $timestamp .'_'. $file .'.php')
                ], 'migrations');
            }
        }
    }
}

<?php namespace Lecturize\Taxonomies;

use Illuminate\Support\ServiceProvider;

class TaxonomiesServiceProvider extends ServiceProvider
{
    protected $migrations = [
        'CreateTaxonomiesTable' => 'create_taxonomies_table',
        'UpdateTaxonomiesTable' => 'extend_taxonomies_table'
    ];

     public function boot()
     {
        $this->handleConfig();
        $this->handleMigrations();

         $this->loadTranslationsFrom(__DIR__ .'/../resources/lang', 'taxonomies');
     }

    /** @inheritdoc */
     public function register()
     {
         //
     }

    /** @inheritdoc */
     public function provides()
     {
          return [];
     }

    /**
     * Publish and merge the config file.
     *
     * @return void
     */
    private function handleConfig()
    {
        $configPath = __DIR__ . '/../config/config.php';

        $this->publishes([$configPath => config_path('lecturize.php')]);

        $this->mergeConfigFrom($configPath, 'lecturize');
    }

    /**
     * Publish migrations.
     *
     * @return void
     */
    private function handleMigrations()
    {
        $count = 0;
        foreach ($this->migrations as $class => $file) {
            if (! class_exists($class)) {
                $timestamp = date('Y_m_d_Hi'. sprintf('%02d', $count), time());

                $this->publishes([
                    __DIR__ .'/../database/migrations/'. $file .'.php.stub' =>
                        database_path('migrations/'. $timestamp .'_'. $file .'.php')
                ], 'migrations');

                $count++;
            }
        }
    }
}

Update service provider with new migration and translations loader


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\Menu;

/**
 * Menu item group
 */
class ItemGroup extends Item
{
    /**
     * {@inheritdoc}
     */
    public function __construct($name)
    {
        parent::__construct($name);

        $this->indexTitle = sprintf('menu.group.%s.title', $name);
        $this->indexUrl = '#';
        $this->description = sprintf('menu.group.%s.description', $name);
    }
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\Menu;

/**
 * Menu item group
 */
class ItemGroup extends Item
{
    /**
     * {@inheritdoc}
     */
    public function __construct(string $name)
    {
        parent::__construct($name);

        $this->indexTitle = sprintf('menu.group.%s.title', $name);
        $this->indexUrl = '#';
        $this->description = sprintf('menu.group.%s.description', $name);
    }
}

Enable strict types in menu item group class.


<?php

namespace Northstar\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Northstar\Http\Middleware\ParseOAuthHeader;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Routing\Router;

class Kernel extends HttpKernel
{
    /**
     * Create a new HTTP kernel instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Routing\Router  $router
     */
    public function __construct(Application $app, Router $router)
    {
        parent::__construct($app, $router);

        // Conditionally apply OAuth middleware if feature flag is set.
        if (config('features.oauth')) {
            $this->middleware[] = ParseOAuthHeader::class;
        }
    }

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Northstar\Http\Middleware\Authenticate::class,
        'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class,
        'scope' => \Northstar\Http\Middleware\RequireScope::class,
    ];
}

<?php

namespace Northstar\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Northstar\Http\Middleware\ParseOAuthHeader;

class Kernel extends HttpKernel
{
    /**
     * Bootstrap the application for HTTP requests.
     *
     * @return void
     */
    public function bootstrap()
    {
        parent::bootstrap();

        // Conditionally apply OAuth middleware if feature flag is set.
        if (config('features.oauth')) {
            $this->middleware[] = ParseOAuthHeader::class;
        }
    }

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Northstar\Http\Middleware\Authenticate::class,
        'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class,
        'scope' => \Northstar\Http\Middleware\RequireScope::class,
    ];
}

Fix bootstrap issue with conditionally enabling middleware.


<?php

namespace Sminnee\SilverStripeIntercom;

class RequestFilter implements \RequestFilter
{
	/**
	 * Does nothing
	 */
	public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) {

	}

	/**
	 * Adds Intercom script tags just before the body
	 */
	public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) {
		$mime = $response->getHeader('Content-Type');
		if(!$mime || strpos($mime, 'text/html') !== false) {
			$intercomScriptTags = (new intercomScriptTags())->forTemplate();

			if($intercomScriptTags) {
				$content = $response->getBody();
				$content = preg_replace("/(<\/body[^>]*>)/i", $intercomScriptTags . "\\1", $content);
				$response->setBody($content);
			}
		}
	}
}

<?php

namespace Sminnee\SilverStripeIntercom;

use SS_HTTPRequest;
use SS_HTTPResponse;
use Session;
use DataModel;

class RequestFilter implements \RequestFilter
{
	/**
	 * Does nothing
	 */
	public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) {

	}

	/**
	 * Adds Intercom script tags just before the body
	 */
	public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) {
		$mime = $response->getHeader('Content-Type');
		if(!$mime || strpos($mime, 'text/html') !== false) {
			$intercomScriptTags = (new IntercomScriptTags())->forTemplate();

			if($intercomScriptTags) {
				$content = $response->getBody();
				$content = preg_replace("/(<\/body[^>]*>)/i", $intercomScriptTags . "\\1", $content);
				$response->setBody($content);
			}
		}
	}
}

Declare classes in global namespace

Declare classes in global namespace

In strict mode, type hints were throwing errors (Sminnee\SilverStripeIntercom\SS_HTTPRequest doesn't exist)


<?php

namespace Clastic\MenuBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ClasticMenuExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}

<?php

namespace Clastic\MenuBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ClasticMenuExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (true === isset($bundles['StofDoctrineExtensionsBundle'])) {
            $this->configureStofDoctrineExtensionsBundle($container);
        }
    }

    /**
     * @param ContainerBuilder $container The service container
     *
     * @return void
     */
    protected function configureStofDoctrineExtensionsBundle(ContainerBuilder $container)
    {
        foreach (array_keys($container->getExtensions()) as $name) {
            switch ($name) {
                case 'stof_doctrine_extensions':
                    $container->prependExtensionConfig(
                        $name,
                        array('orm' => array('default' => array('tree' => true)))
                    );
                    break;
            }
        }
    }
}

Move configuration to Bundle Extension.

[Menu] Move configuration to Bundle Extension.


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => '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.
    |
    | Supported Drivers: "local", "ftp", "s3", "rackspace"
    |
    */

    'disks' => [

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

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

        's3' => [
            'driver' => 's3',
            'key' => 'your-key',
            'secret' => 'your-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => '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.
    |
    | Supported Drivers: "local", "ftp", "s3", "rackspace"
    |
    */

    'disks' => [

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

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => url('storage'),
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => 'your-key',
            'secret' => 'your-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

    ],

];

Put URL config option on the disk to make it obvious how to customize.


<?php

declare(strict_types=1);

namespace App\Entity\Migration;

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

final class Version20220706235608 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add "is_visible" denormalization to song_history table.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE song_history ADD is_visible TINYINT(1) NOT NULL');
        $this->addSql('CREATE INDEX idx_is_visible ON song_history (is_visible)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX idx_is_visible ON song_history');
        $this->addSql('ALTER TABLE song_history DROP is_visible');
    }
}

<?php

declare(strict_types=1);

namespace App\Entity\Migration;

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

final class Version20220706235608 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add "is_visible" denormalization to song_history table.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE song_history ADD is_visible TINYINT(1) NOT NULL');
        $this->addSql('CREATE INDEX idx_is_visible ON song_history (is_visible)');

        $this->addSql('UPDATE song_history SET is_visible=1');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX idx_is_visible ON song_history');
        $this->addSql('ALTER TABLE song_history DROP is_visible');
    }
}

Set all older tracks to be "visible".

Set all older tracks to be "visible".


<?php
class Feedback extends DataObject
{
	/**
	 * @var array
	 */
	public static $db = array(
		'Rating' => 'Boolean',
		'Comment' => 'Text',
		'URL' => 'Text',
		'IP' => 'Text'
	);

	/**
	 * @var array
	 */
	public static $summary_fields = array(
		'Rating',
		'Comment',
		'URL'
	);
}

<?php
class Feedback extends DataObject
{
	/**
	 * @var array
	 */
	public static $db = array(
		'Rating' => 'Boolean',
		'Comment' => 'Text',
		'URL' => 'Text',
		'IP' => 'Text'
	);

	/**
	 * @var array
	 */
	public static $summary_fields = array(
		'Rating',
		'Comment',
		'URL'
	);

	public function canView($member = null) {
        return Permission::check('CMS_ACCESS_FeedbackAdmin');
    }
    public function canEdit($member = null) {
        return Permission::check('CMS_ACCESS_FeedbackAdmin');
    }
    public function canDelete($member = null) {
        return Permission::check('CMS_ACCESS_FeedbackAdmin');
    }
    public function canCreate($member = null) {
        return Permission::check('CMS_ACCESS_FeedbackAdmin');
    }

}

FIX Non-admin users cannot view the feedback in the module admin

CRUD permissions need to be set.


<?php
declare(strict_types=1);

namespace Prooph\EventMachine\GraphQL;

use GraphQL\Type\Definition\ResolveInfo;
use Prooph\EventMachine\EventMachine;
use Psr\Http\Message\ServerRequestInterface;
use React\Promise\FulfilledPromise;
use React\Promise\PromiseInterface;

final class MessageFieldResolver implements FieldResolver
{
    /**
     * @var EventMachine
     */
    private $eventMachine;

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

    public function canResolve($source, array $args, ServerRequestInterface $context, ResolveInfo $info): bool
    {
        $field = $info->fieldName;

        return $this->eventMachine->isKnownQuery($field) || $this->eventMachine->isKnownCommand($field);
    }

    public function resolve($source, array $args, ServerRequestInterface $context, ResolveInfo $info): PromiseInterface
    {
        $message = $this->eventMachine->messageFactory()->createMessageFromArray($info->fieldName, [
            'payload' => $args
        ]);

        $result = $this->eventMachine->dispatch($message);

        if(null === $result) {
            return new FulfilledPromise(true);
        }

        return $result;
    }
}

<?php
declare(strict_types=1);

namespace Prooph\EventMachine\GraphQL;

use GraphQL\Type\Definition\ResolveInfo;
use Prooph\EventMachine\EventMachine;
use Prooph\ServiceBus\Exception\MessageDispatchException;
use Psr\Http\Message\ServerRequestInterface;
use React\Promise\FulfilledPromise;
use React\Promise\PromiseInterface;

final class MessageFieldResolver implements FieldResolver
{
    /**
     * @var EventMachine
     */
    private $eventMachine;

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

    public function canResolve($source, array $args, ServerRequestInterface $context, ResolveInfo $info): bool
    {
        $field = $info->fieldName;

        return $this->eventMachine->isKnownQuery($field) || $this->eventMachine->isKnownCommand($field);
    }

    public function resolve($source, array $args, ServerRequestInterface $context, ResolveInfo $info): PromiseInterface
    {
        $message = $this->eventMachine->messageFactory()->createMessageFromArray($info->fieldName, [
            'payload' => $args
        ]);

        try {
            $result = $this->eventMachine->dispatch($message);
        } catch (MessageDispatchException $exception) {
            throw $exception->getPrevious();
        }

        if(null === $result) {
            return new FulfilledPromise(true);
        }

        return $result;
    }
}

Throw inner exception in case of MessageDispatchException


<?php

namespace Sdmx\api\client\http;

use Requests;

class RequestHttpClient implements HttpClient
{
    /**
     * @var array $predefinedHeaders
     */
    private $predefinedHeaders = [];

    /**
     * @param string $url
     * @param array $headers
     * @param array $options
     * @return string
     */
    public function get($url, $headers = array('Accept' => 'application/xml', 'Accept-Encoding' => 'gzip'), $options = array())
    {
        $headersToSend = array_merge($this->predefinedHeaders, $headers);
        $response =  Requests::get($url, $headersToSend, $options);

        return $response->body;
    }

    /**
     * @param array $headers
     */
    public function setPredefinedHeaders(array $headers)
    {
        $this->predefinedHeaders = $headers;
    }
}

<?php

namespace Sdmx\api\client\http;

use Requests;

class RequestHttpClient implements HttpClient
{
    /**
     * @var array $predefinedHeaders
     */
    private $predefinedHeaders = [];

    /**
     * @param string $url
     * @param array $headers
     * @param array $options
     * @return string
     */
    public function get($url, $headers = array('Accept' => 'application/xml', 'Accept-Encoding' => 'gzip'), $options = array())
    {
        $headersToSend = array_merge($this->predefinedHeaders, $headers);
        $response =  Requests::get($url, $headersToSend, $options);

        return $response->success ? $response->body : null;
    }

    /**
     * @param array $headers
     */
    public function setPredefinedHeaders(array $headers)
    {
        $this->predefinedHeaders = $headers;
    }
}

Return null when a response is not succesful.


<?php
namespace App\Http\Requests\Api\v1\Route;

use Gate;
use App\Models\Page;
use Illuminate\Validation\Rule;
use App\Http\Requests\FormRequest;

class ResolveRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => 'required',
            'host' => 'required'
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }
}

<?php
namespace App\Http\Requests\Api\v1\Route;

use Gate;
use App\Models\Page;
use Illuminate\Validation\Rule;
use App\Http\Requests\FormRequest;

class ResolveRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => ['string','nullable'],
            'host' => 'required'
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }
}

Resolve route allow empty / nullable path


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Mail\GeneralInterestInvite as Mailable;

class GeneralInterestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return Mailable
     */
    public function toMail($notifiable)
    {
        return (new Mailable($notifiable->visit_token))->to($notifiable->recruiting_email);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Mail\GeneralInterestInvite as Mailable;

class GeneralInterestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return Mailable
     */
    public function toMail($notifiable)
    {
        // Set data for inclusion in the view
        $token = $notifiable->recruitingVisit->visit_token;
        $email = $notifiable->email_address;

        // Update the notifiable to show it has been sent
        $notifiable->notified_at = date("Y-m-d H:i:s", time());
        $notifiable->save();

        return (new Mailable($token))->to($email);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Update notifiable upon job send (theoretically)


<?php

class Asm_Solr_Model_Indexer_Cms extends Mage_Index_Model_Indexer_Abstract
{

	protected function _construct()
	{
		$this->_init('solr/indexer_cms');
	}

	/**
	 * Get Indexer name
	 *
	 * @return string
	 */
	public function getName()
	{
		return Mage::helper('solr')->__('Solr CMS Search Index');
	}

	/**
	 * Get Indexer description
	 *
	 * @return string
	 */
	public function getDescription()
	{
		return Mage::helper('solr')->__('Rebuild Solr CMS search index');
	}

	/**
	 * Register indexer required data inside event object
	 *
	 * @param Mage_Index_Model_Event $event
	 */
	protected function _registerEvent(Mage_Index_Model_Event $event)
	{
		// TODO: Implement _registerEvent() method.
	}

	/**
	 * Process event based on event state data
	 *
	 * @param Mage_Index_Model_Event $event
	 */
	protected function _processEvent(Mage_Index_Model_Event $event)
	{
		// TODO: Implement _processEvent() method.
	}

	public function reindexAll()
	{
		$resource = $this->_getResource();
		$resource->rebuildIndex();

		$connection = Mage::helper('solr/connectionManager')->getConnection();
		$connection->commit();
	}
}

<?php

class Asm_Solr_Model_Indexer_Cms extends Mage_Index_Model_Indexer_Abstract
{

	protected function _construct()
	{
		$this->_init('solr/indexer_cms');
	}

	/**
	 * Get Indexer name
	 *
	 * @return string
	 */
	public function getName()
	{
		return Mage::helper('solr')->__('Solr CMS Search Index');
	}

	/**
	 * Get Indexer description
	 *
	 * @return string
	 */
	public function getDescription()
	{
		return Mage::helper('solr')->__('Rebuild Solr CMS search index');
	}

	/**
	 * Register indexer required data inside event object
	 *
	 * @param Mage_Index_Model_Event $event
	 */
	protected function _registerEvent(Mage_Index_Model_Event $event)
	{
		// TODO: Implement _registerEvent() method.
	}

	/**
	 * Process event based on event state data
	 *
	 * @param Mage_Index_Model_Event $event
	 */
	protected function _processEvent(Mage_Index_Model_Event $event)
	{
		// TODO: Implement _processEvent() method.
	}

	public function reindexAll()
	{
		$resource = $this->_getResource();
		$resource->rebuildIndex();
	}
}

Remove explicit commit as Solr will do a soft-commit already


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

/**
 * Page Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @package     Nooku_Server
 * @subpackage  Application
 */

class ComApplicationControllerPage extends KControllerResource
{
    protected function _initialize(KConfig $config)
    {
        $config->append(array(
            'view'      => 'page',
            'toolbars'  => array('menubar', $this->getIdentifier()->name),
        ));

        parent::_initialize($config);
    }
}

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

/**
 * Page Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @package     Nooku_Server
 * @subpackage  Application
 */

class ComApplicationControllerPage extends KControllerResource
{
    protected function _initialize(KConfig $config)
    {
        $config->append(array(
            'view'      => 'page',
            'toolbars'  => array('menubar', $this->getIdentifier()->name),
        ));

        parent::_initialize($config);
    }

    protected function _actionGet(KCommandContext $context)
    {
        $this->getView()->content = $context->response->getContent();
        return parent::_actionGet($context);
    }
}

Set the view content based on the content in the response.


<?php

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

// Check that the extension is loaded.
if ( ! extension_loaded('ds')) {
    echo "ds extension is not enabled\n";
    exit(1);
}

// 'false' so that PHPUnit doesn't use "exit"
PHPUnit_TextUI_Command::main(false);

// Attempt to collect anything left over from the tests.
gc_collect_cycles();

<?php

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

// Check that the extension is loaded.
if ( ! extension_loaded('ds')) {
    echo "ds extension is not enabled\n";
    exit(1);
}

// 'false' so that PHPUnit doesn't use "exit"
\PHPUnit\TextUI\Command::main(false);

// Attempt to collect anything left over from the tests.
gc_collect_cycles();

Fix PHPUnit namespace for 6.x

Fix PHPUnit namespace for 6.x


<?php

declare(strict_types=1);

namespace Arachne\Forms\Extension\Application\Type;

use Arachne\Forms\Extension\Application\ApplicationRequestHandler;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Jáchym Toušek <enumag@gmail.com>
 */
class FormTypeApplicationExtension extends AbstractTypeExtension
{
    /**
     * @var ApplicationRequestHandler
     */
    private $requestHandler;

    public function __construct()
    {
        $this->requestHandler = new ApplicationRequestHandler();
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->setRequestHandler($this->requestHandler);
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType(): string
    {
        return FormType::class;
    }
}

<?php

declare(strict_types=1);

namespace Arachne\Forms\Extension\Application\Type;

use Arachne\Forms\Extension\Application\ApplicationRequestHandler;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Jáchym Toušek <enumag@gmail.com>
 */
class FormTypeApplicationExtension extends AbstractTypeExtension
{
    /**
     * @var ApplicationRequestHandler
     */
    private $requestHandler;

    public function __construct()
    {
        $this->requestHandler = new ApplicationRequestHandler();
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->setRequestHandler($this->requestHandler);
    }

    /**
     * {@inheritdoc}
     */
    public static function getExtendedTypes(): iterable
    {
        yield FormType::class;
    }

    /**
     * @deprecated to be removed when Symfony 4.1 and older are no longer supported
     */
    public function getExtendedType(): string
    {
        return FormType::class;
    }
}

Fix compatibility with Symfony 4.2

Fix compatibility with Symfony 4.2


<?php
require_once 'scripts/script.php';

date_default_timezone_set('UTC');
/**
 *
 */
class time extends Script
{
    private $helpMessage = 'Returns the actual UTC time';

    public function run()
    {
        return $this->send($this->message->number, date(RFC822));
    }
}

<?php
require_once 'scripts/script.php';

date_default_timezone_set('UTC');
/**
 *
 */
class time extends Script
{
    protected $helpMessage = 'Returns the actual UTC time';

    public function run()
    {
        return $this->send($this->message->number, date(DATE_RFC822));
    }
}

Change the accesslevel and use DATE_RFC822


<?php

// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);

/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*
*/
foreach ($emails as $email) {
  if ( !empty($email) && User::findByEmail($email) == false ) { // user doesn't exist yet
    if ( User::create($email) ) {
      echo "
$email aggiunto con successo alla lista {$_POST['name']}.";
    }
    else {
      // Probabilmente fallisce perche` e` gia` nel db.
      echo "
ERRORE durante l'inserimento di $email.";
    }
  }
}
// Setto la list_id all'id della lista corrente, cosi' l'aggiunta e' completa
$update_list_id = $db->prepare("UPDATE users SET list_id = $list_id WHERE list_id <= 0");
$update_list_id->execute();

<?php

// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);

/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*/
foreach ($emails as $email) {

  $_user_is_empty = empty($email);
  $_user_already_exists = User::findByEmail($email);

  if ($_user_is_empty) {

    echo "
$email cannot be added because it's empty.
";
  }

  else if ($_user_already_exists) {

    // then don't insert it.
    echo "
$email cannot be added to the list because it already exists in another list.
";

  } else {

    // let's create the user.
    if (User::create($email, '', $list_id)) {
      echo "
$email successfully added to the list.";
    } else {
      echo "
$email hasn't been created because of an unknown error. Sorry.
";
    }

  }
}

Fix bug when saving users in mailing list


<?php

return [
    'debug'        => env('MESSENGER_DEBUG', false),
    'verify_token' => env('MESSENGER_VERIFY_TOKEN'),
    'app_token'    => env('MESSENGER_APP_TOKEN'),
    'app_secret'   => env('MESSENGER_APP_SECRET'),
    'auto_typing'  => true,
    'handlers'     => [
        Casperlaitw\LaravelFbMessenger\Contracts\DefaultHandler::class,
    ],
    'custom_url'   => '/webhook',
    'postbacks'    => [],
    'home_url'     => [
        'url'                  => env('MESSENGER_HOME_URL'),
        'webview_share_button' => 'show',
        'in_test'              => true,
    ],
];

<?php

return [
    'debug'        => env('MESSENGER_DEBUG', false),
    'verify_token' => env('MESSENGER_VERIFY_TOKEN'),
    'app_token'    => env('MESSENGER_APP_TOKEN'),
    'auto_typing'  => false,
    'handlers'     => [
        App\Chatbot\MessageHandlers\DefaultHandler::class,
    ],
    'custom_url'   => '/webhook',
    'postbacks'    => [
        App\Chatbot\PostbackHandlers\DefaultPostbackHandler::class,
    ],
    'home_url'     => [
        'url'                  => env('MESSENGER_HOME_URL'),
        'webview_share_button' => 'show',
        'in_test'              => true,
    ],
];

Fix config of fb messenger

Fix config of fb messenger


<?php

/**
 * @group pholio
 */
final class PholioInlineThumbController extends PholioController {

  private $imageid;

  public function willProcessRequest(array $data) {
    $this->imageid = idx($data, 'imageid');
  }

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $image = id(new PholioImage())->load($this->imageid);

    if ($image == null) {
      return new Aphront404Response();
    }

    $mock = id(new PholioMockQuery())
      ->setViewer($user)
      ->withIDs(array($image->getMockID()))
      ->executeOne();

    if (!$mock) {
      return new Aphront404Response();
    }

    $file = id(new PhabricatorFile())->loadOneWhere(
      'phid = %s',
      $image->getFilePHID());

    return id(new AphrontRedirectResponse())->setURI($file->getThumb60x45URI());
  }

}

<?php

/**
 * @group pholio
 */
final class PholioInlineThumbController extends PholioController {

  private $imageid;

  public function shouldAllowPublic() {
    return true;
  }

  public function willProcessRequest(array $data) {
    $this->imageid = idx($data, 'imageid');
  }

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $image = id(new PholioImage())->load($this->imageid);

    if ($image == null) {
      return new Aphront404Response();
    }

    $mock = id(new PholioMockQuery())
      ->setViewer($user)
      ->withIDs(array($image->getMockID()))
      ->executeOne();

    if (!$mock) {
      return new Aphront404Response();
    }

    $file = id(new PhabricatorFile())->loadOneWhere(
      'phid = %s',
      $image->getFilePHID());

    return id(new AphrontRedirectResponse())->setURI($file->getThumb60x45URI());
  }

}

Make Pholio mock image thumbnails publicly visible

Summary:
Refs T2652 - This should make all of Pholio mocks publicly visible

The rest that is to be done is more generic, like the ActionListView etc.

Test Plan: set mock to public, visited it in another browser without user session

Reviewers: epriestley, btrahan

Reviewed By: epriestley

CC: aran, Korvin

Maniphest Tasks: T2652

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


<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class CentrifugoProxyController extends Controller
{
    public function connect()
    {
        return new JsonResponse([
            'result' => [
                'user' => (string) Auth::user()->id
            ]
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class CentrifugoProxyController extends Controller
{
    public function connect()
    {
        return new JsonResponse([
            'result' => [
                'user' => (string) Auth::user()->id,
                'channels' => ["personal:#".Auth::user()->id],
            ]
        ]);
    }
}

Revert "personal channel is automatic"

Revert "personal channel is automatic"

This reverts commit 7ed0c57f64adaa0eafc842da4f199f0488c7f4d7.


<?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\Component\Serializer\Tests\Fixtures;

class TraversableDummy implements \IteratorAggregate
{
    public $foo = 'foo';
    public $bar = 'bar';

    public function getIterator()
    {
        return new \ArrayIterator(get_object_vars($this));
    }
}

<?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\Component\Serializer\Tests\Fixtures;

class TraversableDummy implements \IteratorAggregate
{
    public $foo = 'foo';
    public $bar = 'bar';

    public function getIterator(): \Traversable
    {
        return new \ArrayIterator(get_object_vars($this));
    }
}

Add return types to internal & magic methods when possible


<?php
namespace Payum\Core\Security;

interface CryptedInterface
{
    /**
     * {@inheritdoc}
     */
    public function decrypt(CypherInterface $cypher);

    /**
     * {@inheritdoc}
     */
    public function encrypt(CypherInterface $cypher);
}

<?php
namespace Payum\Core\Security;

interface CryptedInterface
{
    /**
     * @param CypherInterface $cypher
     *
     * @return void
     */
    public function decrypt(CypherInterface $cypher);

    /**
     * @param CypherInterface $cypher
     *
     * @return void
     */
    public function encrypt(CypherInterface $cypher);
}

Fix docblocks on the interface

Fix docblocks on the interface


<?php

if(!defined('IDENTITY_IRI')) define('IDENTITY_IRI', null);

class IdentityModule extends Module
{
	public $moduleId = 'com.nexgenta.eregansu.identity';
	public $latestVersion = 1;

	public static function getInstance($args = null)
	{
		if(!isset($args['class'])) $args['class'] = 'IdentityModule';
		if(!isset($args['db'])) $args['db'] = IDENTITY_IRI;
		return parent::getInstance($args);
	}

	public function __construct($args)
	{
		if(!strncmp($args['db'], 'file:', 5) || !strncmp($args['db'], 'ldap:', 5))
		{
			$args['db'] = null;
		}
		parent::__construct($args);
	}

	public function dependencies()
	{
		$this->depend('com.nexgenta.eregansu.store');
	}

	public function updateSchema($targetVersion)
	{
		if($targetVersion == 1)
		{
			$t = $this->db->schema->tableWithOptions('object_identity', DBTable::CREATE_ALWAYS);
			$t->columnWithSpec('uuid', DBType::UUID, null, DBCol::NOT_NULL, null, 'Object identifier');
			$t->columnWithSpec('iri', DBType::VARCHAR, 128, DBCol::NOT_NULL, null, 'IRI relating to this user');
			$t->indexWithSpec('uuid', DBIndex::INDEX, 'uuid');
			$t->indexWithSpec('iri', DBIndex::INDEX, 'iri');
			return $t->apply();
		}
	}
}

<?php

if(!defined('IDENTITY_IRI')) define('IDENTITY_IRI', null);

class IdentityModule extends Module
{
	public $moduleId = 'com.nexgenta.eregansu.identity';
	public $latestVersion = 0;

	public static function getInstance($args = null)
	{
		if(!isset($args['class'])) $args['class'] = 'IdentityModule';
		if(!isset($args['db'])) $args['db'] = IDENTITY_IRI;
		return parent::getInstance($args);
	}

	public function __construct($args)
	{
		if(!strncmp($args['db'], 'file:', 5) || !strncmp($args['db'], 'ldap:', 5))
		{
			$args['db'] = null;
		}
		parent::__construct($args);
	}

	public function dependencies()
	{
		$this->depend('com.nexgenta.eregansu.store');
	}
}

Store defines object_iri; a separate object_identity is unnecessary.


<?php
namespace Youkok\Processors\PopularListing;

use Youkok\Enums\MostPopularElement;
use Youkok\Helpers\CacheHelper;
use Youkok\Helpers\SessionHandler;
use Youkok\Models\Element;

class PopularElementsProcessor extends AbstractPopularListingProcessor
{
    public static function fromDelta($delta, $cache, $limit)
    {
        $ids = CacheHelper::getMostPopularElementsFromDelta($cache, $delta, $limit);
        if (empty($ids)) {
            return [];
        }

        return static::idListToElements($ids);
    }

    public static function fromSessionHandler(SessionHandler $sessionHandler)
    {
        return new PopularElementsProcessor($sessionHandler, 'most_popular_element');
    }

    private static function idListToElements(array $ids)
    {
        $elements = [];
        foreach ($ids as $id => $downloads) {
            $element = Element::fromId($id, ['id', 'name', 'slug', 'uri', 'link', 'empty', 'parent']);
            $element->_downloads = (string) $downloads;

            $elements[] = $element;
        }
        return $elements;
    }
}

<?php
namespace Youkok\Processors\PopularListing;

use Youkok\Enums\MostPopularElement;
use Youkok\Helpers\CacheHelper;
use Youkok\Helpers\SessionHandler;
use Youkok\Models\Element;

class PopularElementsProcessor extends AbstractPopularListingProcessor
{
    public static function fromDelta($delta, $cache, $limit)
    {
        $ids = CacheHelper::getMostPopularElementsFromDelta($cache, $delta, $limit);
        if (empty($ids)) {
            return [];
        }

        return static::idListToElements($ids);
    }

    public static function fromSessionHandler(SessionHandler $sessionHandler)
    {
        return new PopularElementsProcessor($sessionHandler, 'most_popular_element');
    }

    private static function idListToElements(array $ids)
    {
        $elements = [];
        foreach ($ids as $id => $downloads) {
            $element = Element::fromId($id, ['id', 'name', 'slug', 'uri', 'link', 'empty', 'parent', 'checksum']);
            $element->_downloads = (string) $downloads;

            $elements[] = $element;
        }
        return $elements;
    }
}

Fix links to popular elements

Fix links to popular elements


  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()
    ));
  }

  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() ?>AdminExport',
      'module' => $this->getDmModule()
    ));
  }

Fix export class name in generated admin modules


<?php

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

class AddLasteditorGeodataLiterature extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('geodata', function (Blueprint $table) {
            $table->text('lasteditor');
        });
        Schema::table('literature', function (Blueprint $table) {
            $table->text('lasteditor');
        });
    }

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

<?php

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

class AddLasteditorGeodataLiterature extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('geodata', function (Blueprint $table) {
            $table->text('lasteditor')->default('');
        });
        Schema::table('literature', function (Blueprint $table) {
            $table->text('lasteditor')->default('');
        });
    }

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

Set default value for lasteditor

Set default value for lasteditor


<?php

namespace ScottRobertson\Scrutiny\Mock;

class Service
{
    public function getData($key)
    {
        return $key;
    }

    public function getTime()
    {
        return time();
    }

    public function getMessageFromEvent()
    {
        return 'up';
    }
}

<?php

namespace ScottRobertson\Scrutiny\Mock;

class Service
{
    public function getData($key)
    {
        return $key;
    }

    public function getTime()
    {
        return time();
    }

    public function getMessageFromEvent()
    {
        return 'up';
    }

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

Add getName to service mock

Add getName to service mock


<?php
/*
Plugin Name: Random Keywords
Plugin URI: http://yourls.org/
Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK)
Version: 1.1
Author: Ozh
Author URI: http://ozh.org/
*/

/* Release History:
*
* 1.0 Initial release
* 1.1 Added: don't increment sequential keyword counter & save one SQL query
* Fixed: plugin now complies to character set defined in config.php
*/

global $ozh_random_keyword;

/*
* CONFIG: EDIT THIS
*/

/* Length of random keyword */
$ozh_random_keyword['length'] = 5;

/*
* DO NOT EDIT FARTHER
*/

// Generate a random keyword
yourls_add_filter( 'random_keyword', 'ozh_random_keyword' );
function ozh_random_keyword() {
        global $ozh_random_keyword;
        $possible = yourls_get_shorturl_charset() ;
        $str='';
        while (strlen($str) < $ozh_random_keyword['length']) {
                $str .= substr($possible, rand(0,strlen($possible)),1);
        }
        return $str;
}

// Don't increment sequential keyword tracker
yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' );
function ozh_random_keyword_next_decimal( $next ) {
        return ( $next - 1 );
}

<?php
/*
Plugin Name: Random Keywords
Plugin URI: http://yourls.org/
Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK)
Version: 1.1
Author: Ozh
Author URI: http://ozh.org/
*/

/* Release History:
*
* 1.0 Initial release
* 1.1 Added: don't increment sequential keyword counter & save one SQL query
* Fixed: plugin now complies to character set defined in config.php
*/

global $ozh_random_keyword;

/*
* CONFIG: EDIT THIS
*/

/* Length of random keyword */
$ozh_random_keyword['length'] = 5;

/*
* DO NOT EDIT FARTHER
*/

// Generate a random keyword
yourls_add_filter( 'random_keyword', 'ozh_random_keyword' );
function ozh_random_keyword() {
        global $ozh_random_keyword;
        $possible = yourls_get_shorturl_charset() ;
        $str='';
        while (strlen($str) < $ozh_random_keyword['length']) {
                $str .= substr($possible, rand(0,strlen($possible)-1),1);
        }
        return $str;
}

// Don't increment sequential keyword tracker
yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' );
function ozh_random_keyword_next_decimal( $next ) {
        return ( $next - 1 );
}

Fix getting random character from charset

If strlen($possible) is for example 36, rand could also return 36. But substr starts with position 0. So we have to subtract 1 from strlen($possible).