<?php
namespace SwagMediaSftp\Subscriber;

use Enlight\Event\SubscriberInterface;
use Enlight_Event_EventArgs;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Sftp\SftpAdapter;

class AdapterCollectionSubscriber implements SubscriberInterface {

    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Collect_MediaAdapter_sftp' => 'createSftpAdapter'
        ];
    }

    /**
     * Creates adapter instance
     *
     * @param Enlight_Event_EventArgs $args
     * @return AdapterInterface
     */
    public function createSftpAdapter(Enlight_Event_EventArgs $args)
    {
        $defaultConfig = [
            'host' => '',
            'port' => 22,
            'username' => '',
            'password' => '',
            'privateKey' => '',
            'root' => '',
            'timeout' => 10
        ];

        $config = array_merge($defaultConfig, $args->get('config'));

        return new SftpAdapter([
            'host' => $config['host'],
            'port' => $config['port'],
            'username' => $config['username'],
            'password' => $config['password'],
            'privateKey' => $config['privateKey'],
            'root' => $config['root'],
            'timeout' => $config['timeout']
        ]);
    }

}

<?php
namespace SwagMediaSftp\Subscriber;

use Enlight\Event\SubscriberInterface;
use Enlight_Event_EventArgs;

use League\Flysystem\AdapterInterface;
use League\Flysystem\Sftp\SftpAdapter;

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

class AdapterCollectionSubscriber implements SubscriberInterface {

    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Collect_MediaAdapter_sftp' => 'createSftpAdapter'
        ];
    }

    /**
     * Creates adapter instance
     *
     * @param Enlight_Event_EventArgs $args
     * @return AdapterInterface
     */
    public function createSftpAdapter(Enlight_Event_EventArgs $args)
    {
        $defaultConfig = [
            'host' => '',
            'port' => 22,
            'username' => '',
            'password' => '',
            'privateKey' => '',
            'root' => '',
            'timeout' => 10
        ];

        $config = array_merge($defaultConfig, $args->get('config'));

        return new SftpAdapter([
            'host' => $config['host'],
            'port' => $config['port'],
            'username' => $config['username'],
            'password' => $config['password'],
            'privateKey' => $config['privateKey'],
            'root' => $config['root'],
            'timeout' => $config['timeout']
        ]);
    }

}

Move inclusion of autoloader to subscriber


<?php

// ******************************
// Access to current order object
// ******************************

	// Get entity manager
	$entity_manager = \Drupal::entityManager();

	// Get order type
	$order_storage = $entity_manager->getStorage('commerce_order_type');
	$order_type = $order_storage->load('consumer_products')->id();

	// Get store
	$store = $entity_manager->getStorage('commerce_store')->loadDefault();

	// Currrent user
	$uid = \Drupal::currentUser();

	// Get Cart provider
	$cartProvider = Drupal::service('commerce_cart.cart_provider');

	// Get Cart
	$order = $cartProvider->getCart($order_type, $store, $uid);

// ******************************
// Get path object
// ******************************
  $path = '/node/3'
	$path_object = \Drupal::service('path.validator')->getUrlIfValid($path);

// ******************************
// Checkout Btn by order
// ******************************

  $routeName = 'commerce_checkout.form';
  $routeNameParameterKey = 'commerce_order';
  $routeNameParameterValue = 'orderId';

	 //Ex:
	 // {{ 'Buy'|t }}

<?php

// ******************************
// Access to current order object
// ******************************

	// Get entity manager
	$entityManager = \Drupal::entityManager();

	// Get order type
	$orderStorage = $entityManager->getStorage('commerce_order_type');
	$orderType = $orderStorage->load('consumer_products')->id();

	// Get store
	$store = $entityManager->getStorage('commerce_store')->loadDefault();

	// Currrent user
	$uid = \Drupal::currentUser();

	// Get Cart provider
	$cartProvider = Drupal::service('commerce_cart.cart_provider');

	// Get Cart
	$order = $cartProvider->getCart($orderType, $store, $uid);

// ******************************
// Get path object
// ******************************
  $path = '/node/3'
	$pathObbject = \Drupal::service('path.validator')->getUrlIfValid($path);

// ******************************
// Checkout Btn by order
// ******************************

  $routeName = 'commerce_checkout.form';
  $routeNameParameterKey = 'commerce_order';
  $routeNameParameterValue = 'orderId';

	 //Ex:
	 // {{ 'Buy'|t }}

Add CamelCase to the code

Add CamelCase to the code


@if($isHorizontal)

@endif

{!! $controlHtml !!}

@if(! $errors->isEmpty() && ! $errors->has($name))

    (success)
@endif

@if(! $errors->isEmpty() && $errors->has($name))

    (error)
    {{ implode(' ', $errors->get($name)) }}
@endif

@if($isHorizontal)

@endif

Switch from glyphicons to fontawesome

Switch from glyphicons to fontawesome


<?php
if (ereg("^(10|127|192)", $_SERVER['REMOTE_ADDR']) ) {
    require_once 'environments/development.php';
} else {
    require_once 'environments/production.php';
}

define('DB_NAME',     $WP_ENVIRONMENT['db_name']);
define('DB_USER',     $WP_ENVIRONMENT['db_user']);
define('DB_PASSWORD', $WP_ENVIRONMENT['db_password']);
define('DB_HOST',     $WP_ENVIRONMENT['db_host']);

define('WPLANG',      $WP_ENVIRONMENT['wp_lang']);

define('WP_DEBUG',    $WP_ENVIRONMENT['wp_debug']);

define('WPBP_ENV',    $WP_ENVIRONMENT['name']);
?>

<?php
if (ereg("^(10|127|192)", $_SERVER['REMOTE_ADDR']) ) {
    require_once 'environments/development.php';
} else {
    require_once 'environments/production.php';
}

define('DB_NAME',     $WP_ENVIRONMENT['db_name']);
define('DB_USER',     $WP_ENVIRONMENT['db_user']);
define('DB_PASSWORD', $WP_ENVIRONMENT['db_password']);
define('DB_HOST',     $WP_ENVIRONMENT['db_host']);

define('WP_DEBUG',    $WP_ENVIRONMENT['wp_debug']);

define('WPBP_ENV',    $WP_ENVIRONMENT['name']);
?>

Remove definition, as WP 4.0 handles this like a boss


<?php

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

$table = new DifferentialRevision();
$conn_w = $table->establishConnection('w');

$revisions = id(new DifferentialRevision())->loadAll();

echo "Migrating ".count($revisions)." revisions";
foreach ($revisions as $revision) {
  echo ".";

  $diff = $revision->loadActiveDiff();
  if (!$diff) {
    continue;
  }

  $branch_name = $diff->getBranch();
  $arc_project_phid = $diff->getArcanistProjectPHID();

  queryfx(
    $conn_w,
    'UPDATE %T SET branchName = %s, arcanistProjectPHID = %s WHERE id = %d',
    $table->getTableName(),
    $branch_name,
    $arc_project_phid,
    $revision->getID());
}
echo "\nDone.\n";

<?php

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

$table = new DifferentialRevision();
$conn_w = $table->establishConnection('w');

echo "Migrating revisions";
do {
  $revisions = id(new DifferentialRevision())
    ->loadAllWhere('branchName IS NULL LIMIT 1000');

  foreach ($revisions as $revision) {
    echo ".";

    $diff = $revision->loadActiveDiff();
    if (!$diff) {
      continue;
    }

    $branch_name = $diff->getBranch();
    $arc_project_phid = $diff->getArcanistProjectPHID();

    queryfx(
      $conn_w,
      'UPDATE %T SET branchName = %s, arcanistProjectPHID = %s WHERE id = %d',
      $table->getTableName(),
      $branch_name,
      $arc_project_phid,
      $revision->getID());
  }
} while (count($revisions) == 1000);
echo "\nDone.\n";

Fix patch 131 for db with lots of revisions

Summary:
The old version of this loads all differential revisions at once, but that much
can't all be loaded into memory when there are close to 500,000 revisions. This
diff splits up loading the revisions.

Test Plan: Ran this to run the migration in our install

Reviewers: jungejason, epriestley

Reviewed By: epriestley

CC: aran

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


<?php namespace Someline\Support\Controllers;

/**
 * Created for someline-starter.
 * User: Libern
 */

use Carbon\Carbon;
use Illuminate\Http\Request;
use Someline\Base\Http\Controllers\Controller;

class LocaleController extends Controller
{

    /**
     * @param Request $request
     * @param $locale
     * @return \Illuminate\Http\Response
     */
    public function getLocaleJs(Request $request, $locale)
    {
        $content = 'window.Someline.locales = ' . json_encode(trans('app', [], 'messages', $locale));
        $response = response()->make($content);
        $response->header('Content-Type', 'application/javascript');
        $response->setPublic()
            ->setMaxAge(604800)
            ->setExpires(Carbon::now()->addDay(7));
        return $response;
    }

    /**
     * @param Request $request
     * @param $locale
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getSwitchLocale(Request $request, $locale)
    {
        // check if supported
        $supportedLanguagesKeys = \LaravelLocalization::getSupportedLanguagesKeys();
        if (!in_array($locale, $supportedLanguagesKeys)) {
            abort(404);
        }

        // store in session
        session(['someline-locale' => $locale]);

        // check if has redirect url
        $redirect_url = '/';
        if ($request->has('redirect_url')) {
            $redirect_url = $request->get('redirect_url');
        }
        return redirect($redirect_url);
    }

}

<?php namespace Someline\Support\Controllers;

/**
 * Created for someline-starter.
 * User: Libern
 */

use Carbon\Carbon;
use Illuminate\Http\Request;
use Someline\Base\Http\Controllers\Controller;

class LocaleController extends Controller
{

    /**
     * @param Request $request
     * @param $locale
     * @return \Illuminate\Http\Response
     */
    public function getLocaleJs(Request $request, $locale)
    {
        $content = 'window.Someline.locales = ' . json_encode(trans('app', [], $locale));
        $response = response()->make($content);
        $response->header('Content-Type', 'application/javascript');
        $response->setPublic()
            ->setMaxAge(604800)
            ->setExpires(Carbon::now()->addDay(7));
        return $response;
    }

    /**
     * @param Request $request
     * @param $locale
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getSwitchLocale(Request $request, $locale)
    {
        // check if supported
        $supportedLanguagesKeys = \LaravelLocalization::getSupportedLanguagesKeys();
        if (!in_array($locale, $supportedLanguagesKeys)) {
            abort(404);
        }

        // store in session
        session(['someline-locale' => $locale]);

        // check if has redirect url
        $redirect_url = '/';
        if ($request->has('redirect_url')) {
            $redirect_url = $request->get('redirect_url');
        }
        return redirect($redirect_url);
    }

}

Change locale support for Laravel 5.4

Change locale support for Laravel 5.4


<?php
/**
 * Load the reader mode template.
 *
 * @package AMP
 */

the_post();

/**
 * Fires before rendering a post in AMP.
 *
 * This action is not triggered when 'amp' theme support is present. Instead, you should use 'template_redirect' action and check if `is_amp_endpoint()`.
 *
 * @since 0.2
 *
 * @param int $post_id Post ID.
 */
do_action( 'pre_amp_render_post', get_queried_object_id() );

amp_add_post_template_actions();

$amp_post_template = new AMP_Post_Template( get_queried_object_id() );
$amp_post_template->load();

<?php
/**
 * Load the reader mode template.
 *
 * @package AMP
 */

the_post();

/**
 * Fires before rendering a post in AMP.
 *
 * This action is not triggered when 'amp' theme support is present. Instead, you should use 'template_redirect' action and check if `is_amp_endpoint()`.
 *
 * @since 0.2
 *
 * @param int $post_id Post ID.
 */
do_action( 'pre_amp_render_post', get_queried_object_id() );

require_once AMP__DIR__ . '/includes/amp-post-template-functions.php';
amp_post_template_init_hooks();

$amp_post_template = new AMP_Post_Template( get_queried_object_id() );
$amp_post_template->load();

Remove usage of deprecated function

Remove usage of deprecated function


<?php

class Kohana_GIT {

	/**
	 * Execute a GIT command in the specified working directory
	 *
	 * @param  string $command    The GIT command to execute. This is NOT
	 *                            automagically escaped, be ware!
	 * @param  string $repository The path to the git repository
	 * @return string
	 */
	public static function execute($command, $repository = APPPATH)
	{
		if ( ! `which git`)
			throw new Kohana_Exception("The GIT binary must be installed");

		$command = 'git '.$command;

		// Setup the file descriptors specification
		$descriptsspec = array(
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'),
		);

		// Store the pipes in this array
		$pipes = array();

		// Execute the command
		$resource = proc_open($command, $descriptsspec, $pipes);

		// Setup the output
		$output = array(
			1 => trim(stream_get_contents($pipes[1])),
			2 => trim(stream_get_contents($pipes[2])),
		);

		// Close the pipes
		array_map('fclose', $pipes);

		// Make sure the process didn't exit with a non-zero value
		if (trim(proc_close($resource)))
			throw new Kohana_Exception($output[2]);

		return $output[1];
	}

}

<?php

class Kohana_GIT {

	/**
	 * Execute a GIT command in the specified working directory
	 *
	 * @param  string $command The GIT command to execute. This is NOT
	 *                         automagically escaped, be ware!
	 * @param  string $cwd     The working directory to run the command under.
	 *                         This can be set to NULL to use the directory the
	 *                         script was run under
	 * @return string
	 */
	public static function execute($command, $cwd = APPPATH)
	{
		if ( ! `which git`)
			throw new Kohana_Exception("The GIT binary must be installed");

		$command = 'git '.$command;

		if ($cwd !== NULL)
		{
			// Change directories to the working tree
			$command = 'cd '.escapeshellarg($cwd).' && '.$command;
		}

		// Setup the file descriptors specification
		$descriptsspec = array(
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'),
		);

		// Store the pipes in this array
		$pipes = array();

		// Execute the command
		$resource = proc_open($command, $descriptsspec, $pipes);

		// Setup the output
		$output = array(
			1 => trim(stream_get_contents($pipes[1])),
			2 => trim(stream_get_contents($pipes[2])),
		);

		// Close the pipes
		array_map('fclose', $pipes);

		// Make sure the process didn't exit with a non-zero value
		if (trim(proc_close($resource)))
			throw new Kohana_Exception($output[2]);

		return $output[1];
	}

}

Add the functionallity for the `cwd` paremeter

This parameter allows the current working directory to be set for git to
command run in


id="<?php echo $view->escape($id) ?>"
name="<?php echo $view->escape($full_name) ?>"
<?php if ($read_only): ?>readonly="readonly" <?php endif ?>
<?php if ($disabled): ?>disabled="disabled" <?php endif ?>
<?php if ($required): ?>required="required" <?php endif ?>
<?php if ($max_length): ?>maxlength="<?php echo $view->escape($max_length) ?>" <?php endif ?>
<?php if ($pattern): ?>pattern="<?php echo $view->escape($pattern) ?>" <?php endif ?>
<?php foreach ($attr as $k => $v): ?>
    <?php printf('%s="%s" ', $view->escape($k), $view->escape(in_array($v, array('placeholder', 'title')) ? $view['translator']->trans($v, array(), $translation_domain) : $v)) ?>
<?php endforeach; ?>

id="<?php echo $view->escape($id) ?>"
name="<?php echo $view->escape($full_name) ?>"
<?php if ($read_only): ?>readonly="readonly" <?php endif ?>
<?php if ($disabled): ?>disabled="disabled" <?php endif ?>
<?php if ($required): ?>required="required" <?php endif ?>
<?php if ($max_length): ?>maxlength="<?php echo $view->escape($max_length) ?>" <?php endif ?>
<?php if ($pattern): ?>pattern="<?php echo $view->escape($pattern) ?>" <?php endif ?>
<?php foreach ($attr as $k => $v): ?>
    <?php printf('%s="%s" ', $view->escape($k), $view->escape(in_array($k, array('placeholder', 'title')) ? $view['translator']->trans($v, array(), $translation_domain) : $v)) ?>
<?php endforeach; ?>

[FrameworkBundle] Fix title and placeholder rendering in php form templates.


<?php
/**
 * This file is part of the LdapTools package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace LdapTools\Connection;

/**
 * Represents various ldap server control values.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class LdapControlType
{
    /**
     * Paged operation support that splits results into multiple result sets.
     */
    const PAGED_RESULTS = '1.2.840.113556.1.4.319';

    /**
     * Used to specify that tombstones and deleted objects should be visible to the operation.
     */
    const SHOW_DELETED = '1.2.840.113556.1.4.417';

    /**
     * Used to specify that all children of a LDAP object should be removed during a delete operation.
     */
    const SUB_TREE_DELETE = '1.2.840.113556.1.4.805';
}

<?php
/**
 * This file is part of the LdapTools package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace LdapTools\Connection;

/**
 * Represents various ldap server control values.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class LdapControlType
{
    /**
     * Paged operation support that splits results into multiple result sets.
     */
    const PAGED_RESULTS = '1.2.840.113556.1.4.319';

    /**
     * Used to specify that tombstones and deleted objects should be visible to the operation.
     */
    const SHOW_DELETED = '1.2.840.113556.1.4.417';

    /**
     * Used to specify that all children of a LDAP object should be removed during a delete operation.
     */
    const SUB_TREE_DELETE = '1.2.840.113556.1.4.805';

    /**
     * Used to control what part of a Windows Security descriptor is selected/used on searches/modifications/adds.
     *
     * @see https://msdn.microsoft.com/en-us/library/cc223323.aspx
     */
    const SD_FLAGS_CONTROL = '1.2.840.113556.1.4.801';
}

Add the SD Flags Control OID to the types.


<?php

/*
 * This file is a part of Sculpin.
 *
 * (c) Dragonfly Development Inc.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sculpin\Core\SiteConfiguration;

use Dflydev\DotAccessConfiguration\Configuration;
use Dflydev\DotAccessConfiguration\YamlFileConfigurationBuilder;

/**
 * Site Configuration Factory.
 *
 * @author Beau Simensen <beau@dflydev.com>
 */
class SiteConfigurationFactory
{
    /**
     * Constructor.
     *
     * @param string $rootDir     Root directory
     * @param string $environment Environment
     */
    public function __construct($rootDir, $environment)
    {
        $this->rootDir = $rootDir;
        $this->environment = $environment;
    }

    /**
     * Create Site Configuration
     *
     * @return Configuration
     */
    public function create()
    {
        if (file_exists($file = $this->rootDir.'/config/sculpin_site_'.$this->environment.'.yml')) {
            $builder = new YamlFileConfigurationBuilder(array($file));

            return $builder->build();
        } elseif (file_exists($file = $this->rootDir.'/config/sculpin_site.yml')) {
            $builder = new YamlFileConfigurationBuilder(array($file));

            return $builder->build();
        }

        return new Configuration;
    }
}

<?php

/*
 * This file is a part of Sculpin.
 *
 * (c) Dragonfly Development Inc.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sculpin\Core\SiteConfiguration;

use Dflydev\DotAccessConfiguration\Configuration;
use Dflydev\DotAccessConfiguration\YamlFileConfigurationBuilder;

/**
 * Site Configuration Factory.
 *
 * @author Beau Simensen <beau@dflydev.com>
 */
class SiteConfigurationFactory
{
    /**
     * Constructor.
     *
     * @param string $rootDir     Root directory
     * @param string $environment Environment
     */
    public function __construct($rootDir, $environment)
    {
        $this->rootDir = $rootDir;
        $this->environment = $environment;
    }

    /**
     * Get an instance of the Configuration() class from the given file.
     *
     * @param  string $configFile
     * @return YamlFileConfigurationBuilder
     */
    private function getConfigFile($configFile)
    {
        $builder = new YamlFileConfigurationBuilder(array($configFile));
        $config = $builder->build();

        return $config;
    }

    /**
     * Create Site Configuration
     *
     * @return Configuration
     */
    public function create()
    {
        if (file_exists($file = $this->rootDir.'/config/sculpin_site_'.$this->environment.'.yml')) {
            $config = $this->getConfigFile($file);
        } elseif (file_exists($file = $this->rootDir.'/config/sculpin_site.yml')) {
            $config =  $this->getConfigFile($file);
        } else {
            $config = new Configuration();
        }

        $config->set('env', $this->environment);

        return $config;
    }
}

Add 'env' as a default variable available via {{ site.env }} in Twig templates.

The environment is available while pulling in config files so this change
adds the environment to the 'site' variable.

I've tried to avoid code duplication by adding the getConfigFile() method,
but I'm not totally happy with the if .. elseif .. else block.


<?php
namespace Scat;

class Payment extends \Model {
  public static $methods= array(
    'cash' => "Cash",
    'change' => "Change",
    'credit' => "Credit Card",
    'square' => "Square",
    'stripe' => "Stripe",
    'gift' => "Gift Card",
    'check' => "Check",
    'dwolla' => "Dwolla",
    'paypal' => "PayPal",
    'amazon' => "Amazon Pay",
    'eventbrite' => "Eventbrite",
    'discount' => "Discount",
    'bad' => "Bad Debt",
    'donation' => "Donation",
    'withdrawal' => "Withdrawal",
    'internal' => "Internal",
  );

  function pretty_method() {
    switch ($this->method) {
    case 'credit':
      return 'Paid by ' . $this->cc_type . ' ending in ' . $this->cc_lastfour;
    case 'discount':
      return sprintf("Discount (%d%%)", $this->discount);
    case 'change':
      return 'Change';
    default:
      return 'Paid by ' . $this::methods($this->method);
    }
  }
}

<?php
namespace Scat;

class Payment extends \Model {
  public static $methods= array(
    'cash' => "Cash",
    'change' => "Change",
    'credit' => "Credit Card",
    'square' => "Square",
    'stripe' => "Stripe",
    'gift' => "Gift Card",
    'check' => "Check",
    'dwolla' => "Dwolla",
    'paypal' => "PayPal",
    'amazon' => "Amazon Pay",
    'eventbrite' => "Eventbrite",
    'discount' => "Discount",
    'bad' => "Bad Debt",
    'donation' => "Donation",
    'withdrawal' => "Withdrawal",
    'internal' => "Internal",
  );

  function pretty_method() {
    switch ($this->method) {
    case 'credit':
      return 'Paid by ' . $this->cc_type . ' ending in ' . $this->cc_lastfour;
    case 'discount':
      return sprintf("Discount (%d%%)", $this->discount);
    case 'change':
      return 'Change';
    default:
      return 'Paid by ' . self::$methods[$this->method];
    }
  }
}

Fix printing of payment methods

Fix printing of payment methods


<?php

namespace Cs278\BankModulus;

final class ModulusAlgorithm
{
    public static function mod10($input, $weights)
    {
        // var_dump($input, $weights);
        return self::calculateMod($input, $weights) % 10;
    }

    public static function mod11($input, $weights)
    {
        return self::calculateMod($input, $weights) % 11;
    }

    public static function dblAl($input, $weights)
    {
        return self::calculateDblAl($input, $weights) % 10;
    }

    public static function calculateMod($input, $weights)
    {
        $checksum = self::applyWeights($input, $weights);

        return array_sum($checksum);
    }

    public static function calculateDblAl($input, $weights)
    {
        $checksum = self::applyWeights($input, $weights);

        // Sum individual digits.
        $checksum = array_reduce($checksum, function ($carry, $value) {
            return $carry + array_sum(str_split($value));
        }, 0);

        return $checksum % 10;
    }

    private static function applyWeights($input, $weights)
    {
        return array_map(function ($a, $b) {
            return $a * $b;
        }, str_split($input), str_split($weights));
    }
}

<?php

namespace Cs278\BankModulus;

final class ModulusAlgorithm
{
    public static function mod10($input, array $weights)
    {
        // var_dump($input, $weights);
        return self::calculateMod($input, $weights) % 10;
    }

    public static function mod11($input, array $weights)
    {
        return self::calculateMod($input, $weights) % 11;
    }

    public static function dblAl($input, array $weights)
    {
        return self::calculateDblAl($input, $weights) % 10;
    }

    public static function calculateMod($input, array $weights)
    {
        $checksum = self::applyWeights($input, $weights);

        return array_sum($checksum);
    }

    public static function calculateDblAl($input, array $weights)
    {
        $checksum = self::applyWeights($input, $weights);

        // Sum individual digits.
        $checksum = array_reduce($checksum, function ($carry, $value) {
            return $carry + array_sum(str_split($value));
        }, 0);

        return $checksum % 10;
    }

    private static function applyWeights($input, array $weights)
    {
        return array_map(function ($a, $b) {
            return $a * $b;
        }, str_split($input), $weights);
    }
}

Change algorithms to accept array of weights


<?php

namespace OpenDominion\Models;

/**
 * OpenDominion\Models\TechPerk
 *
 * @property int $id
 * @property int $tech_id
 * @property int $tech_perk_type_id
 * @property string $value
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \OpenDominion\Models\Tech $tech
 * @property-read \OpenDominion\Models\TechPerkType $type
 */
class TechPerk extends AbstractModel
{
    public function tech()
    {
        return $this->belongsTo(Tech::class);
    }

    public function type()
    {
        return $this->belongsTo(TechPerkType::class, 'tech_perk_type_id');
    }
}

Revert "Apply fixes from StyleCI"

Revert "Apply fixes from StyleCI"

This reverts commit f33b1e0bb3a668aa11f4f29a11fe5563f410f2b0.


<?php namespace Barryvdh\Omnipay;

use Omnipay\Common\GatewayFactory;

class ServiceProvider extends \Illuminate\Support\ServiceProvider {

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $configPath = __DIR__ . '/../config/omnipay.php';
        $this->publishes([$configPath => config_path('omnipay.php')]);

        $this->app['omnipay'] = $this->app->share(function ($app){
            $defaults = $app['config']->get('omnipay.defaults', array());
            return new GatewayManager($app, new GatewayFactory, $defaults);
        });
    }

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

<?php namespace Barryvdh\Omnipay;

use Omnipay\Common\GatewayFactory;

class ServiceProvider extends \Illuminate\Support\ServiceProvider {

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $configPath = __DIR__ . '/../config/omnipay.php';
        $this->publishes([$configPath => config_path('omnipay.php')]);

        $this->app['omnipay'] = $this->app->singleton('omnipay',function ($app){
            $defaults = $app['config']->get('omnipay.defaults', array());
            return new GatewayManager($app, new GatewayFactory, $defaults);
        });
    }

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

Convert from share() to singleton()

Convert from share() to singleton()

Replace the share() methods for the new singleton() ones.


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\EventHandling;

use Broadway\Domain\DomainMessage;

trait DelegateEventHandlingToSpecificMethodTrait
{
    /**
     * {@inheritDoc}
     */
    public function handle(DomainMessage $domainMessage)
    {
        $event  = $domainMessage->getPayload();
        $method = $this->getHandleMethod($event);
        if (!method_exists($this, $method)) {
            return;
        }

        try {
            $parameter = new \ReflectionParameter(array($this, $method), 0);
        } catch (\ReflectionException $e) {
            // No parameter for the method, so we ignore it.
            return;
        }
        $expectedClass = $parameter->getClass();

        if ($expectedClass->getName() == get_class($event)) {
            $this->$method($event, $domainMessage);
        }
    }

    private function getHandleMethod($event)
    {
        $classParts = explode('\\', get_class($event));

        return 'apply' . end($classParts);
    }
}

Add back empty line removed previously by zuuperman while committing debug statements


<?PHP
date_default_timezone_set(timezone_name_from_abbr("CST"));
$yest = date('Y-m-d', strtotime( '-1 days' ));
$today = date('Y-m-d');

?>
Stats | Download All (.tgz) | <a href="parser.php?log=<?PHP echo $yest; ?>.log">Yesterday's Logs | <a href="parser.php?log=<?PHP echo $today; ?>.log">Today's Logs | <form action="search" method="get" style="margin: 0; padding: 0; display:inline;"><input style="display: inline;" type="text" name="search"><input style="display: inline;" type="submit" value="Search"></form>

<?PHP
date_default_timezone_set(timezone_name_from_abbr("CST"));
$yest = date('Y-m-d', strtotime( '-1 days' ));
$today = date('Y-m-d');

?>
Stats | Download All (.tgz) | <a href="parser.php?log=<?PHP echo $yest; ?>.log">Yesterday's Logs | <a href="parser.php?log=<?PHP echo $today; ?>.log">Today's Logs | <form action="search" method="get" style="margin: 0; padding: 0; display:inline;"><input type="hidden" name="case" value="1" /><input style="display: inline;" type="text" name="search"><input style="display: inline;" type="submit" value="Search"></form>

Make searches from index default to ignore case


@extends('front::app')

@section('content')

{{ config('app.name') }}

    {{ trans('dictionary.restricted-area') }}
@stop

@extends('front::app')

@section('page-title', 'Home')

@section('content')

{{ config('app.name') }}

    {{ trans('dictionary.restricted-area') }}
@stop

Add page title to home

Add page title to home


<?php

class LocaleProviderClientGeoIP extends AbstractLocaleProvider {
    // path and filename of geoip data file relative to Director::baseFolder.
    private static $geoip_data_file = '';
    /**
     * Return the locale as found by GeoIP lookup of clients REMOTE_ADDR
     *
     * - null (missing data value) can't find remote address in lookup file
     * - false (no available data) no file or no remote address provided in request so can't do lookup
     * - locale string in e.g. en_US format.
     *
     * @return string|null|boolean
     */
    public static function get_locale()
    {
        if ($filePathAndName = self::config()->geoip_data_file) {
            $gi = geoip_open(Director::baseFolder() . $filePathAndName, GEOIP_STANDARD);
            $countryCode = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
            geoip_close($gi);

            return $countryCode ?: null;
        }
        return false;
    }
}

<?php

class LocaleProviderClientGeoIP extends AbstractLocaleProvider {
    // path and filename of geoip data file relative to Director::baseFolder.
    private static $geoip_data_file = '';
    /**
     * Return the locale as found by GeoIP lookup of clients REMOTE_ADDR
     *
     * - null (missing data value) can't find remote address in lookup file
     * - false (no available data) no file or no remote address provided in request so can't do lookup
     * - locale string in e.g. en_US format.
     *
     * @return string|null|boolean
     */
    public static function get_locale()
    {
        if ($filePathAndName = self::config()->geoip_data_file) {
            if ($gi = geoip_open(Director::baseFolder() . $filePathAndName, GEOIP_STANDARD)) {
                $countryCode = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
                geoip_close($gi);

                return $countryCode ? "en_$countryCode" : null;
            }
        }
        return false;
    }
}

Prepend en_ to country code, this is a HACK, need to do a proper looked of ISO-3166-1 to locales


<?php
/**
 *  * Created by mtils on 22.08.18 at 13:31.
 **/

namespace Ems\Core;

use Ems\Contracts\Core\Input as InputContract;
use Ems\Contracts\Core\None;
use Ems\Core\Exceptions\KeyNotFoundException;
use Ems\Core\Support\FastArrayDataTrait;
use Ems\Core\Support\InputTrait;
use Ems\Core\Support\RoutableTrait;
use function array_key_exists;

class Input implements InputContract
{
    use FastArrayDataTrait;
    use RoutableTrait;
    use InputTrait;

    /**
     * {@inheritDoc}
     *
     * @param mixed $key
     * @param mixed $default (optional)
     *
     * @return mixed
     **/
    public function get($key, $default = null)
    {
        if (array_key_exists($key, $this->_attributes)) {
            return $this->_attributes[$key];
        }
        return $default;
    }

    /**
     * {@inheritDoc}
     *
     * @param string $key
     *
     * @throws \Ems\Contracts\Core\Errors\NotFound
     *
     * @return mixed
     **/
    public function getOrFail($key)
    {
        $result = $this->get($key, new None());

        if ($result instanceof None) {
            throw new KeyNotFoundException("Key '$key' not found in Input");
        }

        return $result;
    }

}

<?php
/**
 *  * Created by mtils on 22.08.18 at 13:31.
 **/

namespace Ems\Core;

use Ems\Contracts\Core\Input as InputContract;
use Ems\Contracts\Core\None;
use Ems\Core\Exceptions\KeyNotFoundException;
use Ems\Core\Support\FastArrayDataTrait;
use Ems\Core\Support\InputTrait;
use Ems\Core\Support\RoutableTrait;
use function array_key_exists;

class Input implements InputContract
{
    use FastArrayDataTrait;
    use RoutableTrait;
    use InputTrait;

    /**
     * Input constructor.
     *
     * @param array $parameters
     */
    public function __construct($parameters=[])
    {
        $this->_attributes = $parameters;
    }

    /**
     * {@inheritDoc}
     *
     * @param mixed $key
     * @param mixed $default (optional)
     *
     * @return mixed
     **/
    public function get($key, $default = null)
    {
        if (array_key_exists($key, $this->_attributes)) {
            return $this->_attributes[$key];
        }
        return $default;
    }

    /**
     * {@inheritDoc}
     *
     * @param string $key
     *
     * @throws \Ems\Contracts\Core\Errors\NotFound
     *
     * @return mixed
     **/
    public function getOrFail($key)
    {
        $result = $this->get($key, new None());

        if ($result instanceof None) {
            throw new KeyNotFoundException("Key '$key' not found in Input");
        }

        return $result;
    }

}

Allow passing attributes in construct

Allow passing attributes in construct


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */

    'default' => env('LOG_CHANNEL', 'stack'),

    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "custom", "stack"
    |
    */

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */

    'default' => env('LOG_CHANNEL', 'stack'),

    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "custom", "stack"
    |
    */

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'permission' => 02770,
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
            'permission' => 02770,
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

Set the permission of the file logs for daily and single to be 02770


<?php
/*
 * This file is part of the Pomm's Foundation package.
 *
 * (c) 2014 Grégoire HUBERT <hubert.greg@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PommProject\Foundation;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;

class LoggerListener implements LoggerAwareInterface, ListenerInterface
{
    use LoggerAwareTrait;

    public function notify($event, $data)
    {
        if ($event === 'pre') {
            $message = $data['sql'];
            $context = $data['parameters'];
        } else if ($event === 'post') {
            $message = "Query ok.";
            $context = $data;
        }

        $this->logger->info($message, $context);
    }
}

<?php
/*
 * This file is part of the Pomm's Foundation package.
 *
 * (c) 2014 Grégoire HUBERT <hubert.greg@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PommProject\Foundation;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;

class LoggerListener implements LoggerAwareInterface, ListenerInterface
{
    use LoggerAwareTrait;

    public function notify($event, array $data)
    {
        if ($event === 'pre') {
            $message = $data['sql'];
            $context = $data['parameters'];
        } else if ($event === 'post') {
            $message = "Query ok.";
            $context = $data;
        } else {
            throw new FoundationException(
                sprintf(
                    "Do not know what to log for event '%s' (data {%s}).",
                    $event,
                    join(', ', array_map(function($val) { return sprintf("'%s'", $val); }))
                )
            );
        }

        $this->logger->info($message, $context);
    }
}

Handle unknown events in LoggerListner.

Handle unknown events in LoggerListner.


<?php

/*
 * This file is part of the Ruler package, an OpenSky project.
 *
 * (c) 2011 OpenSky Project Inc
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Ruler;

/**
 * @author Jordan Raub <jordan@raub.me>
 */
abstract class Operator
{
    const UNARY = 'UNARY';
    const BINARY = 'BINARY';
    const MULTIPLE = 'MULTIPLE';

    protected $operands = [];

    /**
     * @param array $operands
     */
    public function __construct()
    {
        foreach (func_get_args() as $operand) {
            $this->addOperand($operand);
        }
    }

    public function getOperands()
    {
        switch ($this->getOperandCardinality()) {
            case self::UNARY:
                if (1 != count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes only 1 operand');
                }
                break;
            case self::BINARY:
                if (2 != count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes 2 operands');
                }
                break;
            case self::MULTIPLE:
                if (0 == count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes at least 1 operand');
                }
                break;
        }

        return $this->operands;
    }

    abstract public function addOperand($operand);
    abstract protected function getOperandCardinality();
}

<?php

/*
 * This file is part of the Ruler package, an OpenSky project.
 *
 * (c) 2011 OpenSky Project Inc
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Ruler;

/**
 * @author Jordan Raub <jordan@raub.me>
 */
abstract class Operator
{
    const UNARY = 'UNARY';
    const BINARY = 'BINARY';
    const MULTIPLE = 'MULTIPLE';

    protected $operands = array();

    /**
     * @param array $operands
     */
    public function __construct()
    {
        foreach (func_get_args() as $operand) {
            $this->addOperand($operand);
        }
    }

    public function getOperands()
    {
        switch ($this->getOperandCardinality()) {
            case self::UNARY:
                if (1 != count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes only 1 operand');
                }
                break;
            case self::BINARY:
                if (2 != count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes 2 operands');
                }
                break;
            case self::MULTIPLE:
                if (0 == count($this->operands)) {
                    throw new \LogicException(get_class($this) . ' takes at least 1 operand');
                }
                break;
        }

        return $this->operands;
    }

    abstract public function addOperand($operand);
    abstract protected function getOperandCardinality();
}

Use array() instead of [] for older php versions


<?php

    /** config.init.php
    * @author Team22mars <pierre@owni.fr>
    * @version 1.0
    * @desc Set up the application
    */

    // MySQL Database settings
    // -----------------------
    if (strstr($_SERVER['SERVER_NAME'], 'influencenetworks.org') ):

            /* *** PROD ENVIRONMENT *** */
            define('MYSQL_HOST', 'localhost');
            define('MYSQL_DB', '');
            define('MYSQL_USER', '');
            define('MYSQL_PASS', '');

            define('TABLE_PREFIX', 'inf_');

    else :

            /* *** DEV ENVIRONMENT *** */
            define('MYSQL_HOST', 'localhost');
            define('MYSQL_DB',   'influence_networks');
            define('MYSQL_USER', 'root');
            define('MYSQL_PASS', 'root');

            define('TABLE_PREFIX', 'inf_');

    endif;

    // Sharing configuration
    // -----------------------
    define("DOC_URL"   , "http://influencenetworks.org");
    define("DOC_TITLE" , "[APP] Influence Networks lets you see how public figures know each other" );
    define("DOC_TWUSER", "owni");
    define("GA_PROFILE", "UA-18463169-5");

?>

<?php

    /** config.init.php
    * @author Team22mars <pierre@owni.fr>
    * @version 1.0
    * @desc Set up the application
    */

    // MySQL Database settings
    // -----------------------
    if (strstr($_SERVER['SERVER_NAME'], 'influencenetworks.org') ):

            /* *** PROD ENVIRONMENT *** */
            define('MYSQL_HOST', 'localhost');
            define('MYSQL_DB',   '@@MYSQL_DB@@');
            define('MYSQL_USER', '@@MYSQL_USER@@');
            define('MYSQL_PASS', '@@MYSQL_PASS@@');

            define('TABLE_PREFIX', 'inf_');

    else :

            /* *** DEV ENVIRONMENT *** */
            define('MYSQL_HOST', 'localhost');
            define('MYSQL_DB',   'influence_networks');
            define('MYSQL_USER', 'root');
            define('MYSQL_PASS', 'root');

            define('TABLE_PREFIX', 'inf_');

    endif;

    // Sharing configuration
    // -----------------------
    define("DOC_URL"   , "http://influencenetworks.org");
    define("DOC_TITLE" , "[APP] Influence Networks lets you see how public figures know each other" );
    define("DOC_TWUSER", "owni");
    define("GA_PROFILE", "UA-18463169-5");

?>

Add value alias to script routine...

Add value alias to script routine...


<?php
class PhpTemplate
{
    protected $_dir  = Null;
    protected $_data = Array();

    public function __construct() {
        $this->_dir  = '..'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR;
    }

    public function render($__view, $data = Array()) {
        $content = $this->renderPartial($__view, $data);

        echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content));
    }

    public function renderPartial($__view, $__data = Array()) {
        $this->_data = array_merge($__data, $this->_data);

        ob_start();

        include($this->_dir.$__view.'.php');

        $content = ob_get_contents();

        ob_clean();

        return $content;
    }

    public function __set($key, $value) {
        $this->_data[$key] = $value;
    }

    public function __get($key) {
        return isset($this->_data[$key]) ? $this->_data[$key] : Null;
    }
}

<?php
class PhpTemplate
{
    protected $_dir  = Null;
    protected $_data = Array();

    public $app    = Null;
    public $router = Null;

    public function __construct() {
        $this->_dir   = '..'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR;
        $this->app    = App::instance();
        $this->router = Router::instance();
    }

    public function render($__view, $data = Array()) {
        $content = $this->renderPartial($__view, $data);

        echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content));
    }

    public function renderPartial($__view, $__data = Array()) {
        $this->_data = array_merge($__data, $this->_data);

        ob_start();

        include($this->_dir.$__view.'.php');

        $content = ob_get_contents();

        ob_clean();

        return $content;
    }

    public function __set($key, $value) {
        $this->_data[$key] = $value;
    }

    public function __get($key) {
        return isset($this->_data[$key]) ? $this->_data[$key] : Null;
    }
}

Send app and router instance to template


<?php
namespace DanDMartin\LoggerAware\Traits;

use Psr\Log\LoggerInterface as PsrLogger;
use DanDMartin\LoggerAware\Logger\NullLogger;

trait LoggerAware
{
    /**
     * @var PsrLogger
     */
    protected $logger;

    /**
     * @param PsrLogger $l
     * @required
     */
    public function setLogger(PsrLogger $l)
    {
        $this->logger = $l;
    }

    /**
     * @return PsrLogger
     */
    public function getLogger()
    {
        if(is_null($this->logger)) {
            $this->logger = new NullLogger();
        }
        return $this->logger;
    }
}

<?php
namespace DanDMartin\LoggerAware\Traits;

use Psr\Log\LoggerInterface as PsrLogger;
use DanDMartin\LoggerAware\Logger\NullLogger;

trait LoggerAware
{
    /**
     * @var PsrLogger
     */
    protected $logger;

    /**
     * @param PsrLogger $l
     * @required
     */
    public function setLogger(PsrLogger $l): void
    {
        $this->logger = $l;
    }

    /**
     * @return PsrLogger
     */
    public function getLogger(): PsrLogger
    {
        if(is_null($this->logger)) {
            $this->logger = new NullLogger();
        }
        return $this->logger;
    }
}

Add return types to trait methods

Add return types to trait methods


<?php
/* Tab Menu */
$tabs = array(
	array( 'url'=>"index.php", 'label'=>"Home" ),
	/*array( 'url'=>"stats.php", 'label'=>"Stats" ),*/
	array( 'url'=>"http://heavyink.com/", 'label'=>"HeavyInk" ) /* TODO: add a togle for Heavy/er Ink */
);
?>

<?php
foreach ($tabs as $tab):
	$class  = (isset($heri_selected_tab) && $heri_selected_tab == $tab['label'])
		? "class=\"selected\"" : "";
	$target = ( substr($tab['url'],0,4) == "http" )
		? "target=\"_blank\"" : "";
?>
			<li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?>

<?php
endforeach;
?>

<?php
/* Tab Menu */
$tabs = array(
	array( 'url'=>"index.php", 'label'=>"Home" ),
	/*array( 'url'=>"stats.php", 'label'=>"Stats" ),*/
	array( 'url'=>"https://heavyink.com/forums/1/topics/2655", 'label'=>"Discuss" ),
	array( 'url'=>"http://heavyink.com/", 'label'=>"HeavyInk" ) /* TODO: add a togle for Heavy/er Ink */
);
?>

<?php
foreach ($tabs as $tab):
	$class  = (isset($heri_selected_tab) && $heri_selected_tab == $tab['label'])
		? "class=\"selected\"" : "";
	$target = ( substr($tab['url'],0,4) == "http" )
		? "target=\"_blank\"" : "";
?>
			<li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?>

<?php
endforeach;
?>

Add a link to the forum thread about Heavyer Ink


<?php

use OpenConext\Component\EngineBlockMetadata\Entity\AbstractRole;

class EngineBlock_Corto_Mapper_Metadata_Entity_SsoDescriptor_UiInfo_Description
{
    /**
     * @var AbstractRole
     */
    private $_entity;

    public function __construct(AbstractRole $entity)
    {
        $this->_entity = $entity;
    }

    public function mapTo(array $rootElement)
    {
        $descriptions = array();
        if (!empty($this->_entity->descriptionEn)) {
            $descriptions['nl'] = $this->_entity->descriptionEn;
        }
        if (!empty($this->_entity->descriptionNl)) {
            $descriptions['en'] = $this->_entity->descriptionEn;
        }
        if (empty($descriptions)) {
            return $rootElement;
        }

        if (!isset($rootElement['md:Extensions'])) {
            $rootElement['md:Extensions'] = array();
        }
        if (!isset($rootElement['md:Extensions']['mdui:UIInfo'])) {
            $rootElement['md:Extensions']['mdui:UIInfo'] = array(0=>array());
        }

        foreach($descriptions as $languageCode => $value) {
            if(empty($value)) {
                continue;
            }

            $rootElement['md:Extensions']['mdui:UIInfo'][0]['mdui:Description'][] = array(
                EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . 'xml:lang' => $languageCode,
                EngineBlock_Corto_XmlToArray::VALUE_PFX => $value
            );
        }
        return $rootElement;
    }
}

<?php

use OpenConext\Component\EngineBlockMetadata\Entity\AbstractRole;

class EngineBlock_Corto_Mapper_Metadata_Entity_SsoDescriptor_UiInfo_Description
{
    /**
     * @var AbstractRole
     */
    private $_entity;

    public function __construct(AbstractRole $entity)
    {
        $this->_entity = $entity;
    }

    public function mapTo(array $rootElement)
    {
        $descriptions = array();
        if (!empty($this->_entity->descriptionNl)) {
            $descriptions['nl'] = $this->_entity->descriptionNl;
        }
        if (!empty($this->_entity->descriptionEn)) {
            $descriptions['en'] = $this->_entity->descriptionEn;
        }
        if (empty($descriptions)) {
            return $rootElement;
        }

        if (!isset($rootElement['md:Extensions'])) {
            $rootElement['md:Extensions'] = array();
        }
        if (!isset($rootElement['md:Extensions']['mdui:UIInfo'])) {
            $rootElement['md:Extensions']['mdui:UIInfo'] = array(0=>array());
        }

        foreach($descriptions as $languageCode => $value) {
            if(empty($value)) {
                continue;
            }

            $rootElement['md:Extensions']['mdui:UIInfo'][0]['mdui:Description'][] = array(
                EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . 'xml:lang' => $languageCode,
                EngineBlock_Corto_XmlToArray::VALUE_PFX => $value
            );
        }
        return $rootElement;
    }
}

Fix mdui_description 'nl' always having 'en' value.


<?php

namespace Application\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150920220909 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE post');
    }
}

<?php

namespace Application\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150920220909 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, author VARCHAR(255) NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE post');
    }
}

Add author to doctrine migrations

Add author to doctrine migrations


<?php

/**
 * @file
 * Contains \Drupal\Console\EventSubscriber\CallCommandListener.
 */

namespace Drupal\Console\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;

class CallCommandListener implements EventSubscriberInterface
{
    /**
     * @param ConsoleTerminateEvent $event
     */
    public function callCommands(ConsoleTerminateEvent $event)
    {
        /**
         * @var \Drupal\Console\Command\Command $command
         */
        $command = $event->getCommand();
        $output = $event->getOutput();

        if (!$command instanceof Command) {
            return;
        }

        $application = $command->getApplication();
        $commands = $application->getChain()->getCommands();

        if (!$commands) {
            return;
        }

        foreach ($commands as $chainedCommand) {
            if ($chainedCommand['name'] == 'module:install') {
                $messageHelper = $application->getMessageHelper();
                $translatorHelper = $application->getTranslator();
                $messageHelper->addErrorMessage(
                    $translatorHelper->trans('commands.chain.messages.module_install')
                );
                continue;
            }

            $callCommand = $application->find($chainedCommand['name']);

            $input = new ArrayInput($chainedCommand['inputs']);
            if (!is_null($chainedCommand['interactive'])) {
                $input->setInteractive($chainedCommand['interactive']);
            }
            $callCommand->run($input, $output);
        }
    }

    /**
     * @{@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [ConsoleEvents::TERMINATE => 'callCommands'];
    }
}

<?php

/**
 * @file
 * Contains \Drupal\Console\EventSubscriber\CallCommandListener.
 */

namespace Drupal\Console\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;

class CallCommandListener implements EventSubscriberInterface
{
    /**
     * @param ConsoleTerminateEvent $event
     */
    public function callCommands(ConsoleTerminateEvent $event)
    {
        /**
         * @var \Drupal\Console\Command\Command $command
         */
        $command = $event->getCommand();
        $output = $event->getOutput();

        if (!$command instanceof Command) {
            return;
        }

        $application = $command->getApplication();
        $commands = $application->getChain()->getCommands();

        if (!$commands) {
            return;
        }

        foreach ($commands as $chainedCommand) {
            $callCommand = $application->find($chainedCommand['name']);

            $input = new ArrayInput($chainedCommand['inputs']);
            if (!is_null($chainedCommand['interactive'])) {
                $input->setInteractive($chainedCommand['interactive']);
            }
            $callCommand->run($input, $output);
        }
    }

    /**
     * @{@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [ConsoleEvents::TERMINATE => 'callCommands'];
    }
}

[chain] Improve enable module:install command execution


<?

/**
 * This is implemented by the _pagination partial and hydrated
 * by the Bkwld\Decoy\Html\Paginator class to render pagination.
 * It is based on /laravel/framework/src/Illuminate/Pagination/views/slider.php
 * The paginator is only shown if there are more results than the smallest
 * per_page option.
 */

$presenter = new Illuminate\Pagination\BootstrapPresenter($paginator);
if ($paginator->getTotal() > Bkwld\Decoy\Controllers\Base::$per_page): ?>

		<?// The list of pages ?>
		<? if ($paginator->getLastPage() > 1): ?>

				<?=$presenter->render(); ?>

		<? endif ?>

		<?// Per page selector
		$options = array(Bkwld\Decoy\Controllers\Base::$per_page, 40, 'all');
		$count = Input::get('count', $options[0]); ?>

Show

			<? foreach($options as $option): ?>
				<? if ($count == $option): ?>
					<?=$presenter->getActivePageWrapper(ucfirst($option))?>
				<? else: ?>
					<?=$presenter->getPageLinkWrapper($paginator->addQuery('count', $option)->getUrl(1), ucfirst($option))?>
				<? endif ?>
			<? endforeach ?>

<? endif ?>

<?

/**
 * This is implemented by the _pagination partial and hydrated
 * by the Bkwld\Decoy\Html\Paginator class to render pagination.
 * It is based on /laravel/framework/src/Illuminate/Pagination/views/slider.php
 * The paginator is only shown if there are more results than the smallest
 * per_page option.
 */

$presenter = new Illuminate\Pagination\BootstrapPresenter($paginator);
if ($paginator->getTotal() > Bkwld\Decoy\Controllers\Base::$per_page): ?>

		<?// The list of pages ?>
		<? if ($paginator->getLastPage() > 1): ?>

				<?=$presenter->render(); ?>

		<? endif ?>

		<?// Per page selector
		$options = array(
			Bkwld\Decoy\Controllers\Base::$per_page,
			Bkwld\Decoy\Controllers\Base::$per_page * 2,
			'all');
		$count = Input::get('count', $options[0]); ?>

Show

			<? foreach($options as $option): ?>
				<? if ($count == $option): ?>
					<?=$presenter->getActivePageWrapper(ucfirst($option))?>
				<? else: ?>
					<?=$presenter->getPageLinkWrapper($paginator->addQuery('count', $option)->getUrl(1), ucfirst($option))?>
				<? endif ?>
			<? endforeach ?>

<? endif ?>

Make pagination choices multiples of the base per_page


<?php

namespace Neblion\ScrumBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * FeatureRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FeatureRepository extends EntityRepository
{
    public function load($id)
    {
        return $this->getEntityManager()
                ->createQuery(
                    'SELECT f, p, s
                    FROM NeblionScrumBundle:Feature f
                    INNER JOIN f.project p
                    INNER JOIN f.stories s
                    WHERE f.id = :id'
                )
                ->setParameter('id', $id)
                ->getOneOrNullResult();
    }

    public function getListForProject($project_id, $returnQuery = false)
    {
        $query = $this->getEntityManager()
                ->createQuery(
                    'SELECT f FROM NeblionScrumBundle:Feature f
                    INNER JOIN f.project p
                    WHERE p.id = :project_id
                    ORDER BY f.name'
                )
                ->setParameter('project_id', $project_id);
        if (!$returnQuery) {
            return $query->getArrayResult();
        }

        return $query;
    }

}

<?php

namespace Neblion\ScrumBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * FeatureRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FeatureRepository extends EntityRepository
{
    public function load($id)
    {
        return $this->getEntityManager()
                ->createQuery(
                    'SELECT f, p, s
                    FROM NeblionScrumBundle:Feature f
                    INNER JOIN f.project p
                    LEFT JOIN f.stories s
                    WHERE f.id = :id'
                )
                ->setParameter('id', $id)
                ->getOneOrNullResult();
    }

    public function getListForProject($project_id, $returnQuery = false)
    {
        $query = $this->getEntityManager()
                ->createQuery(
                    'SELECT f FROM NeblionScrumBundle:Feature f
                    INNER JOIN f.project p
                    WHERE p.id = :project_id
                    ORDER BY f.name'
                )
                ->setParameter('project_id', $project_id);
        if (!$returnQuery) {
            return $query->getArrayResult();
        }

        return $query;
    }

}

Fix FeatureRepo load left join to stories


<?php
namespace Companies20Module;

/**
 * Base class for all companies20 module presenters.
 *
 * @author     Michal Špaček
 * @package    michalspacek.cz
 */
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{

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

		$contentSecurityPolicy = $this->getContext()->getByType(\MichalSpacekCz\ContentSecurityPolicy::class);
		$header = $contentSecurityPolicy->getHeader();

		if ($header !== false) {
			$httpResponse = $this->getContext()->getByType(\Nette\Http\IResponse::class);
			$httpResponse->setHeader('Content-Security-Policy', $header);
		}
	}

	protected function createTemplate($class = null)
	{
		$helpers = $this->getContext()->getByType(\MichalSpacekCz\Templating\Helpers::class);

		$template = parent::createTemplate($class);
		$template->getLatte()->addFilter(null, [$helpers, 'loader']);
		return $template;
	}

}

<?php
namespace Companies20Module;

/**
 * Base class for all companies20 module presenters.
 *
 * @author     Michal Špaček
 * @package    michalspacek.cz
 */
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{

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

		$startup = $this->getContext()->getByType(\MichalSpacekCz\Startup::class);
		$startup->startup();
	}

	protected function createTemplate($class = null)
	{
		$helpers = $this->getContext()->getByType(\MichalSpacekCz\Templating\Helpers::class);

		$template = parent::createTemplate($class);
		$template->getLatte()->addFilter(null, [$helpers, 'loader']);
		return $template;
	}

}

Add XSS reporting to X-XSS-Protection

Add XSS reporting to X-XSS-Protection


<?php

namespace Rooty\UserBundle\Listener;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\DoctrineBundle\Registry as Doctrine;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use DateTime;
use Rooty\UserBundle\Entity\User;

class Activity
{
    protected $context;
    protected $em;
    public function __construct(SecurityContext $context, Doctrine $doctrine)
    {
        $this->context = $context;
        $this->em = $doctrine->getEntityManager();
    }
    /**
     * On each request we want to update the user's last activity datetime
     *
     * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
     * @return void
     */
    public function onCoreController(FilterControllerEvent $event)
    {
        if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
            return;
        };

        $user = $this->context->getToken()->getUser();
        if($user instanceof User)
        {
            //here we can update the user as necessary
            $user->setLastActivity(new DateTime());
            $this->em->persist($user);
            $this->em->flush($user);
        }
    }
}

<?php

namespace Rooty\UserBundle\Listener;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\DoctrineBundle\Registry as Doctrine;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use DateTime;
use Rooty\UserBundle\Entity\User;

class Activity
{
    protected $context;
    protected $em;
    public function __construct(SecurityContext $context, Doctrine $doctrine)
    {
        $this->context = $context;
        $this->em = $doctrine->getEntityManager();
    }
    /**
     * On each request we want to update the user's last activity datetime
     *
     * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
     * @return void
     */
    public function onCoreController(FilterControllerEvent $event)
    {
        if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
            return;
        };

        $user = $this->context->getToken()->getUser();
        if($user instanceof User)
        {
            //here we can update the user as necessary
            $user->setLastActivity(new DateTime());
            $this->em->persist($user);
            $this->em->flush($user);

            //force authentication to reload current roles
            $this->context->getToken()->setAuthenticated(false);
        }
    }
}

Update user roles on every request

Update user roles on every request


<?php namespace Analogue\LaravelAuth;

use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\RemindableInterface;

class User extends Entity implements UserInterface, RemindableInterface {

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->id;
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->password;
	}

	/**
	 * Get the token value for the "remember me" session.
	 *
	 * @return string
	 */
	public function getRememberToken()
	{
		return $this->{$this->getRememberTokenName()};
	}

	/**
	 * Set the token value for the "remember me" session.
	 *
	 * @param  string  $value
	 * @return void
	 */
	public function setRememberToken($value)
	{
		$this->{$this->getRememberTokenName()} = $value;
	}

	/**
	 * Get the column name for the "remember me" token.
	 *
	 * @return string
	 */
	public function getRememberTokenName()
	{
		return 'remember_token';
	}

}

<?php namespace Analogue\LaravelAuth;

use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Entity implements UserInterface, RemindableInterface {

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->id;
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->password;
	}

	/**
	 * Get the token value for the "remember me" session.
	 *
	 * @return string
	 */
	public function getRememberToken()
	{
		return $this->{$this->getRememberTokenName()};
	}

	/**
	 * Set the token value for the "remember me" session.
	 *
	 * @param  string  $value
	 * @return void
	 */
	public function setRememberToken($value)
	{
		$this->{$this->getRememberTokenName()} = $value;
	}

	/**
	 * Get the column name for the "remember me" token.
	 *
	 * @return string
	 */
	public function getRememberTokenName()
	{
		return 'remember_token';
	}

}

Change RemindableInterface to correct namespace


<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\View;
use AppBundle\Entity\User;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class UserController extends FOSRestController
{
    /**
     * Show details on a user
     * @ApiDoc()
     * @View(statusCode=200, serializerGroups={"profile"})
     * @Get("/api/v1/users/{id}")
     */
    public function getAction(User $user)
    {
        return ['user' => $user];
    }
}

<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\View;
use AppBundle\Entity\User;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class UsersController extends FOSRestController
{
    /**
     * Show details on a user
     * @ApiDoc()
     * @View(statusCode=200, serializerGroups={"profile"})
     * @Get("/api/v1/users/{id}")
     */
    public function getAction(User $user)
    {
        return ['user' => $user];
    }
}

Refactor Controller names, add Store/Pickup Entities


<?php  namespace Mbbender\Doctrine\DBAL\Types;

use Doctrine\DBAL\Types\GuidType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class OrderedGuidType extends GuidType
{
    const ORDEREDGUID = 'ordered_guid';

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $field['length'] = 36;
        $field['fixed']  = true;

        // TODO: Would prefer to allow $fieldDeclaration to override $field, but fixed = false is being passed in somewhere
        $fieldDeclaration = array_merge($fieldDeclaration, $field);

        return $platform->getBinaryTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
            //TODO: Throw exception? Never should have a null value here I don't think
        }

        // TODO: Throw exception if $value is not a resource. Not sure how you can not have a resource.
        $value = (is_resource($value)) ? stream_get_contents($value) : $value;

        return bin2hex($value);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        try{
            $value = hex2bin($value);
        }
        catch(\ErrorException $e)
        {

        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::ORDEREDGUID;
    }
}

<?php  namespace Mbbender\Doctrine\DBAL\Types;

use Doctrine\DBAL\Types\GuidType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class OrderedGuidType extends GuidType
{
    const ORDEREDGUID = 'ordered_guid';

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $field['length'] = 16;
        $field['fixed']  = true;

        // TODO: Would prefer to allow $fieldDeclaration to override $field, but fixed = false is being passed in somewhere
        $fieldDeclaration = array_merge($fieldDeclaration, $field);

        return $platform->getBinaryTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
            //TODO: Throw exception? Never should have a null value here I don't think
        }

        // TODO: Throw exception if $value is not a resource. Not sure how you can not have a resource.
        $value = (is_resource($value)) ? stream_get_contents($value) : $value;

        return bin2hex($value);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        try{
            $value = hex2bin($value);
        }
        catch(\ErrorException $e)
        {

        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::ORDEREDGUID;
    }
}

Update to fixed width 16 for binary guid


<?php
namespace PhpBrew\Command;

use CLIFramework\Command;
use PhpBrew\Config;

/**
 * @codeCoverageIgnore
 */
class UseCommand extends Command
{

    public function arguments($args) {
        $args->add('php version')
            ->validValues(function(){
                return Config::findMatchedBuilds();
            })
            ;
    }

    public function brief()
    {
        return 'Use php, switch version temporarily';
    }

    public function execute($buildName) {
        { // this block is important for tests only
            $root = Config::getPhpbrewRoot();
            $home = Config::getPhpbrewHome();
            putenv("PHPBREW_ROOT=$root");
            putenv("PHPBREW_HOME=$home");
            putenv("PHPBREW_PHP=$buildName");
            putenv("PHPBREW_PATH=$root/$buildName/bin");
            putenv("PHPBREW_BIN=$home/bin");
        }
        $this->logger->warning("You should not see this, if you see this, it means you didn't load the ~/.phpbrew/bashrc script, please check if bashrc is sourced in your shell.");
    }
}

<?php
namespace PhpBrew\Command;
use CLIFramework\Command;
use PhpBrew\Config;
use Exception;

/**
 * @codeCoverageIgnore
 */
class UseCommand extends Command
{

    public function arguments($args) {
        $args->add('php version')
            ->validValues(function(){
                return Config::findMatchedBuilds();
            })
            ;
    }

    public function brief()
    {
        return 'Use php, switch version temporarily';
    }

    public function execute($buildName) {
        if ($buildName) {
            // This exception is used for tracing tests
            throw new Exception("build name is required.");
        }
        { // this block is important for tests only
            $root = Config::getPhpbrewRoot();
            $home = Config::getPhpbrewHome();
            if (!file_exists("$root/php/$buildName")) {
                throw new Exception("build $buildName doesn't exist.");
            }
            putenv("PHPBREW_ROOT=$root");
            putenv("PHPBREW_HOME=$home");
            putenv("PHPBREW_PHP=$buildName");
            putenv("PHPBREW_PATH=$root/php/$buildName/bin");
            putenv("PHPBREW_BIN=$home/bin");
        }
        $this->logger->warning("You should not see this, if you see this, it means you didn't load the ~/.phpbrew/bashrc script, please check if bashrc is sourced in your shell.");
    }
}

Add more checks in use command

Add more checks in use command


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\twig;

/**
 * Template base class
 *
 * @author Alexei Tenitski <alexei@ten.net.nz>
 */
abstract class Template extends \Twig_Template
{
    protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
    {
        // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null

        if ($object instanceof \yii\db\BaseActiveRecord) {
            return $object->$item;
        }

        return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
    }
}

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\twig;

/**
 * Template base class
 *
 * @author Alexei Tenitski <alexei@ten.net.nz>
 */
abstract class Template extends \Twig_Template
{
    protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
    {
        // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null

        if ($object instanceof \yii\db\BaseActiveRecord) {
            if ($type == \Twig_Template::METHOD_CALL) {
                return $object->$item();
            } else {
                return $object->$item;
            }
        }

        return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
    }
}

Support for method calls on models from Twig templates


<?php

namespace Slate\Progress;

class SectionInterimReport extends AbstractSectionTermReport
{
    public static $tableName = 'section_interim_reports';
    public static $singularNoun = 'section interim report';
    public static $pluralNoun = 'section interim reports';
    public static $collectionRoute = '/progress/section-interim-reports';

    public static $defaultClass = __CLASS__;
    public static $subClasses = [__CLASS__];

    public static $fields = [
        'Notes' => [
            'type' => 'clob',
            'default' => null
        ]
    ];

    public static $indexes = [
        'StudentSectionTerm' => [
            'fields' => ['StudentID', 'SectionID', 'TermID'],
            'unique' => true
        ]
    ];
}

<?php

namespace Slate\Progress;

class SectionInterimReport extends AbstractSectionTermReport
{
    public static $tableName = 'section_interim_reports';
    public static $singularNoun = 'section interim report';
    public static $pluralNoun = 'section interim reports';
    public static $collectionRoute = '/progress/section-interim-reports';

    public static $defaultClass = __CLASS__;
    public static $subClasses = [__CLASS__];

    public static $fields = [
        'Notes' => [
            'type' => 'clob',
            'default' => null
        ],
        'NotesFormat' => [
            'type' => 'enum',
            'values' => ['markdown', 'html'],
            'default' => 'markdown'
        ]
    ];

    public static $indexes = [
        'StudentSectionTerm' => [
            'fields' => ['StudentID', 'SectionID', 'TermID'],
            'unique' => true
        ]
    ];
}

Add NotesFormat field to core model

Add NotesFormat field to core model


<?php

namespace Test\AppBundle\API\Details;

use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;

class OrganismsWithTraitTest extends WebTestCase
{
    public function testExecute()
    {
        $container = static::createClient()->getContainer();
        $default_db = $container->getParameter('default_db');
        $service = $container->get('app.api.webservice')->factory('details', 'organismsWithTrait');
        //Test for the correct number of elements in the returned array
        $results = $service->execute(new ParameterBag(array(
            'dbversion' => $default_db,
            'trait_type_id' => 1)),
            null
        );
        $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
        $results = $service->execute(
            new ParameterBag(array(
                'dbversion' => $default_db,
                'trait_type_id' => 1, 'limit' => 10
            )),
            null
        );
        $this->assertEquals(10, count($results));
    }
}

<?php

namespace Test\AppBundle\API\Details;

use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OrganismsWithTraitTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $default_db = $this->default_db;
        $service = $this->webservice->factory('details', 'organismsWithTrait');
        //Test for the correct number of elements in the returned array
        $results = $service->execute(new ParameterBag(array(
            'dbversion' => $default_db,
            'trait_type_id' => 1)),
            null
        );
        $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
        $results = $service->execute(
            new ParameterBag(array(
                'dbversion' => $default_db,
                'trait_type_id' => 1, 'limit' => 10
            )),
            null
        );
        $this->assertEquals(10, count($results));
    }
}

Use WebserviceTestCase as parent for details organismsWithTrait test


<?php

system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/Dinkly.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyBuilder.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataCollection.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConfig.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConnector.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyFlash.php');

<?php

system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/Dinkly.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyBuilder.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataCollection.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConfig.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConnector.php');
<<<<<<< HEAD
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyFlash.php');
=======
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
>>>>>>> parent of dac7b56... fixed run_unit_test.php system commands

Revert "fixed run_unit_test.php system commands"

This reverts commit dac7b56be5f32296cb6c98d72f15a65037017a33.

Conflicts:
	tools/run_unit_tests.php


#!/usr/bin/env php
<?php
// workerman.php

if (! defined ( 'DS' )) {
	define ( 'DS', DIRECTORY_SEPARATOR );
	define ( 'ROOT', __DIR__ . \DS .'..'.\DS. 'app' . \DS );
}
$config=include ROOT.'config/config.php';
$sConfig= include __DIR__.\DS.'workerman-config.php';
$config["sessionName"]=$sConfig["sessionName"];
$address=$sConfig['host'].':'.$sConfig['port'];
$config ["siteUrl"] = 'http://'.$address;
require ROOT . './../vendor/autoload.php';
require ROOT.'config/services.php';
$workerServer=new \Ubiquity\servers\workerman\WorkermanServer();
$workerServer->init($config, __DIR__);
$workerServer->setDefaultCount();
$workerServer->run($sConfig['host'],$sConfig['port'],$sConfig);

#!/usr/bin/env php
<?php
// workerman.php

if (! defined ( 'DS' )) {
	define ( 'DS', DIRECTORY_SEPARATOR );
	define ( 'ROOT', __DIR__ . \DS .'..'.\DS. 'app' . \DS );
}
$config=include ROOT.'config/config.php';
$sConfig= include __DIR__.\DS.'workerman-config.php';
$config["sessionName"]=$sConfig["sessionName"];
$address=$sConfig['host'].':'.$sConfig['port'];
$config ["siteUrl"] = 'http://'.$address;
require ROOT . './../vendor/autoload.php';
require ROOT.'config/services.php';
$workerServer=new \Ubiquity\servers\workerman\WorkermanServer();
$workerServer->init($config, __DIR__);
$workerServer->setDefaultCount();
$workerServer->run($sConfig['host'],$sConfig['port'],$sConfig['socket']??[]);

Fix workerman server start warnings

Fix workerman server start warnings


<?php

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

class CreateAddressesTable extends Migration
{
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('addressable');
            $table->integer('country_id')->unsigned()->index();
            $table->string('organization')->nullable();
            $table->string('name_prefix');
            $table->string('name_suffix')->nullable();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('street');
            $table->string('building_number');
            $table->string('building_flat')->nullable();
            $table->string('city');
            $table->string('city_prefix')->nullable();
            $table->string('city_suffix')->nullable();
            $table->string('state');
            $table->string('state_code')->nullable();
            $table->string('postcode');
            $table->string('phone')->nullable();
            $table->float('lat')->nullable();
            $table->float('lng')->nullable();
            foreach (config('addressable.flags', []) as $flag) {
                $table->boolean('is_'.$flag)->default(false)->index();
            }
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('addresses');
    }
}

<?php

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

class CreateAddressesTable extends Migration
{
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('addressable');
            $table->integer('country_id')->unsigned()->index();
            $table->string('organization')->nullable();
            $table->string('name_prefix');
            $table->string('name_suffix')->nullable();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('street');
            $table->string('building_number')->nullable();
            $table->string('building_flat')->nullable();
            $table->string('city');
            $table->string('city_prefix')->nullable();
            $table->string('city_suffix')->nullable();
            $table->string('state')->nullable();
            $table->string('state_code')->nullable();
            $table->string('postcode');
            $table->string('phone')->nullable();
            $table->float('lat')->nullable();
            $table->float('lng')->nullable();
            foreach (config('addressable.flags', []) as $flag) {
                $table->boolean('is_'.$flag)->default(false)->index();
            }
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('addresses');
    }
}

Make building_number and state optional

Make building_number and state optional


@title('Create your thread')

@extends('layouts.default')

@section('content')

{{ $title }}

            Please read our Forum Rules before creating a thread.

    @include('forum.threads._form', ['route' => 'threads.store'])
@endsection

@title('Create your thread')

@extends('layouts.default')

@section('content')

{{ $title }}

            Please try to search for your question first using
            the search box and make sure you've read our
            Forum Rules before creating a thread.

    @include('forum.threads._form', ['route' => 'threads.store'])
@endsection

Add a note about searching for threads first


<?php

namespace Northstar\Models;

use Jenssegers\Mongodb\Model;

class ApiKey extends Model
{
    /**
     * The database collection used by the model.
     *
     * @var string
     */
    protected $collection = 'api_keys';

    /**
     * The model's default attributes.
     *
     * @var array
     */
    protected $attributes = [
        'scope' => ['user'],
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'app_id',
        'scope',
    ];

    /**
     * Create a new API key.
     *
     * @param $attributes
     * @return ApiKey
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        // Automatically set random API key. This field *may* be manually
        // set when seeding the database, so we first check if empty.
        if (empty($this->api_key)) {
            $this->api_key = str_random(40);
        }
    }

    /**
     * Mutator for 'app_id' field.
     */
    public function setAppIdAttribute($app_id)
    {
        $this->attributes['app_id'] = snake_case(str_replace(' ', '', $app_id));
    }

    /**
     * Getter for 'scope' field.
     */
    public function getScopeAttribute()
    {
        if (empty($this->attributes['scope'])) {
            return ['user'];
        }

        $scope = $this->attributes['scope'];

        return is_string($scope) ? json_decode($scope) : $scope;
    }
}

<?php

namespace Northstar\Models;

use Jenssegers\Mongodb\Model;

class ApiKey extends Model
{
    /**
     * The database collection used by the model.
     *
     * @var string
     */
    protected $collection = 'api_keys';

    /**
     * The model's default attributes.
     *
     * @var array
     */
    protected $attributes = [
        'scope' => ['user'],
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'app_id',
        'scope',
    ];

    /**
     * Create a new API key.
     *
     * @param $attributes
     * @return ApiKey
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        // Automatically set random API key. This field *may* be manually
        // set when seeding the database, so we first check if empty.
        if (empty($this->api_key)) {
            $this->api_key = str_random(40);
        }
    }

    /**
     * Mutator for 'app_id' field.
     */
    public function setAppIdAttribute($app_id)
    {
        $this->attributes['app_id'] = snake_case(str_replace(' ', '', $app_id));
    }

    /**
     * Getter for 'scope' field.
     */
    public function getScopeAttribute()
    {
        if (empty($this->attributes['scope'])) {
            return ['user'];
        }

        return $this->attributes['scope'];
    }
}

Remove casting from scope getter.

Remove casting from scope getter.

We don’t need this, and it seemed to be causing weird issues where the
Mongo arrays were being turned into strings when experimenting with the
Artisan REPL.


<?php
namespace \SlaxWeb\Bootstrap;

use \SlaxWeb\Hooks\Hooks;
use \SlaxWeb\Registry\Container as Registry;

class Swf
{
    /**
     * Composer Autoloader
     *
     * @var object
     */
    protected $_loader = null;
    /**
     * Router
     *
     * @var \SlaxWeb\Router\Router
     */
    protected $_router = null;

    public function __construct(\Composer\Autoload\ClassLoader $loader, \SlaxWeb\Router\Router $router)
    {
        $this->_loader = $loader;
        $this->_router = $router;

        Hooks::call("bootstrap.after.construct");
    }

    public function configureAutoload()
    {
        $this->_loader->add("Controller\\", APPPATH);
        $this->_loader->add("Model\\", APPPATH);
        $this->_loader->add("View\\", APPPATH);

        Hooks::call("bootstrap.after.autoload");
    }

    public function routeRequest()
    {
        Hooks::call("bootstrap.before.route");
        require_once APPPATH . "config/routes.php";

        $route = $this->_router->process();

        Hooks::call("bootstrap.before.controller");
        if (is_object($route["action"]) && $route["action"] instanceof \Closure) {
            call_user_func_array($route["action"], $route["params"]);
        } else {
            $controller = Registry::setAlias("controller", "\\Controller\\{$route["action"][0]}");
            $controller->{$route["action"][1]}(...$route["params"]);
        }

        Hooks::call("bootstrap.after.route");
    }
}

<?php
namespace SlaxWeb\Bootstrap;

use SlaxWeb\Hooks\Hooks;
use SlaxWeb\Registry\Container as Registry;

class Swf
{
    /**
     * Composer Autoloader
     *
     * @var object
     */
    protected $_loader = null;
    /**
     * Router
     *
     * @var \SlaxWeb\Router\Router
     */
    protected $_router = null;

    public function __construct(\Composer\Autoload\ClassLoader $loader, \SlaxWeb\Router\Router $router)
    {
        $this->_loader = $loader;
        $this->_router = $router;

        Hooks::call("bootstrap.after.construct");
    }

    public function configureAutoload()
    {
        $this->_loader->add("Controller\\", APPPATH);
        $this->_loader->add("Model\\", APPPATH);
        $this->_loader->add("View\\", APPPATH);

        Hooks::call("bootstrap.after.autoload");
    }

    public function routeRequest()
    {
        Hooks::call("bootstrap.before.route");
        require_once APPPATH . "config/routes.php";

        $route = $this->_router->process();

        Hooks::call("bootstrap.before.controller");
        if (is_object($route["action"]) && $route["action"] instanceof \Closure) {
            call_user_func_array($route["action"], $route["params"]);
        } else {
            $controller = Registry::setAlias("controller", "\\Controller\\{$route["action"][0]}");
            $controller->{$route["action"][1]}(...$route["params"]);
        }

        Hooks::call("bootstrap.after.route");
    }
}

Fix declaration of namespace and uses

Fix declaration of namespace and uses