<?php

use Illuminate\Database\Seeder;

class MinecraftVersionsSeeder extends Seeder
{
    private $versionsByType = [
        'PC' => [
            4   => '1.7.2',
            5   => '1.7.10',
            47  => '1.8',
            107 => '1.9',
            210 => '1.10',
        ],
        'PE' => [
        ]
    ];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        foreach ($this->versionsByType as $type => $versions) {
            foreach ($versions as $protocol_id => $name) {
                $exists = DB::table('versions')->where('type', $type)->where('name', $name)->exists();
                if (!$exists) {
                    try {
                        DB::table('versions')->insert([
                            'type'        => $type,
                            'protocol_id' => $protocol_id,
                            'name'        => $name,
                        ]);
                    } catch (\Illuminate\Database\QueryException $e) {
                        /*
                         * Ignore duplicate entry exception
                         */
                        if ($e->getCode() != 23000 /* ER_DUP_CODE */) {
                            throw $e;
                        }
                    }
                }
            }
        }
    }
}

<?php

use Illuminate\Database\Seeder;

class MinecraftVersionsSeeder extends Seeder
{
    private $versionsByType = [
        'PC' => [
            5   => '1.7.10',
            47  => '1.8',
            107 => '1.9',
            210 => '1.10',
            315 => '1.11',
            335 => '1.12',
        ],
        'PE' => [
        ]
    ];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        foreach ($this->versionsByType as $type => $versions) {
            foreach ($versions as $protocol_id => $name) {
                $exists = DB::table('versions')->where('type', $type)->where('name', $name)->exists();
                if (!$exists) {
                    try {
                        DB::table('versions')->insert([
                            'type'        => $type,
                            'protocol_id' => $protocol_id,
                            'name'        => $name,
                        ]);
                    } catch (\Illuminate\Database\QueryException $e) {
                        /*
                         * Ignore duplicate entry exception
                         */
                        if ($e->getCode() != 23000 /* ER_DUP_CODE */) {
                            throw $e;
                        }
                    }
                }
            }
        }
    }
}

Remove 1.7.2 and add 1.11/1.12

Remove 1.7.2 and add 1.11/1.12


<?php

namespace Honeybee\Infrastructure\Security\Auth;

class CryptedPasswordHandler implements PasswordHandlerInterface
{
    public function hash($password)
    {
        $options = [
            'cost' => 11,
            'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)
        ];

        return password_hash($password, PASSWORD_BCRYPT, $options);
    }

    public function verify($password, $challenge)
    {
        return password_verify($password, $challenge);
    }
}

<?php

namespace Honeybee\Infrastructure\Security\Auth;

class CryptedPasswordHandler implements PasswordHandlerInterface
{
    public function hash($password)
    {
        $options = [
            'cost' => 11
        ];

        return password_hash($password, PASSWORD_BCRYPT, $options);
    }

    public function verify($password, $challenge)
    {
        return password_verify($password, $challenge);
    }
}

Fix PHP 7.0.* warning for password_hash deprecated option

From php.net:
- The salt option has been deprecated as of PHP 7.0.0.
  It is now preferred to simply use the salt that is generated by default

closes #80


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@php
    $translatedPages = [];
    foreach ($page->availableLocales() as $l) {
        $translatedPages[$l] = wiki_url($page->path, $l);
    }
@endphp

@extends('master', [
    'translatedPages' => $translatedPages,
])

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@php
    $translatedPages = [];
    foreach ($page->availableLocales() as $l) {
        $translatedPages[$l] = wiki_url($page->path, $l);
    }
@endphp

@extends('master', [
    'canonicalUrl' => $page->isVisible() ? wiki_url($page->path, $page->locale) : null,
    'translatedPages' => $translatedPages,
])

Add canonical url for wiki page

Add canonical url for wiki page


<?php
$home = drush_server_home();
// Solve the key file to use
$path = explode('/', dirname(__FILE__));
array_pop($path);
$path[] = '/../.vagrant';
$path = implode('/', $path);
$key = shell_exec('find ' . $path . ' -iname private_key');
if (!$key) {
  $key = $home . '/.vagrant.d/insecure_private_key';
}
$key = rtrim($key);

$aliases['local'] = array(
  'uri' => 'https://local.ansibleref.com',
  'parent' => '@parent',
  'site' => 'ansibleref',
  'env' => 'vagrant',
  'root' => '/vagrant/drupal/current/web',
  'remote-host' => 'local.ansibleref.com',
  'remote-user' => 'vagrant',
  'ssh-options' => '-i ' . $key,
);

<?php
$home = drush_server_home();
// Solve the key file to use
$path = explode('/', dirname(__FILE__));
array_pop($path);
$path[] = '/../.vagrant';
$path = implode('/', $path);
$key = shell_exec('find ' . $path . ' -iname private_key');
if (!$key) {
  $key = $home . '/.vagrant.d/insecure_private_key';
}
$key = rtrim($key);

$aliases['local'] = array(
  'uri' => 'https://local.ansibleref.com',
  'parent' => '@parent',
  'site' => 'ansibleref',
  'env' => 'vagrant',
  'root' => '/vagrant/drupal/current/web',
  'remote-host' => 'local.ansibleref.com',
  'remote-user' => 'vagrant',
  'ssh-options' => '-i ' . $key,
  'path-aliases' => array(
    '%files' => '/vagrant/drupal/files',
    '%dump-dir' => '/home/vagrant',
  ),
);
);

Add some useful settings to local vagrant alias example.


<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\ElementInterface;

class TextConverter implements ConverterInterface
{
    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $value = $element->getValue();

        $markdown = preg_replace('~\s+~', ' ', $value);

        //escape the following characters: '*', '_' and '\'
        $markdown = preg_replace('~([*_\\\\])~', '\\\\$1', $markdown);

        $markdown = preg_replace('~^#~', '\\\\#', $markdown);

        if ($markdown === ' ') {
            $next = $element->getNext();
            if (!$next || $next->isBlock()) {
                $markdown = '';
            }
        }

        return $markdown;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('#text');
    }
}

<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\ElementInterface;

class TextConverter implements ConverterInterface
{
    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $value = $element->getValue();

        $markdown = preg_replace('~\s+~u', ' ', $value);

        //escape the following characters: '*', '_' and '\'
        $markdown = preg_replace('~([*_\\\\])~u', '\\\\$1', $markdown);

        $markdown = preg_replace('~^#~u', '\\\\#', $markdown);

        if ($markdown === ' ') {
            $next = $element->getNext();
            if (!$next || $next->isBlock()) {
                $markdown = '';
            }
        }

        return $markdown;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('#text');
    }
}

Add UTF flag to preg_replace

Add UTF flag to preg_replace


<?php

/** Change it if needed */
define( 'HOME_URL',     'http://' . $_SERVER['HTTP_HOST'] );
define( 'APACHE_DIR',   '/etc/apache2' );
define( 'PROJECTS_DIR', realpath( '..' ) );

/** Add here the name of the virtual hosts files to be ignored */
$ignore    = array(
	'000-default.conf',
	'default-ssl.conf',
	'README.md',
	'LICENSE'
);

<?php

/** Change it if needed */
define( 'HOME_URL',     'http://' . $_SERVER['HTTP_HOST'] );
define( 'APACHE_DIR',   '/etc/apache2' );
define( 'PROJECTS_DIR', realpath( '..' ) );

/** Add here the name of the virtual hosts files to be ignored */
$ignore    = array(
	'000-default.conf',
	'default-ssl.conf'
);

Remove some items from ignore array

Remove some items from ignore array


<?php
// Version: 2.1 RC2; Settings

global $settings;

$txt['theme_thumbnail_href'] = '%1$s/thumbnail.png';
$txt['theme_description'] = 'The default theme from Simple Machines.

Author: The Simple Machines Team';

?>

<?php
// Version: 2.1 RC2; Settings

global $settings;

// argument(s): images_url as saved in settings
$txt['theme_thumbnail_href'] = '%1$s/thumbnail.png';
$txt['theme_description'] = 'The default theme from Simple Machines.

Author: The Simple Machines Team';

?>

Add context comment for $txt['theme_thumbnail_href']

Signed-off-by: Christopher 'm4z' Holm <38073e896c2d24ee83797bcfa758b496d851ce61@gmail.com>


<?php

class Denkmal_Model_UserTest extends CMTest_TestCase {

    public function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testCreate() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        $this->assertRow('denkmal_model_user', null, 1);
        $this->assertSame('foo@bar', $user->getEmail());
        $this->assertSame('foo', $user->getUsername());
    }

    public function testGetSetUsername() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');

        $user->setUsername('bar');
        $this->assertSame('bar', $user->getUsername());
    }

    public function testAuthenticate() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        $authenticatedUser = Denkmal_Model_User::authenticate('foo@bar', 'pass');
        $this->assertEquals($user, $authenticatedUser);
    }

    /**
     * @expectedException CM_Exception_AuthFailed
     */
    public function testAuthenticateIncorrectLogin() {
        Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        Denkmal_Model_User::authenticate('foo@bar', 'bar');
    }
}

<?php

class Denkmal_Model_UserTest extends CMTest_TestCase {

    public function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testCreate() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        $this->assertRow('denkmal_model_user', null, 1);
        $this->assertSame('foo@bar', $user->getEmail());
        $this->assertSame('foo', $user->getUsername());
    }

    /**
     * @expectedException CM_Db_Exception
     */
    public function testCreateDuplicateUsername() {
        Denkmal_Model_User::create('foo@example.com', 'foo', 'pass');
        Denkmal_Model_User::create('bar@example.com', 'foo', 'pass');
    }

    public function testGetSetUsername() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');

        $user->setUsername('bar');
        $this->assertSame('bar', $user->getUsername());
    }

    public function testAuthenticate() {
        $user = Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        $authenticatedUser = Denkmal_Model_User::authenticate('foo@bar', 'pass');
        $this->assertEquals($user, $authenticatedUser);
    }

    /**
     * @expectedException CM_Exception_AuthFailed
     */
    public function testAuthenticateIncorrectLogin() {
        Denkmal_Model_User::create('foo@bar', 'foo', 'pass');
        Denkmal_Model_User::authenticate('foo@bar', 'bar');
    }
}

Add test for duplicate username

Add test for duplicate username


<?php
namespace CouchDB\Tests\Http;

use CouchDB\Tests\TestCase;
use CouchDB\Http\SocketClient;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class SocketClientTest extends TestCase
{
    protected function setUp()
    {
        $this->client = $this->getTestClient();
    }

    public function testConnect()
    {
        $this->assertFalse($this->client->isConnected());
        $this->client->connect();
        $this->assertTrue($this->client->isConnected());
    }

    public function testPutRequest()
    {
        $this->client->connect();
        $response = $this->client->request('/test', 'PUT');
        $this->assertTrue($response->isSuccessful());
    }

    public function testPostRequest()
    {
        $this->client->connect();
        $response = $this->client->request('/_all_dbs', 'GET');
        $this->assertInstanceOf('\\CouchDB\\Http\\Response\ResponseInterface', $response);
        $this->assertTrue($response->isSuccessful());
        $this->assertInternalType('string', $response->getContent());
    }

    protected function getTestClient()
    {
        static $c;
        if (null === $c) {
            $c = new SocketClient();
        }
        return $c;
    }
}

<?php
namespace CouchDB\Tests\Http;

use CouchDB\Tests\TestCase;
use CouchDB\Http\SocketClient;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class SocketClientTest extends TestCase
{
    protected function setUp()
    {
        $this->markTestSkipped('Performance to low');
        $this->client = $this->getTestClient();
    }

    public function testConnect()
    {
        $this->assertFalse($this->client->isConnected());
        $this->client->connect();
        $this->assertTrue($this->client->isConnected());
    }

    public function testPutRequest()
    {
        $this->client->connect();
        $response = $this->client->request('/test', 'PUT');
        $this->assertTrue($response->isSuccessful());
    }

    public function testPostRequest()
    {
        $this->client->connect();
        $response = $this->client->request('/_all_dbs', 'GET');
        $this->assertInstanceOf('\\CouchDB\\Http\\Response\ResponseInterface', $response);
        $this->assertTrue($response->isSuccessful());
        $this->assertInternalType('string', $response->getContent());
    }

    protected function getTestClient()
    {
        static $c;
        if (null === $c) {
            $c = new SocketClient();
        }
        return $c;
    }
}

Mark the socket client as skipped

Mark the socket client as skipped


<?php

function ipadPopUpScript(){
?>

<?php
}

function ipadPopUpModal(){
?>
  jQuery('#colophon').after('

We'+
  'are opening a new tab.

The following link will open a'+
  ' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
  'zine from there.

If you have any items in your shopping cart, they '+
  'won\'t go anywhere (as long as you don\'t close the window).
<\/a>×<\/a><\/div>');
<?php
}

function PopUpModal(){
  ipadPopUpScript();
  ipadPopUpModal();
}

add_action('wp_footer', 'PopUpModal', 33);

?>

<?php

function ipadPopUpScript(){
?>
  jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp');
<?php
}

function ipadPopUpModal(){
?>
  jQuery('#colophon').after('

We'+
  'are opening a new tab.

The following link will open a'+
  ' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
  'zine from there.

If you have any items in your shopping cart, they '+
  'won\'t go anywhere (as long as you don\'t close the window).
<\/a>×<\/a><\/div>');
<?php
}

function PopUpModal(){
  ?>

  <?php
}

add_action('wp_footer', 'PopUpModal', 33);

?>

Add modal for ipad links

Add modal for ipad links


<?
include '../scat.php';
include '../lib/catalog.php';

$id= (int)$_REQUEST['id'];
$name= $_REQUEST['name'];
$slug= $_REQUEST['slug'];

try {
  $product= Model::factory('Product')->find_one($id);
  if ($name)
    $product->name= $name;
  if ($slug)
    $product->slug= $slug;
  if (array_key_exists('active', $_REQUEST))
    $product->active= (int)$_REQUEST['active'];
  $product->save();
} catch (\PDOException $e) {
  die_jsonp($e->getMessage());
}

echo jsonp($product->as_array());

<?
include '../scat.php';
include '../lib/catalog.php';

$id= (int)$_REQUEST['id'];
$name= $_REQUEST['name'];
$slug= $_REQUEST['slug'];

try {
  $product= Model::factory('Product')->find_one($id);

  $old_slug= "";
  if (($product->slug && $_REQUEST['slug'] != $product->slug) ||
      ($product->department_id &&
       $_REQUEST['department_id'] != $product->department_id))
  {
    // XXX handle rename
    $old_slug= '';
  }

  foreach ($_REQUEST as $k => $v) {
    if (in_array($k, array('department_id', 'brand_id', 'name', 'description',
                           'slug', 'image', 'variation_style', 'active')))
    {
      $product->set($k, $v);
    }
  }

  $product->save();

  // XXX Save redirect information
  if ($old_slug) {
  }

} catch (\PDOException $e) {
  die_jsonp($e->getMessage());
}

echo jsonp($product->as_array());

Handle updates of all product fields

Handle updates of all product fields

Doesn’t record renames yet for redirects


<?php

namespace Tylercd100\LERN\Models;

use Illuminate\Database\Eloquent\Model;

class ExceptionModel extends Model {
    protected $table;
    protected $guarded = array('id');

    public function __construct(array $attributes = [])
    {
        $this->table = config('lern.record.table');
        parent::__construct($attributes);
    }

    public function setDataAttribute($value) {
        $this->attributes['data'] = json_encode($value);
    }

    public function getDataAttribute($value) {
        return json_decode($value);
    }
}

<?php

namespace Tylercd100\LERN\Models;

use Illuminate\Database\Eloquent\Model;

class ExceptionModel extends Model {
    protected $table;
    protected $guarded = array('id');

    protected $casts = array(
        'data' => 'array'
    );

    public function __construct(array $attributes = [])
    {
        $this->table = config('lern.record.table');
        parent::__construct($attributes);
    }
}

Use Attribute Casting in Exception Model

No need for the boilerplate code, Laravel 5.0+ has support for `array` type cast which handles JSON properly.


<?php get_template_part('templates/page', 'header'); ?>

<?php if (!have_posts()) : ?>

    <?php _e('Sorry, no results were found.', 'roots'); ?>

  <?php get_search_form(); ?>
<?php endif; ?>

<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/content', get_post_format()); ?>
<?php endwhile; ?>

<?php if ($wp_query->max_num_pages > 1) : ?>

<?php next_posts_link(__('← Older posts', 'roots')); ?>

<?php previous_posts_link(__('Newer posts →', 'roots')); ?>

<?php endif; ?>

<?php get_template_part('templates/page', 'header'); ?>

<?php if (!have_posts()) : ?>
  <div class="alert alert-warning">
    <?php _e('Sorry, no results were found.', 'roots'); ?>
  </div>
<?php endif; ?>

<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/content', get_post_format()); ?>
<?php endwhile; ?>

<?php get_template_part('templates/pagination');

Remove the search form when it returns no results and add a pagination


<?php
header('Content-Type: application/json');
$ret = new array();
$ret["request"] = _GET['request'];
echo json_encode($ret);
?>

Change test API to JSON

Change test API to JSON


<?php

namespace Kunstmaan\AdminBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
	/**
	 * @Route("/", name="KunstmaanAdminBundle_homepage")
	 * @Template()
	 */
    public function indexAction()
    {
        return $this->redirect($this->generateUrl("KunstmaanAdminBundle_pages"));;
    }
}

<?php

namespace Kunstmaan\AdminBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
	/**
	 * @Route("/", name="KunstmaanAdminBundle_homepage")
	 * @Template()
	 */
    public function indexAction()
    {
        return array();
    }
}

Fix for default index, this shouldn't be the pages overview


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2016, 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\MenuBundle\Configuration;

/**
 * Menu configuration
 */
class MenuConfiguration
{
    /**
     * @var \Darvin\MenuBundle\Configuration\Menu[]
     */
    private $menus;

    /**
     * @param array[] $configs Configs
     */
    public function __construct(array $configs)
    {
        $this->menus = [];

        foreach ($configs as $config) {
            $this->menus[] = new Menu($config['alias'], $config['breadcrumbs']);
        }
    }

    /**
     * @return \Darvin\MenuBundle\Configuration\Menu[]
     */
    public function getMenus()
    {
        return $this->menus;
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2016, 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\MenuBundle\Configuration;

/**
 * Menu configuration
 */
class MenuConfiguration
{
    /**
     * @var \Darvin\MenuBundle\Configuration\Menu[]
     */
    private $menus;

    /**
     * @param array[] $configs Configs
     *
     * @throws \Darvin\MenuBundle\Configuration\ConfigurationException
     */
    public function __construct(array $configs)
    {
        $this->menus = [];

        foreach ($configs as $config) {
            $alias = $config['alias'];

            if (isset($this->menus[$alias])) {
                throw new ConfigurationException(sprintf('Menu with alias "%s" already exists.', $alias));
            }

            $this->menus[$alias] = new Menu($alias, $config['breadcrumbs']);
        }
    }

    /**
     * @return \Darvin\MenuBundle\Configuration\Menu[]
     */
    public function getMenus()
    {
        return $this->menus;
    }
}

Throw exception in menu configuration class if menu with same alias already exists.


<?php
use Mongovel\Model;

class IrcLog extends Model
{
	protected $collectionName = 'logs';

	/**
	 * Get the log's message
	 *
	 * @return  string
	 */
	public function getText()
	{
		return Lang::get('messages.'.$this->type, array(
			'username' => $this->nick,
			'message'  => $this->text,
		));
	}

	/**
	 * Returns the hour of the entry
	 *
	 * @return  string
	 */
	public function getHour()
	{
		return date('H:s', $this->time->sec);
	}
}

<?php
use Mongovel\Model;

class IrcLog extends Model
{
	protected $collectionName = 'logs';

	/**
	 * Get the log's message
	 *
	 * @return  string
	 */
	public function getText()
	{
		return Lang::get('messages.'.$this->type, array(
			'username' => $this->nick,
			'message'  => $this->text,
		));
	}

	/**
	 * Returns the hour of the entry
	 *
	 * @return  string
	 */
	public function getHour()
	{
		return date('H:i', $this->time->sec);
	}
}

Fix variable for minutes in entries time


<?php
# Signed Authentication has been deprecated.
# Please check out the authentication wiki page: http://apiwiki.seomoz.org/HttpBasicAuth
$objectURL = "www.example.com/";
$accessID = "my access id";
$secretKey = "my secret key";
$expires = mktime() + 300;  // The request is good for the next 5 minutes, or 300 seconds from now.
$stringToSign = $accessID."\n".$expires;

// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);

// We need to base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$urlToFetch = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($objectURL)."?AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature;

// You don't have to use fopen and can't in some scenarios. CURL is a better choice for production.
$handle = fopen($urlToFetch, "r");
$contents = '';

while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}

fclose($handle);
echo $contents;

?>

<?php
# Please check out the authentication wiki page: http://apiwiki.seomoz.org/w/page/29574176/SignedAuthentication
$objectURL = "www.example.com/";
$accessID = "my access id";
$secretKey = "my secret key";
$expires = mktime() + 300;  // The request is good for the next 5 minutes, or 300 seconds from now.
$stringToSign = $accessID."\n".$expires;

// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);

// We need to base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$urlToFetch = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($objectURL)."?AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature;

// You don't have to use fopen and can't in some scenarios. CURL is a better choice for production.
$handle = fopen($urlToFetch, "r");
$contents = '';

while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}

fclose($handle);
echo $contents;

?>

Remove deprication warning, which shouldn't have been there in the first place.


<?php
namespace Respect\Validation\Rules;

class Digit extends AbstractCtypeRule
{
    public $additionalChars = "\n\r\t ";
    protected function ctypeFunction($input)
    {
        return ctype_digit($input);
    }
}

<?php
namespace Respect\Validation\Rules;

class Digit extends AbstractCtypeRule
{
    protected function ctypeFunction($input)
    {
        return ctype_digit($input);
    }
}

Remove redundant and filter is inherited


<?php

namespace Purethink\CMSBundle\Repository;

use Doctrine\ORM\EntityRepository;

class LanguageRepository extends EntityRepository
{
    public function getPublicLanguages()
    {
        $qb = $this->createQueryBuilder('a')
            ->addSelect('m')
            ->leftJoin('a.media', 'm')
            ->where('a.enabled = true')
            ->orderBy('a.position');

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

<?php

namespace Purethink\CMSBundle\Repository;

use Doctrine\ORM\EntityRepository;

class LanguageRepository extends EntityRepository
{
    public function getLastPosition()
    {
        return (int)$this->createQueryBuilder('a')
            ->select('MAX(a.position)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function getPublicLanguages()
    {
        $qb = $this->createQueryBuilder('a')
            ->addSelect('m')
            ->leftJoin('a.media', 'm')
            ->where('a.enabled = true')
            ->orderBy('a.position');

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

Fix query for get max position

Fix query for get max position


<?php

namespace Drupal\ga_front;

class FrontUtils
{

    public static function getPreliveConfiguration()
    {
        $config = \Drupal::config('ga_ticket.settings');

        $variables['edition_name'] = $config->get('edition_name');
        $variables['event_title'] = $config->get('event_title');
        $variables['event_text'] = $config->get('event_text');
        $variables['event_cta'] = $config->get('event_cta');
        $variables['planning_text'] = $config->get('planning_text');
        $variables['planning_cta'] = $config->get('planning_cta');
        $variables['ticket_text'] = $config->get('ticket_text');
        $variables['ticket_cta'] = $config->get('ticket_cta');

        return $variables;
    }
}

<?php

namespace Drupal\ga_front;

class FrontUtils
{

    public static function getPreliveConfiguration()
    {
        $config = \Drupal::config('ga_front.prelive.settings');

        $variables['edition_name'] = $config->get('edition_name');
        $variables['event_title'] = $config->get('event_title');
        $variables['event_text'] = $config->get('event_text');
        $variables['event_cta'] = $config->get('event_cta');
        $variables['planning_text'] = $config->get('planning_text');
        $variables['planning_cta'] = $config->get('planning_cta');
        $variables['ticket_text'] = $config->get('ticket_text');
        $variables['ticket_cta'] = $config->get('ticket_cta');

        return $variables;
    }
}

Fix bug on homepage configuration

Fix bug on homepage configuration


@extends('core')

@section('subnav')

    @include('event::nav')

@endsection

{{-- Placeholder for view sections specific to this package --}}

@extends('core')

@section('subnav')

    @include('-package-::admin.nav')

@endsection

{{-- Placeholder for view sections specific to this package --}}

Update laravel/package-scaffolding/src/Views/admin/layout with placeholder for package name


<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\CoreBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Base class to define Bundle Extension
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
abstract class ASFExtension extends Extension
{
	/**
	 * Maps parameters in container
	 *
	 * @param ContainerBuilder $container
	 * @param string $rootNodeName
	 * @param array $config
	 */
	public function mapsParameters(ContainerBuilder $container, $rootNodeName, $config)
	{
		foreach($config as $name => $value) {
			if ( is_array($value) ) {
				$this->mapsParameters($container, $rootNodeName . '.' . $name, $value);
			} else {
				$container->setParameter($rootNodeName . '.' . $name, $value);
			}
		}
	}
}

<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\CoreBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Base class to define Bundle Extension
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
abstract class ASFExtension extends Extension
{
	/**
	 * Maps parameters in container
	 *
	 * @param ContainerBuilder $container
	 * @param string $rootNodeName
	 * @param array $config
	 */
	public function mapsParameters(ContainerBuilder $container, $rootNodeName, $config)
	{
		foreach($config as $name => $value) {
			if ( is_array($value) ) {
				$this->mapsParameters($container, $rootNodeName . '.' . $name, $value);
			} else {
				$container->setParameter($rootNodeName . '.' . $name, $value);
			}
		}
	}

	/**
	 * Check the validity of a path done in bundle's configuration parameter
	 *
	 * @param string $path
	 * @param ContainerBuilder $container
	 *
	 * @return boolean
	 */
	public function checkPath($path, ContainerBuilder $container)
	{
		$path = str_replace('%kernel.root_dir%', $container->getParameter('kernel.root_dir'), $path);
		return file_exists($path);
	}
}

Add method for check file path in bundle's configurations


<?php
/**
 * Created by PhpStorm.
 * User: s216121
 * Date: 12.10.16
 * Time: 09:34
 */

namespace AppBundle\Controller;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class TraitController extends Controller
{
    /**
     * @param $request Request
     * @return \Symfony\Component\HttpFoundation\Response
     * @Route("/{dbversion}/trait/search", name="trait_search")
     */
    public function searchAction(Request $request, $dbversion){
        return $this->render('trait/search.html.twig', ['type' => 'trait', 'dbversion' => $dbversion, 'title' => 'Trait Search']);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: s216121
 * Date: 12.10.16
 * Time: 09:34
 */

namespace AppBundle\Controller;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class TraitController extends Controller
{
    /**
     * @param $request Request
     * @return \Symfony\Component\HttpFoundation\Response
     * @Route("/{dbversion}/trait/search", name="trait_search")
     */
    public function searchAction(Request $request, $dbversion){
        return $this->render('trait/search.html.twig', ['type' => 'trait', 'dbversion' => $dbversion, 'title' => 'Trait Search']);
    }

    /**
     * @param Request $request
     * @param $dbversion
     * @param $trait_id
     * @return Response
     * @Route("/{dbversion}/organism/details/{trait_id}", name="trait_details", options={"expose" = true})
     */
    public function detailsAction(Request $request, $dbversion, $trait_id){

    }
}

Create dummy route for trait_details

Create dummy route for trait_details


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2016, 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\EntityNamer;

/**
 * Entity namer
 */
interface EntityNamerInterface
{
    /**
     * @param object|string $entityOrClass Entity object or class
     *
     * @return string
     */
    public function name($entityOrClass);
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2016, 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\EntityNamer;

/**
 * Entity namer
 */
interface EntityNamerInterface
{
    /**
     * @param object|string $entityOrClass Entity object or class
     *
     * @return string
     */
    public function name($entityOrClass): string;
}

Enable strict types in entity namer interface.


<?php

namespace App\Models\Collections;

// @TODO: Make Images not Assets, both in the CDS and the DA?
class Image extends Asset
{

    // Note: Not all Images are meant to be associated w/ Artworks
    public function artworks()
    {

        return $this->belongsToMany('App\Models\Collections\Artwork');

    }

    /**
     * Turn this model object into a generic array.
     *
     * @TODO Image currently extends Asset, which means it contains IR fields.
     * However, only 1547 of 103518 images are interpretive resources.
     * We need to think more about abstracting away these shared fields.
     * Maybe think of Interpretive Resource as a container..?
     *
     * @return array
     */
    public function transformAsset()
    {

        return [

            // 'type' => $item->type,
            'iiif_url' =>  env('IIIF_URL', 'https://localhost/iiif') . '/' . $this->lake_guid . '/info.json',
            'is_preferred' => (bool) $this->preferred,
            'artwork_ids' => $this->artworks->pluck('citi_id')->all(),
            'artwork_titles' => $this->artworks()->pluck('title'),

        ];

    }

}

<?php

namespace App\Models\Collections;

// @TODO: Make Images not Assets, both in the CDS and the DA?
class Image extends Asset
{

    protected $appends = ['iiif_url'];

    // Note: Not all Images are meant to be associated w/ Artworks
    public function artworks()
    {

        return $this->belongsToMany('App\Models\Collections\Artwork');

    }

    /**
     * Turn this model object into a generic array.
     *
     * @TODO Image currently extends Asset, which means it contains IR fields.
     * However, only 1547 of 103518 images are interpretive resources.
     * We need to think more about abstracting away these shared fields.
     * Maybe think of Interpretive Resource as a container..?
     *
     * @return array
     */
    public function transformAsset()
    {

        return [

            // 'type' => $item->type,
            'iiif_url' =>  $this->iiif_url,
            'is_preferred' => (bool) $this->preferred,
            'artwork_ids' => $this->artworks->pluck('citi_id')->all(),
            'artwork_titles' => $this->artworks()->pluck('title'),

        ];

    }

    /**
     * Get the IIIF URL.
     *
     * @TODO Change this link from info.json into just the `@id` attribute, i.e. strip `/info.json'
     * We need to wait for the LAKE team to fix a redirect bug before we can implement that change.
     *
     * @return string
     */
    public function getIiifUrlAttribute()
    {

        return env('IIIF_URL', 'https://localhost/iiif') . '/' . $this->lake_guid . '/info.json';

    }

}

Use accessor to abstract iiif_url attribute


<?php namespace GeneaLabs\LaravelGovernor\Http\Controllers\Nova;

use GeneaLabs\LaravelGovernor\Http\Controllers\Controller;
use GeneaLabs\LaravelGovernor\Http\Requests\StoreRoleRequest;
use GeneaLabs\LaravelGovernor\Http\Requests\UpdateRoleRequest;
use GeneaLabs\LaravelGovernor\Role;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;

class RoleController extends Controller
{
    public function __construct()
    {
        $this->middleware([]);
        // $this->middleware(["nova"]);
    }

    public function index() : Collection
    {
        $roleClass = config("genealabs-laravel-governor.models.role");

        return (new $roleClass)
            ->with("permissions", "users")
            ->get();
    }

    public function store(StoreRoleRequest $request) : Response
    {
        $request->process();

        return response(null, 204);
    }

    public function show(Role $role) : Role
    {
        $role->load("permissions.entity");

        return $role;
    }

    public function update(UpdateRoleRequest $request, Role $role) : Response
    {
        $request->process();

        return response(null, 204);
    }

    public function destroy(Role $role) : Response
    {
        $role->delete();

        return response(null, 204);
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Http\Controllers\Nova;

use GeneaLabs\LaravelGovernor\Http\Controllers\Controller;
use GeneaLabs\LaravelGovernor\Http\Requests\StoreRoleRequest;
use GeneaLabs\LaravelGovernor\Http\Requests\UpdateRoleRequest;
use GeneaLabs\LaravelGovernor\Role;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;

class RoleController extends Controller
{
    public function __construct()
    {
        $this->middleware([]);
        // $this->middleware(["nova"]);
    }

    public function index() : Collection
    {
        $roleClass = config("genealabs-laravel-governor.models.role");

        return (new $roleClass)
            ->with("permissions", "users")
            ->get();
    }

    public function store(StoreRoleRequest $request) : Response
    {
        $request->process();

        return response(null, 204);
    }

    public function show($id) : Role
    {
        $roleClass = config("genealabs-laravel-governor.models.role");
        $role = (new $roleClass)
            ->find($id);
        $role->load("permissions.entity");

        return $role;
    }

    public function update(UpdateRoleRequest $request) : Response
    {
        $request->process();

        return response(null, 204);
    }

    public function destroy($id) : Response
    {
        $roleClass = config("genealabs-laravel-governor.models.role");
        $role = (new $roleClass)
            ->find($id);
        $role->delete();

        return response(null, 204);
    }
}

Fix loading of role to use config class

Fix loading of role to use config class


<?php

namespace ModuleGenerator\PhpGenerator\Constant;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;

final class ConstantType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'name',
            TextType::class,
            [
                'label' => 'Name',
                'required' => true,
                'constraints' => [
                    new NotBlank(),
                ],
            ]
        )->add(
            'value',
            $options['type_class_name'],
            [
                'label' => $options['value_label'],
                'required' => true,
                'constraints' => $options['value_constraints'],
            ]
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => ConstantDataTransferObject::class,
                'label' => 'Constant',
                'required' => true,
                'value_label' => 'Value',
                'value_constraints' => [
                    new NotBlank(),
                ],
            ]
        );
    }
}

<?php

namespace ModuleGenerator\PhpGenerator\Constant;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;

final class ConstantType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'name',
            TextType::class,
            [
                'label' => 'Name',
                'required' => true,
                'constraints' => [
                    new NotBlank(),
                ],
            ]
        )->add(
            'value',
            $options['value_type_class_name'],
            [
                'label' => $options['value_label'],
                'required' => true,
                'constraints' => $options['value_constraints'],
            ]
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => ConstantDataTransferObject::class,
                'label' => 'Constant',
                'required' => true,
                'value_type_class_name' => TextType::class,
                'value_label' => 'Value',
                'value_constraints' => [
                    new NotBlank(),
                ],
            ]
        );
    }
}

Configure mission form type option

Configure mission form type option


<?php

namespace ZfcBase\EventManager;

use Traversable;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;

abstract class EventProvider implements EventManagerAwareInterface
{
    /**
     * @var EventManagerInterface
     */
    protected $events;

    /**
     * Set the event manager instance used by this context
     *
     * @param  EventManagerInterface $events
     * @return mixed
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $identifiers = array(__CLASS__, get_called_class());
        if (isset($this->eventIdentifier)) {
            if ((is_string($this->eventIdentifier))
                || (is_array($this->eventIdentifier))
                || ($this->eventIdentifier instanceof Traversable)
            ) {
                $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
            } elseif (is_object($this->eventIdentifier)) {
                $identifiers[] = $this->eventIdentifier;
            }
            // silently ignore invalid eventIdentifier types
        }
        $events->setIdentifiers($identifiers);
        $this->events = $events;
        return $this;
    }

    /**
     * Retrieve the event manager
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventManagerInterface
     */
    public function events()
    {
        if (!$this->events instanceof EventManagerInterface) {
            $this->setEventManager(new EventManager());
        }
        return $this->events;
    }
}

<?php

namespace ZfcBase\EventManager;

use Traversable;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;

abstract class EventProvider implements EventManagerAwareInterface
{
    /**
     * @var EventManagerInterface
     */
    protected $events;

    /**
     * Set the event manager instance used by this context
     *
     * @param  EventManagerInterface $events
     * @return mixed
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $identifiers = array(__CLASS__, get_called_class());
        if (isset($this->eventIdentifier)) {
            if ((is_string($this->eventIdentifier))
                || (is_array($this->eventIdentifier))
                || ($this->eventIdentifier instanceof Traversable)
            ) {
                $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
            } elseif (is_object($this->eventIdentifier)) {
                $identifiers[] = $this->eventIdentifier;
            }
            // silently ignore invalid eventIdentifier types
        }
        $events->setIdentifiers($identifiers);
        $this->events = $events;
        return $this;
    }

    /**
     * Retrieve the event manager
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!$this->events instanceof EventManagerInterface) {
            $this->setEventManager(new EventManager());
        }
        return $this->events;
    }
}

Fix for EventManager BC breaks

Fix for EventManager BC breaks


<?php namespace professionalweb\payment\contracts\recurring;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;
}

<?php namespace professionalweb\payment\contracts\recurring;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;

    /**
     * Remember payment fo recurring payments
     *
     * @return RecurringPayment
     */
    public function makeRecurring(): self;
}

Add method to recurring interface

Add method to recurring interface


<?php

require_once( dirname( __FILE__ ) . '/B3_RoutesHelper.php' );

class B3_SettingsHelper {

    /**
     * [get_options description]
     * @return [type] [description]
     */
    public function __construct () {

    }

    /**
     * Option getter.
     *
     * By default, options will take their value from WordPress's
     * `get_bloginfo()`.  Options specific to B3 are handled manually.
     *
     * @param  [type] $option [description]
     * @return [type]         [description]
     */
    public function __get( $option ) {
        switch ($option) {
            case 'api_url':
                return home_url( json_get_url_prefix() );

            case 'root_url':
                return get_stylesheet_directory_uri();

            case 'routes':
                $routes = new B3_RoutesHelper();
                return $routes->get_routes();

            case 'site_url':
                return get_bloginfo( 'url' );

            case 'site_path':
                $site_url_components = parse_url( site_url() );
                return (string) $site_url_components['path'];

            case 'wp_url':
                return get_bloginfo( 'wpurl' );

            case 'show_on_front':
            case 'page_on_front':
            case 'page_for_posts':
                return get_option( $option );

            default:
                return get_bloginfo( $option );
        }
    }

}

<?php

require_once( dirname( __FILE__ ) . '/B3_RoutesHelper.php' );

class B3_SettingsHelper {

    /**
     * [get_options description]
     * @return [type] [description]
     */
    public function __construct () {

    }

    /**
     * Option getter.
     *
     * By default, options will take their value from WordPress's
     * `get_bloginfo()`.  Options specific to B3 are handled manually.
     *
     * @param  [type] $option [description]
     * @return [type]         [description]
     */
    public function __get( $option ) {
        switch ($option) {
            case 'api_url':
                return home_url( json_get_url_prefix() );

            case 'root_url':
                return get_stylesheet_directory_uri();

            case 'routes':
                $routes = new B3_RoutesHelper();
                return $routes->get_routes();

            case 'site_url':
                return get_bloginfo( 'url' );

            case 'site_path':
                $site_url_components = parse_url( site_url() );
                return (string) $site_url_components['path'];

            case 'wp_url':
                return get_bloginfo( 'wpurl' );

            case 'show_on_front':
            case 'page_on_front':
            case 'page_for_posts':
                return (int) get_option( $option );

            default:
                return get_bloginfo( $option );
        }
    }

}

Convert page or post to int

Convert page or post to int


<?php

namespace Vend\Statsd\Datadog;

use Vend\Statsd\Metric as BaseMetric;

class Metric extends BaseMetric
{
    /**
     * @var array<string,string>
     */
    protected $tags = [];

    public function __construct($key, $value, $type, array $tags = [])
    {
        parent::__construct($key, $value, $type);

        $this->setTags($tags);
    }

    public function setTags(array $tags = [])
    {
        $this->tags = $tags;
    }

    public function getData()
    {
        $result = parent::getData();

        if (!empty($this->tags)) {
            $tags = [];

            array_walk($this->tags, function ($v, $k) {
                $tags[] = is_integer($k) ? $v : $k . ':' . $v;
            });

            $result .= '|#' . implode(',', $tags);
        }

        return $result;
    }
}

<?php

namespace Vend\Statsd\Datadog;

use Vend\Statsd\Metric as BaseMetric;

class Metric extends BaseMetric
{
    /**
     * @var array<string,string>
     */
    protected $tags = [];

    public function __construct($key, $value, $type, array $tags = [])
    {
        parent::__construct($key, $value, $type);

        $this->setTags($tags);
    }

    public function setTags(array $tags = [])
    {
        $this->tags = $tags;
    }

    public function getData()
    {
        $result = parent::getData();

        if (!empty($this->tags)) {
            $tags = [];

            array_walk($this->tags, function ($tagValue, $tagName) use (&$tags) {
                $tags[] = is_integer($tagName) ? $tagValue : $tagName . ':' . $tagValue;
            });

            $result .= '|#' . implode(',', $tags);
        }

        return $result;
    }
}

Fix tags not being mutated

Fix tags not being mutated


<?php

namespace OpenDominion\Calculators\Dominion\Actions;

use OpenDominion\Contracts\Calculators\Dominion\Actions\RezoningCalculator as RezoningCalculatorContract;

class RezoningCalculator implements RezoningCalculatorContract
{
//    /**
//     * Returns the Dominion's rezoning cost per acre.
//     *
//     * @return int
//     */
//    public function getRezoningPlatinumCost()
//    {
//        return round((($this->getTotalLand() - 250) * 0.6) + 250);
//    }
}

<?php

namespace OpenDominion\Calculators\Dominion\Actions;

use OpenDominion\Contracts\Calculators\Dominion\Actions\RezoningCalculator as RezoningCalculatorContract;
use OpenDominion\Contracts\Calculators\Dominion\LandCalculator;
use OpenDominion\Models\Dominion;

class RezoningCalculator implements RezoningCalculatorContract
{
    /** @var LandCalculator */
    protected $landCalculator;

    /**
     * RezoningCalculator constructor.
     *
     * @param LandCalculator $landCalculator
     */
    public function __construct(LandCalculator $landCalculator)
    {
        $this->landCalculator = $landCalculator;
    }

    /**
     * {@inheritdoc}
     */
    public function getPlatinumCost(Dominion $dominion)
    {
        return (int)round((($this->landCalculator->getTotalLand($dominion) - 250) * 0.6) + 250);
    }

    /**
     * {@inheritdoc}
     */
    public function getMaxAfford(Dominion $dominion)
    {
        return (int)floor($dominion->resource_platinum / $this->getPlatinumCost($dominion));
    }
}

Implement dominion rezoning action calculator


<?php namespace TightenCo\Jigsaw;

use ArrayAccess;
use Illuminate\Support\Collection as BaseCollection;

class IterableObject extends BaseCollection implements ArrayAccess
{
    public function __get($key)
    {
        if (! $this->has($key)) {
            return;
        }

        $element = $this->get($key);

        return is_array($element) ? new self($element) : $element;
    }

    public function offsetGet($key)
    {
        $element = $this->items[$key];

        return is_array($element) ? new self($element) : $element;
    }
}

<?php namespace TightenCo\Jigsaw;

use ArrayAccess;
use Exception;
use Illuminate\Support\Collection as BaseCollection;

class IterableObject extends BaseCollection implements ArrayAccess
{
    public function __get($key)
    {
        if (! $this->has($key)) {
            return;
        }

        $element = $this->get($key);

        return is_array($element) ? new self($element) : $element;
    }

    public function offsetGet($key)
    {
        if (! isset($this->items[$key])) {
            $prefix = $this->_source ? 'Error in ' . $this->_source . ': '  : 'Error: ';
            throw new Exception($prefix . "The key '$key' does not exist.");
        }

        $element = $this->items[$key];

        return is_array($element) ? new self($element) : $element;
    }
}

Throw meaningful error message for missing variables referenced in view


<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_last_file_galleries_info()
{
	return array(
		'name' => tra('Last-modified File Galleries'),
		'description' => tra('Displays the specified number of file galleries, starting from the most recently modified.'),
		'prefs' => array("feature_file_galleries"),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_last_file_galleries($mod_reference, $module_params)
{
	global $smarty, $prefs;
	$filegallib = TikiLib::lib('filegal');
	$ranking = $filegallib->get_files(0, $mod_reference["rows"], 'lastModif_desc', null, $prefs['fgal_root_id'], false, true, false, false);

	$smarty->assign('modLastFileGalleries', $ranking["data"]);
}

<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_last_file_galleries_info()
{
	return array(
		'name' => tra('Last-Modified File Galleries'),
		'description' => tra('Display the specified number of file galleries, starting from the most recently modified.'),
		'prefs' => array("feature_file_galleries"),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_last_file_galleries($mod_reference, $module_params)
{
	global $smarty, $prefs;
	$filegallib = TikiLib::lib('filegal');
	$ranking = $filegallib->get_files(0, $mod_reference["rows"], 'lastModif_desc', null, $prefs['fgal_root_id'], false, true, false, false);

	$smarty->assign('modLastFileGalleries', $ranking["data"]);
}

Tidy up info a little for the PluginModule popup edit form

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40383 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace React\Filesystem;

use React\EventLoop\LoopInterface;
use React\Filesystem\Node;

class Filesystem
{
    protected $filesystem;

    /**
     * @param LoopInterface $loop
     * @param AdapterInterface $adapter
     * @return static
     * @throws NoAdapterException
     */
    public static function create(LoopInterface $loop, AdapterInterface $adapter = null)
    {
        if ($adapter instanceof AdapterInterface) {
            return new static($adapter);
        }

        if (extension_loaded('eio')) {
            return new static(new EioAdapter($loop));
        }

        throw new NoAdapterException();
    }

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

    /**
     * @param string $filename
     * @return Node\File
     */
    public function file($filename)
    {
        return new Node\File($filename, $this->filesystem);
    }

    /**
     * @param string $path
     * @return Node\Directory
     */
    public function dir($path)
    {
        return new Node\Directory($path, $this->filesystem);
    }

    /**
     * @param string $filename
     * @return \React\Promise\PromiseInterface
     */
    public function getContents($filename)
    {
        return $this->file($filename)->getContents();
    }
}

<?php

namespace React\Filesystem;

use React\EventLoop\LoopInterface;
use React\Filesystem\Node;

class Filesystem
{
    protected $filesystem;

    /**
     * @param LoopInterface $loop
     * @param AdapterInterface $adapter
     * @return static
     * @throws NoAdapterException
     */
    public static function create(LoopInterface $loop, AdapterInterface $adapter = null)
    {
        if ($adapter instanceof AdapterInterface) {
            return new static($adapter);
        }

        if (extension_loaded('eio')) {
            return new static(new EioAdapter($loop));
        }

        throw new NoAdapterException();
    }

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

    /**
     * @param string $filename
     * @return Node\File
     */
    public function file($filename)
    {
        return new Node\File($filename, $this->filesystem);
    }

    /**
     * @param string $path
     * @return Node\Directory
     */
    public function dir($path)
    {
        return new Node\Directory($path, $this->filesystem);
    }

    /**
     * @param string $filename
     * @return \React\Promise\PromiseInterface
     */
    public function getContents($filename)
    {
        return $this->file($filename)->getContents();
    }

    /**
     * @param CallInvokerInterface $invoker
     */
    public function setInvoker(CallInvokerInterface $invoker)
    {
        $this->filesystem->setInvoker($invoker);
    }
}

Allow to set invoker through filesystem decorator


<?php
namespace Alsatian\FormBundle\Form;

use Symfony\Component\Form\AbstractType;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

abstract class AbstractRoutableType extends AbstractType
{
    protected $router;
    protected $default_attr_class;

    public function __construct($router,$default_attr_class)
    {
        $this->router = $router;
        $this->default_attr_class = $default_attr_class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('route'=>false,'route_params'=>array()));

        $resolver->setDefault('attr', function(Options $options, $attr){
            if($this->default_attr_class){
                $attr['class'] = $this->default_attr_class;
            }

            if($options['route']){
                $attr['data-ajax--url']=$this->router->generate($options['route'],$options['route_params']);
            }

            return $attr;
        });
    }
}

<?php
namespace Alsatian\FormBundle\Form;

use Symfony\Component\Form\AbstractType;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

abstract class AbstractRoutableType extends AbstractType
{
    protected $router;
    protected $default_attr_class;

    public function __construct($router,$default_attr_class)
    {
        $this->router = $router;
        $this->default_attr_class = $default_attr_class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('route'=>false,'route_params'=>array()));

        $resolver->setNormalizer('attr', function (Options $options, $attr) {
            if($this->default_attr_class){
                if (array_key_exists('class', $attr)) {
                    $attr['class'] = $this->default_attr_class . ' ' . $attr['class'];
                } else {
                    $attr['class'] = $this->default_attr_class;
                }
            }

            if($options['route'] && !array_key_exists('data-ajax--url', $attr)){
                $attr['data-ajax--url'] = $this->router->generate($options['route'], $options['route_params']);
            }

           return $attr;
        });
    }
}

Allow to add more "attr"

Allow to add more "attr"

Allow to add more "attr" options without removing the default ones (default_attr_class & data-ajax--url)


<?php namespace Cello;

use \Asset,
	\Event,
	Orchestra\Acl,
	Orchestra\Core as O;

class Core {

	/**
	 * Start your engine.
	 *
	 * @static
	 * @access public
	 * @return void
	 */
	public static function start()
	{
		Acl::make('cello')->attach(O::memory());

		// Append all Cello required assets for Orchestra Administrator
		// Interface usage mainly on Resources page.
		Event::listen('orchestra.started: backend', function()
		{
			$asset = Asset::container('orchestra.backend');

			$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.js', array('jquery', 'bootstrap'));
			$asset->script('cello', 'bundles/cello/js/cello.min.js', array('redactor'));
			$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
		});
	}
}

<?php namespace Cello;

use \Asset,
	\Event,
	Orchestra\Acl,
	Orchestra\Core as O;

class Core {

	/**
	 * Start your engine.
	 *
	 * @static
	 * @access public
	 * @return void
	 */
	public static function start()
	{
		Acl::make('cello')->attach(O::memory());

		// Append all Cello required assets for Orchestra Administrator
		// Interface usage mainly on Resources page.
		Event::listen('orchestra.started: backend', function()
		{
			$asset = Asset::container('orchestra.backend: footer');

			$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.min.js', array('jquery', 'bootstrap'));
			$asset->script('cello', 'bundles/cello/js/cello.min.js', array('redactor'));
			$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
		});
	}
}

Update asset loading to be loaded in footer.

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


<?php

return [
    'remove_strings_from_command' => [
        "'".PHP_BINARY."'",
        "'".strtolower(config('app.name'))."'",
    ],
];

<?php

return [
    'remove_strings_from_command' => [
        "'".PHP_BINARY."'",
        "'application'",
    ],
];

Update configuration stub in the tests

Update configuration stub in the tests


<?php

/**
 * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\Memcache;

class APCuTest extends Cache {
	protected function setUp() {
		parent::setUp();

		if(!\OC\Memcache\APCu::isAvailable()) {
			$this->markTestSkipped('The APCu extension is not available.');
			return;
		}
		$this->instance=new \OC\Memcache\APCu($this->getUniqueID());
	}
}

<?php

/**
 * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\Memcache;

class APCuTest extends Cache {
	protected function setUp() {
		parent::setUp();

		if(!\OC\Memcache\APCu::isAvailable()) {
			$this->markTestSkipped('The APCu extension is not available.');
			return;
		}
		$this->instance=new \OC\Memcache\APCu($this->getUniqueID());
	}

	public function testCasIntChanged() {
		$this->instance->set('foo', 1);
		$this->assertTrue($this->instance->cas('foo', 1, 2));
		$this->assertEquals(2, $this->instance->get('foo'));
	}

	public function testCasIntNotChanged() {
		$this->instance->set('foo', 1);
		$this->assertFalse($this->instance->cas('foo', 2, 3));
		$this->assertEquals(1, $this->instance->get('foo'));
	}
}

Extend APCu test with int CAS

Extend APCu test with int CAS

Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>


<?php
    $slides = get_field('slides', $module->ID);
?>

    <?php foreach ($slides as $slide) : ?>

        <?php if ($slide['acf_fc_layout'] == 'image') : ?>

            <img src="<?php echo $slide['image']['url']; ?>">

        <?php elseif ($slide['acf_fc_layout'] == 'video' && $slide['type'] == 'embed') : ?>

                <?php echo \Modularity\Module\Slider\Slider::getEmbed($slide['embed_link'], ['content']); ?>

        <?php elseif ($slide['acf_fc_layout'] == 'video' && $slide['type'] == 'upload') : ?>

            Markup for uploaded video.

        <?php endif; ?>

    <?php endforeach; ?>

<?php
    $slides = get_field('slides', $module->ID);
?>

    <?php foreach ($slides as $slide) : ?>

        <?php if ($slide['acf_fc_layout'] == 'image') : ?>

            <div class="slider-image" style="background-image:url('<?php echo $slide['image']['url']; ?>');">

        <?php elseif ($slide['acf_fc_layout'] == 'video' && $slide['type'] == 'embed') : ?>

                <?php echo \Modularity\Module\Slider\Slider::getEmbed($slide['embed_link'], ['content']); ?>

        <?php elseif ($slide['acf_fc_layout'] == 'video' && $slide['type'] == 'upload') : ?>

            Markup for uploaded video.

        <?php endif; ?>

    <?php endforeach; ?>

Change slider image markup output

Change slider image markup output


<?php

require dirname(__FILE__) . '/../vendor/autoload.php';

class JadePHPTest extends PHPUnit_Framework_TestCase {

    static private $skipped = array(
        // Here is the remain to implement list
        'inheritance.extend.mixins',
        'mixin.attrs',
        'mixin.block-tag-behaviour',
        'mixin.blocks',
        'mixin.merge',
        'tag.interpolation'
    );

    public function caseProvider() {
        static $rawResults = null;
        if(is_null($rawResults)) {
            $rawResults = get_tests_results();
            $rawResults = $rawResults['results'];
        }
        return $rawResults;
    }

    /**
     * @dataProvider caseProvider
     */
    public function testStringGeneration($name, $input, $expected) {
        if(! in_array($name, static::$skipped)) {
            $this->assertSame($input, $expected, $name);
        }
    }
}

<?php

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

class JadePHPTest extends PHPUnit_Framework_TestCase {

    static private $skipped = array(
        // Here is the remain to implement list
        'inheritance.extend.mixins',
        'mixin.attrs',
        'mixin.block-tag-behaviour',
        'mixin.blocks',
        'mixin.merge',
        'tag.interpolation'
    );

    public function caseProvider() {
        static $rawResults = null;
        if(is_null($rawResults)) {
            $rawResults = get_tests_results();
            $rawResults = $rawResults['results'];
        }
        return $rawResults;
    }

    /**
     * @dataProvider caseProvider
     */
    public function testStringGeneration($name, $input, $expected) {
        if(! in_array($name, static::$skipped)) {
            $this->assertSame($input, $expected, $name);
        }
    }
}

Use __DIR__ as PHP < 5.3 is not supported


<?php

namespace Backpack\CRUD\Tests\Unit\CrudPanel;

use Backpack\CRUD\CrudPanel;
use Backpack\CRUD\Tests\BaseTest;

abstract class BaseCrudPanelTest extends BaseTest
{
    /**
     * @var CrudPanel
     */
    protected $crudPanel;

    protected $model;

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

        $this->crudPanel = new CrudPanel();
        $this->model = new TestModel();
    }
}

<?php

namespace Backpack\CRUD\Tests\Unit\CrudPanel;

use Backpack\CRUD\CrudPanel;
use Backpack\CRUD\Tests\BaseTest;

abstract class BaseCrudPanelTest extends BaseTest
{
    /**
     * @var CrudPanel
     */
    protected $crudPanel;

    protected $model;

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

        $this->crudPanel = new CrudPanel();
        $this->crudPanel->setModel(TestModel::class);
        $this->model = $this->crudPanel->getModel();
    }
}

Set the test model to the CrudPanel.

Set the test model to the CrudPanel.


<?php

// Custom form validation messages
$lang['form_validation_unique'] = "The {field} field is not unique. Please choose another.";
$lang['form_validation_alpha_dot_dash'] = 'The {field} field may only contain alphanumeric characters, periods, underscores and dashes.';

<?php

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

Add latlong and shield factor form validation messages


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Swift Mailer Transport
	|--------------------------------------------------------------------------
	|
	| The name of your default Swift Mailer Transport. This transport will used
	| as the default for all mailing operations unless a different name is
	| given when performing said operation. This transport name should be
	| listed in the array of transports below.
	|
	*/

	'default' => 'mail',

	/*
	|--------------------------------------------------------------------------
	| Swift Mailer Transports
	|--------------------------------------------------------------------------
	|
	| Below is the configuration for each of the Swift Mailer transports. For
	| more information refer to:
	|
	|	http://swiftmailer.org/docs/sending.html
	|
	*/

	'transports' => array(

		'smtp' => array(
			'host'       => 'smtp.example.com',
			'port'       => 25,
			'username'   => 'username',
			'password'   => 'password',
			'encryption' => null,
		),

		'sendmail' => array(
			'command' => '/user/sbin/sendmail -bs',
		),

		'mail',

	),
);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Swift Mailer Transport
	|--------------------------------------------------------------------------
	|
	| The name of your default Swift Mailer Transport. This transport will used
	| as the default for all mailing operations unless a different name is
	| given when performing said operation. This transport name should be
	| listed in the array of transports below.
	|
	*/

	'default' => 'mail',

	/*
	|--------------------------------------------------------------------------
	| Swift Mailer Transports
	|--------------------------------------------------------------------------
	|
	| Below is the configuration for each of the Swift Mailer transports. For
	| more information refer to:
	|
	|	http://swiftmailer.org/docs/sending.html
	|
	*/

	'transports' => array(

		'smtp' => array(
			'host'       => 'smtp.example.com',
			'port'       => 25,
			'username'   => 'username',
			'password'   => 'password',
			'encryption' => null,
		),

		'sendmail' => array(
			'command' => '/usr/sbin/sendmail -bs',
		),

		'mail',

	),
);

Update sendmail default path configuration


<?php

/*
	Copyright (c) 2012 Colin Rotherham, http://colinr.com
	https://github.com/colinrotherham
*/

	namespace CRD\Core;

	class View
	{
		public $app;
		public $name;
		public $action;
		public $template;

		// All templates and partials
		public $templates = array();
		public $partials = array();

		// Shared array for passing from route action to view
		public $bag = array();

		public function __construct($app, $name, $action)
		{
			$this->app = $app;
			$this->name = $name;
			$this->action = $action;

			if (!file_exists($this->location()))
				throw new \Exception('Checking view: Missing view file');

			// Allow views to access templates/partials
			$this->templates = $app->templates;
			$this->partials = $app->partials;

			// Provide caching helper
			$this->cache = $app->cache;
		}

		public function location()
		{
			return $this->app->path . '/views/' . $this->name . '.php';
		}

		public function render()
		{
			// Run controller action
			if (is_callable($this->action))
			{
				$action = $this->action;
				$action($this);
			}

			// Present view
			require_once ($this->location());
		}
	}
?>

<?php

/*
	Copyright (c) 2012 Colin Rotherham, http://colinr.com
	https://github.com/colinrotherham
*/

	namespace CRD\Core;

	class View
	{
		public $app;
		public $name;
		public $action;
		public $template;

		// All templates and partials
		public $templates = array();
		public $partials = array();

		// Shared array for passing from route action to view
		public $bag = array();

		public function __construct($app, $name, $action)
		{
			$this->app = $app;
			$this->name = $name;
			$this->action = $action;

			if (!empty($this->name) && !file_exists($this->location()))
				throw new \Exception('Checking view: Missing view file');

			// Allow views to access templates/partials
			$this->templates = $app->templates;
			$this->partials = $app->partials;

			// Provide caching helper
			$this->cache = $app->cache;
		}

		public function location()
		{
			return $this->app->path . '/views/' . $this->name . '.php';
		}

		public function render()
		{
			// Run controller action
			if (is_callable($this->action))
			{
				$action = $this->action;
				$action($this);
			}

			// Present view if provided
			if (!empty($this->name))
				require_once ($this->location());
		}
	}
?>

Allow views to be action-only (i.e. no markup returned)


<?php
use App\Entity\StationMount;

$form_config = require __DIR__.'/generic.php';

$form_config['groups']['basic_info']['elements']['name'][1]['validator'] = function($text) {
    $forbidden_paths = ['listen', 'admin', 'statistics', '7.html'];

    foreach($forbidden_paths as $forbidden_path) {
        if (stripos($text, $forbidden_path) !== false) {
            return __('Stream path cannot include reserved keywords: %s', implode(', ', $forbidden_paths));
        }
    }

    return true;
};

$form_config['groups']['basic_info']['elements']['authhash'] = [
    'text',
    [
        'label' => __('YP Directory Authorization Hash'),
        'description' => sprintf(__('If your stream is set to advertise to YP directories above, you must specify an authorization hash. You can manage authhashes on the SHOUTcast web site.'),
            'https://rmo.shoutcast.com'),
        'default' => '',
        'form_group_class' => 'col-sm-12',
    ]
];

$form_config['groups']['autodj']['elements']['autodj_format'][1]['choices'] = [
    StationMount::FORMAT_MP3 => 'MP3',
    StationMount::FORMAT_AAC => 'AAC+ (MPEG4 HE-AAC v2)',
];

$form_config['groups']['autodj']['elements']['autodj_format'][1]['default'] = StationMount::FORMAT_MP3;

return $form_config;

<?php

use App\Entity\StationMount;

$form_config = require __DIR__ . '/generic.php';

$form_config['groups']['basic_info']['elements']['name'][1]['validator'] = function ($text) {
    $forbidden_paths = ['listen', 'admin', 'statistics', '7.html'];

    foreach ($forbidden_paths as $forbidden_path) {
        if (stripos($text, $forbidden_path) !== false) {
            return __('Stream path cannot include reserved keywords: %s', implode(', ', $forbidden_paths));
        }
    }

    return true;
};

$form_config['groups']['basic_info']['elements']['authhash'] = [
    'text',
    [
        'label' => __('YP Directory Authorization Hash'),
        'description' => __('If your stream is set to advertise to YP directories above, you must specify an authorization hash. You can manage authhashes on the SHOUTcast web site.',
            'https://rmo.shoutcast.com'),
        'default' => '',
        'form_group_class' => 'col-sm-12',
    ],
];

$form_config['groups']['autodj']['elements']['autodj_format'][1]['choices'] = [
    StationMount::FORMAT_MP3 => 'MP3',
    StationMount::FORMAT_AAC => 'AAC+ (MPEG4 HE-AAC v2)',
];

$form_config['groups']['autodj']['elements']['autodj_format'][1]['default'] = StationMount::FORMAT_MP3;

return $form_config;

Update syntax on SHOUTcast authhash form.


<?php
/**
 * ownCloud - gallery
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Olivier Paroz <owncloud@interfasys.ch>
 *
 * @copyright Olivier Paroz 2015
 */

use Codeception\Util\Autoload;

define('PHPUNIT_RUN', 1);

require_once __DIR__ . '/../../../lib/base.php';
Autoload::addNamespace('Test', '/../../../tests/lib');

// load minimum set of apps
OC_App::loadApps(array('authentication'));
OC_App::loadApps(array('filesystem', 'logging'));
OC_Hook::clear();

<?php
/**
 * ownCloud - gallery
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Olivier Paroz <owncloud@interfasys.ch>
 *
 * @copyright Olivier Paroz 2015
 */

use Codeception\Util\Autoload;

define('PHPUNIT_RUN', 1);

require_once __DIR__ . '/../../../lib/base.php';
OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
Autoload::addNamespace('Test', '/../../../tests/lib');

// load minimum set of apps
OC_App::loadApps(array('authentication'));
OC_App::loadApps(array('filesystem', 'logging'));
OC_Hook::clear();

Fix tests bootstrap to meet the new core requirements


<?php

class SculpinKernel extends \Sculpin\Bundle\SculpinBundle\HttpKernel\AbstractKernel
{
    protected function getAdditionalSculpinBundles(): array
    {
        return array(
            'Beryllium\Icelus\IcelusBundle',
        );
    }
}

<?php

class SculpinKernel extends \Sculpin\Bundle\SculpinBundle\HttpKernel\AbstractKernel
{
    protected function getAdditionalSculpinBundles(): array
    {
        return [];
    }
}

Remove reference to icelus, which was unused in this project


<?php namespace TightenCo\Jigsaw;

use TightenCo\Jigsaw\IterableObject;
use TightenCo\Jigsaw\Traits\HelperFunctionTrait;

class PageVariable extends IterableObject
{
    use HelperFunctionTrait;

    public function addVariables($variables)
    {
        $this->items = collect($this->items)->merge($variables)->all();
    }

    protected function missingHelperError($functionName)
    {
        return 'No function named "' . $functionName . '" was found in the file "config.php".';
    }
}

<?php namespace TightenCo\Jigsaw;

use TightenCo\Jigsaw\IterableObject;
use TightenCo\Jigsaw\Traits\HelperFunctionTrait;

class PageVariable extends IterableObject
{
    use HelperFunctionTrait;

    public function addVariables($variables)
    {
        $this->items = collect($this->items)->merge($this->makeIterable($variables))->all();
    }

    protected function missingHelperError($functionName)
    {
        return 'No function named "' . $functionName . '" was found in the file "config.php".';
    }
}

Make arrays defined in YAML frontmatter into iterable objects


<!DOCTYPE html>

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

Laravel 5

<!DOCTYPE html>

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

SUYABAY RELOADED

Change laravel 5 to Suyabay Reloaded

Change laravel 5 to Suyabay Reloaded


<?php

namespace Pinq\Tests\Integration\Traversable;

class SliceTest extends TraversableTest
{
    /**
     * @dataProvider Everything
     */
    public function testThatSkipRemovesCorrectAmountOfElementsFromTheStartAndPreservesKeys(\Pinq\ITraversable $Traversable, array $Data)
    {
        $WithoutFirstFiveElements = $Traversable->Skip(5);

        $this->AssertMatches($WithoutFirstFiveElements, array_slice($Data, 5, null, true));
    }

    /**
     * @dataProvider Everything
     */
    public function testThatTakeGetsTheCorrectAmountOfElementsFromTheStartAndPreservesKeys(\Pinq\ITraversable $Traversable, array $Data)
    {
        $FirstFiveElements = $Traversable->Take(5);

        $this->AssertMatches($FirstFiveElements, array_slice($Data, 0, 5));
    }

    /**
     * @dataProvider Everything
     */
    public function testThatTakeZeroReturnsEmptyArray(\Pinq\ITraversable $Traversable, array $Data)
    {
        $NoNumbers = $Traversable->Take(0);

        $this->AssertMatches($NoNumbers, []);
    }

    /**
     * @dataProvider Everything
     */
    public function testThatSkipZeroReturnsOriginalArray(\Pinq\ITraversable $Traversable, array $Data)
    {
        $Values = $Traversable->Skip(0);

        $this->AssertMatches($Values, $Data);
    }
}

<?php

namespace Pinq\Tests\Integration\Traversable;

class SliceTest extends TraversableTest
{
    /**
     * @dataProvider Everything
     */
    public function testThatSkipRemovesCorrectAmountOfElementsFromTheStartAndPreservesKeys(\Pinq\ITraversable $Traversable, array $Data)
    {
        $WithoutFirstFiveElements = $Traversable->Skip(5);

        $this->AssertMatches($WithoutFirstFiveElements, array_slice($Data, 5, null, true));
    }

    /**
     * @dataProvider Everything
     */
    public function testThatTakeGetsTheCorrectAmountOfElementsFromTheStartAndPreservesKeys(\Pinq\ITraversable $Traversable, array $Data)
    {
        $FirstFiveElements = $Traversable->Take(5);

        $this->AssertMatches($FirstFiveElements, array_slice($Data, 0, 5, true));
    }

    /**
     * @dataProvider Everything
     */
    public function testThatTakeZeroReturnsEmptyArray(\Pinq\ITraversable $Traversable, array $Data)
    {
        $NoNumbers = $Traversable->Take(0);

        $this->AssertMatches($NoNumbers, []);
    }

    /**
     * @dataProvider Everything
     */
    public function testThatSkipZeroReturnsOriginalArray(\Pinq\ITraversable $Traversable, array $Data)
    {
        $Values = $Traversable->Skip(0);

        $this->AssertMatches($Values, $Data);
    }
}

Fix take test key preserving

Fix take test key preserving


<?php namespace Bogardo\Mailgun;

use Illuminate\Support\ServiceProvider;

class MailgunServiceProvider extends ServiceProvider
{

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

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

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

		$this->app->booting(function(){
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Mailgun', 'Bogardo\Mailgun\Facades\Mailgun');
		});

        $this->mergeConfigFrom(
            __DIR__.'/../config/config.php', 'mailgun'
        );
	}

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

}

<?php namespace Bogardo\Mailgun;

use Illuminate\Support\ServiceProvider;

class MailgunServiceProvider extends ServiceProvider
{

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

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

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

		$this->app->booting(function(){
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Mailgun', 'Bogardo\Mailgun\Facades\Mailgun');
		});

        $this->mergeConfigFrom(
            __DIR__.'/../../config/config.php', 'mailgun'
        );
	}

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

}

Correct path to access to config file

Correct path to access to config file


<?php
/* @var $this yii\web\View */
$this->title = 'Welcome To Biser';
?>

Welcome!

欢迎来到Biser数据聚合服务

<?php foreach($summary as $s) {?>

<?php echo $s['title'];?>

<?php echo $s['post_name']; ?>

<a class="btn btn-default" href="./feed/index?post_id=<?php echo $s['post_id']; ?>">Read more

<?php } ?>

<?php
/* @var $this yii\web\View */
$this->title = 'Welcome To Biser';
?>

Welcome!

欢迎来到Biser数据聚合服务

<?php foreach($summary as $s) {?>

<?php echo $s['title'];?>

<?php echo $s['post_name']; ?>

<a class="btn btn-default" href="/feed/index?post_id=<?php echo $s['post_id']; ?>">Read more

<?php } ?>

Fix a little bug: mainpage jump link

Fix a little bug: mainpage jump link


<?php

namespace Hub\Client\Common;

use Hub\Client\Exception\BadRequestException;
use Hub\Client\Exception\NotFoundException;
use Hub\Client\Exception\NotAuthorizedException;
use GuzzleHttp\Psr7\Response;
use RuntimeException;

class ErrorResponseHandler
{
    public static function handle(Response $response)
    {
        if ($response->getStatusCode() == 401) {
            throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed');
        }

        $xml = $response->getBody();
        $rootNode = @simplexml_load_string($xml);
        if ($rootNode) {
            if ($rootNode->getName()=='error') {
                switch ((string)$rootNode->status) {
                    case 400:
                        throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 404:
                        throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 403:
                        throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    default:
                        throw new RuntimeException(
                            "Unsupported response status code returned: " .
                            (string)$rootNode->status . ' / ' . (string)$rootNode->code
                        );
                        break;
                }
            }
            throw new RuntimeException(
                "Failed to parse response. It's valid XML, but not the expected error root element"
            );
        }

        throw new RuntimeException("Failed to parse response: " . $xml);
    }
}

<?php

namespace Hub\Client\Common;

use Hub\Client\Exception\BadRequestException;
use Hub\Client\Exception\NotFoundException;
use Hub\Client\Exception\NotAuthorizedException;
use RuntimeException;

class ErrorResponseHandler
{
    public static function handle($response)
    {
        if ($response->getStatusCode() == 401) {
            throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed');
        }

        $xml = $response->getBody();
        $rootNode = @simplexml_load_string($xml);
        if ($rootNode) {
            if ($rootNode->getName()=='error') {
                switch ((string)$rootNode->status) {
                    case 400:
                        throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 404:
                        throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 403:
                        throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    default:
                        throw new RuntimeException(
                            "Unsupported response status code returned: " .
                            (string)$rootNode->status . ' / ' . (string)$rootNode->code
                        );
                        break;
                }
            }
            throw new RuntimeException(
                "Failed to parse response. It's valid XML, but not the expected error root element"
            );
        }

        throw new RuntimeException("Failed to parse response: " . $xml);
    }
}

Drop type-hint for Response to support multiple Guzzle versions


<?php

namespace ZfcTwig\Service;

use RuntimeException;
use Twig_Environment;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcTwig\Twig\Func\ViewHelper;

class TwigEnvironmentFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config  = $serviceLocator->get('Configuration');
        $config  = $config['zfctwig'];
        $env     = new Twig_Environment(null, (array) $config['environment_options']);

        if ($config['enable_fallback_functions']) {
            $helperPluginManager = $serviceLocator->get('ViewHelperManager');
            $env->registerUndefinedFunctionCallback(function($name) use ($helperPluginManager) {
                if ($helperPluginManager->has($name)) {
                    return new ViewHelper($name);
                }
                return null;
            });
        }

        if (!$serviceLocator->has($config['environment_loader'])) {
            throw new RuntimeException(sprintf(
                'Loader with alias "%s" could not be found!',
                $config['loader']
            ));
        }

        $env->setLoader($serviceLocator->get($config['environment_loader']));

        // Extensions are loaded later to avoid circular dependencies (for example, if an extension needs Renderer).
        return $env;
    }
}

<?php

namespace ZfcTwig\Service;

use RuntimeException;
use Twig_Environment;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcTwig\Twig\Func\ViewHelper;

class TwigEnvironmentFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config  = $serviceLocator->get('Configuration');
        $config  = $config['zfctwig'];
        $env     = new Twig_Environment(null, (array) $config['environment_options']);

        if ($config['enable_fallback_functions']) {
            $helperPluginManager = $serviceLocator->get('ViewHelperManager');
            $env->registerUndefinedFunctionCallback(function($name) use ($helperPluginManager) {
                if ($helperPluginManager->has($name)) {
                    return new ViewHelper($name);
                }
                return false;
            });
        }

        if (!$serviceLocator->has($config['environment_loader'])) {
            throw new RuntimeException(sprintf(
                'Loader with alias "%s" could not be found!',
                $config['loader']
            ));
        }

        $env->setLoader($serviceLocator->get($config['environment_loader']));

        // Extensions are loaded later to avoid circular dependencies (for example, if an extension needs Renderer).
        return $env;
    }
}

Return false for undefined functions, not null


<?php
/*
 * This file is part of Bestboysmedialab-LanguageList
 *
 * (c) 2016 best boys media lab GmbH & Co. KG
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 *
 * @category    Bestboysmedialab
 * @package     LanguageList
 * @copyright   (c) 2016 best boys media lab GmbH & Co. KG <volker.ansmann@bestboys-medialab.com>
 * @link        http://www.bestboys-medialab.com
 */

namespace Bestboysmedialab\LanguageList;

use Illuminate\Support\Facades\Facade;

/**
 * LanguageListFacade
 *
 * @author Volker Ansmann <volker.ansmann@bestboys-medialab.com>
 */
class LanguageListFacade extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'languagelist'; }

}

<?php
/*
 * This file is part of Bestboysmedialab-LanguageList
 *
 * (c) 2016 best boys media lab GmbH & Co. KG
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 *
 * @category    Bestboysmedialab
 * @package     LanguageList
 * @copyright   (c) 2016 best boys media lab GmbH & Co. KG <volker.ansmann@bestboys-medialab.com>
 * @link        http://www.bestboys-medialab.com
 */

namespace Bestboysmedialab\LanguageList;

use Illuminate\Support\Facades\Facade;

/**
 * LanguageListFacade
 *
 * @author Volker Ansmann <volker.ansmann@bestboys-medialab.com>
 */
class LanguageListFacade extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return LanguageList::class; }

}

Return the correct class in getFacadeAccessor function


<?php

namespace Umpirsky\I18nRoutingBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class UmpirskyI18nRoutingExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new Configuration(), $configs);

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

        $container->getDefinition('umpirsky_i18n_routing.routing.loader.i18n_route_loader')->addArgument(
            new Reference(sprintf('umpirsky_i18n_routing.routing.strategy.%s_strategy', $config['strategy']))
        );

        $container->setParameter('umpirsky_i18n_routing.route_name_suffix', $config['route_name_suffix']);
        $container->setParameter('umpirsky_i18n_routing.default_locale', $config['default_locale']);
        $container->setParameter('umpirsky_i18n_routing.locales', $config['locales']);
        $container->setParameter('umpirsky_i18n_routing.strategy', $config['strategy']);
    }
}

<?php

namespace Umpirsky\I18nRoutingBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class UmpirskyI18nRoutingExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new Configuration(), $configs);

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

        $container->getDefinition('umpirsky_i18n_routing.routing.loader.i18n_route_loader')->addArgument(
            new Reference(sprintf('umpirsky_i18n_routing.routing.strategy.%s_strategy', $config['strategy']))
        );

        $container->setParameter('umpirsky_i18n_routing.route_name_suffix', $config['route_name_suffix']);
        $container->setParameter('umpirsky_i18n_routing.default_locale', $config['default_locale']);
        if ('prefix_except_default' === $config['strategy']) {
            $config['locales'] = array_diff($config['locales'], [$config['default_locale']]);
        }
        $container->setParameter('umpirsky_i18n_routing.locales', $config['locales']);
        $container->setParameter('umpirsky_i18n_routing.strategy', $config['strategy']);
    }
}

Remove default locale for prefix_except_default strategy