{!! '<?'.'php' !!}
declare(strict_types=1);

namespace phln\{{$ns}};

use function phln\fn\curry;
use const phln\fn\nil;

const {{$name}} = '\\phln\\{{$ns}}\\𝑓{{$name}}';

function {{$name}}()
{
    return curry({{$name}});
}

function 𝑓{{$name}}()
{
}

{!! '<?'.'php' !!}
declare(strict_types=1);

namespace phln\{{$ns}};

use function phln\fn\curry;
use const phln\fn\nil;

const {{$name}} = '\\phln\\{{$ns}}\\{{$name}}';
const 𝑓{{$name}} = '\\phln\\{{$ns}}\\𝑓{{$name}}';

function {{$name}}()
{
    return curry(𝑓{{$name}});
}

function 𝑓{{$name}}()
{
}

Add new const to function template

Add new const to function template


<?php

if( ! defined( 'ABSPATH' ) ) exit;

class Cuztom_Field_Wysiwyg extends Cuztom_Field
{
	var $_supports_ajax			= true;
	var $_supports_bundle		= true;

	function __construct( $field, $parent )
	{
		parent::__construct( $field, $parent );

		$this->args = array_merge(
			array(
				'textarea_name' => 'cuztom[' . $this->id . ']',
				'editor_class'	=> ''
			),
			$this->args
		);

		$this->args['editor_class'] .= ' cuztom-input';
	}

	function _output( $value )
	{
		$this->args['textarea_name'] = 'cuztom' . $this->pre . '[' . $this->id . ']' . $this->after;
		return wp_editor( ( ! empty( $value ) ? $value : $this->default_value ), $this->pre_id . $this->id . $this->after_id, $this->args ) . $this->output_explanation();
	}

	function save_value( $value ) {
		return wpautop( $value );
	}
}

<?php

if( ! defined( 'ABSPATH' ) ) exit;

class Cuztom_Field_Wysiwyg extends Cuztom_Field
{
	var $_supports_ajax			= true;
	var $_supports_bundle		= true;

	function __construct( $field, $parent )
	{
		parent::__construct( $field, $parent );

		$this->args = array_merge(
			array(
				'textarea_name' => 'cuztom[' . $this->id . ']',
				'editor_class'	=> ''
			),
			$this->args
		);

		$this->args['editor_class'] .= ' cuztom-input';
	}

	function _output( $value )
	{
		$this->args['textarea_name'] = 'cuztom' . $this->pre . '[' . $this->id . ']' . $this->after;
		return wp_editor( ( ! empty( $value ) ? $value : $this->default_value ), $this->pre_id . $this->id . $this->after_id, $this->args ) . $this->output_explanation();
	}
}

Remove wpautop from wysiwyg field

Remove wpautop from wysiwyg field


<?php
namespace GeekCache\Cache;

class MemcachedServiceProvider
{
    public function __construct($container)
    {
        $this->container = $container;
    }

    public function register()
    {
        $this->container['geekcache.memcached'] = $this->container->share(function ($c) {
            $memcached = new \Memcached();

            $servers = isset($c['geekcache.memcached.servers'])
                ? $c['geekcache.memcached.servers']
                : array('localhost' => array(11211));

            foreach ($servers as $ip => $ports) {
                foreach ($ports as $port) {
                    $flatServers[] = array($ip, (int)$port);
                }
            };

            $memcached->addServers($flatServers);
            return $memcached;
        });

        $this->container['geekcache.persistentincrementablecache.unnamespaced'] = $this->container->share(function ($c) {
            return new IncrementableMemcachedCache($c['geekcache.memcached']);
        });

        $this->container['geekcache.persistentcache.unnamespaced'] = $this->container->share(function ($c) {
            return new MemcachedCache($c['geekcache.memcached']);
        });
    }
}

<?php
namespace GeekCache\Cache;

class MemcachedServiceProvider
{
    public function __construct($container)
    {
        $this->container = $container;
    }

    public function register()
    {
        $this->container['geekcache.memcached'] = $this->container->share(function ($c) {
            $memcached = new \Memcached();

            $servers = isset($c['geekcache.memcache.servers'])
                ? $c['geekcache.memcache.servers']
                : array('localhost' => array(11211));

            foreach ($servers as $ip => $ports) {
                foreach ($ports as $port) {
                    $flatServers[] = array($ip, (int)$port);
                }
            };

            $memcached->addServers($flatServers);
            return $memcached;
        });

        $this->container['geekcache.persistentincrementablecache.unnamespaced'] = $this->container->share(function ($c) {
            return new IncrementableMemcachedCache($c['geekcache.memcached']);
        });

        $this->container['geekcache.persistentcache.unnamespaced'] = $this->container->share(function ($c) {
            return new MemcachedCache($c['geekcache.memcached']);
        });
    }
}

Use the same name for the servers for the memcached and memcache service providers


<?php
include '../../config/config.php';
$referer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-');
$cookies = (isset($_GET['cookie']) ? $_GET['cookie'] : '-');
$cookies = preg_split('/;\s*/', $cookies);
$ip = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-');
$message = "IP: $ip\n"
	. "Referer: $referer\n"
	. "Cookies:\n"
	. implode("\n", $cookies);
mail($mailTo, 'Stolen session', $message, "From: $mailFrom");

<?php
include '../../config/config.php';
$referer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-');
$cookies = (isset($_GET['cookie']) ? $_GET['cookie'] : '');
$cookies = preg_split('/;\s*/', $cookies, flags: PREG_SPLIT_NO_EMPTY);
$ip = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-');
$message = "IP: $ip\n"
	. "Referer: $referer\n"
	. "Cookies:\n"
	. implode("\n", $cookies);
if ($cookies) {
	mail($mailTo, 'Stolen session', $message, "From: $mailFrom");
}

Send email only when some cookies are passed


<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
 */

namespace Drupal\AppConsole\Generator;

class PluginBlockGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  $module
   * @param  $class_name
   * @param  $plugin_label
   * @param  $plugin_id
   * @param  $services
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
  {
    $path = DRUPAL_ROOT.'/'.drupal_get_path('module', $module);
    $path_plugin = $path.'/src/Plugin/Block';

    // set syntax for arguments
    $args = ', ';
    $i = 0;
    foreach ($services as $service) {
      $args .= $service['short'] . ' $' . $service['machine_name'];
      if ( ++$i != count($services)) {
        $args .= ', ';
      }
    }

    $parameters = [
      'module'   => $module,
      'class'     => [
        'name'      => $class_name,
        'underscore' => $this->camelCaseToUnderscore($class_name)
      ],
      'plugin_label' => $plugin_label,
      'plugin_id' => $plugin_id,
      'services'    => $services,
      'args'   => $args
    ];

    $this->renderFile(
      'module/plugin-block.php.twig',
      $path_plugin.'/'.$class_name.'.php',
      $parameters
    );
  }

}

<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
 */

namespace Drupal\AppConsole\Generator;

class PluginBlockGenerator extends Generator
{
  /**
   * Generator Plugin Block
   * @param  $module
   * @param  $class_name
   * @param  $plugin_label
   * @param  $plugin_id
   * @param  $services
   */
  public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
  {
    // set syntax for arguments
    $args = ', ';
    $i = 0;
    foreach ($services as $service) {
      $args .= $service['short'] . ' $' . $service['machine_name'];
      if ( ++$i != count($services)) {
        $args .= ', ';
      }
    }

    $parameters = [
      'module'   => $module,
      'class'     => [
        'name'      => $class_name,
        'underscore' => $this->camelCaseToUnderscore($class_name)
      ],
      'plugin_label' => $plugin_label,
      'plugin_id' => $plugin_id,
      'services'    => $services,
      'args'   => $args
    ];

    $this->renderFile(
      'module/plugin-block.php.twig',
      $path_plugin.'/'.$class_name.'.php',
      $parameters
    );
  }

}

Remove local vars path & path_plugin

Remove local vars path & path_plugin


<!---
<?php
if (!empty(Yii::app()->session['user'])) {
	$user = Yii::app()->session['user'];
} else {
	$user = User::model()->findByPk(Yii::app()->user->id);
}
$firm = Firm::model()->findByPk($this->selectedFirmId);

if (file_exists("/etc/hostname")) {
	$hostname = trim(file_get_contents("/etc/hostname"));
} else {
	$hostname = trim(`hostname`);
}

if (is_object($user)) {
	$username = "$user->username ($user->id)";
	$firm = "$firm->name ($firm->id)";
} else {
	$username = 'Not logged in';
	$firm = 'Not logged in';
}

$commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD"));
?>
Server: <?php echo $hostname?>

Date: <?php echo date('d.m.Y H:i:s')?>

Commit: <?php echo $commit?>

User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?>

Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?>

Username: <?php echo $username?>

Firm: <?php echo $firm?>

-->

<!---
<?php
if (!empty(Yii::app()->session['user'])) {
	$user = Yii::app()->session['user'];
} else {
	$user = User::model()->findByPk(Yii::app()->user->id);
}
$firm = Firm::model()->findByPk($this->selectedFirmId);

if (file_exists("/etc/hostname")) {
	$hostname = trim(file_get_contents("/etc/hostname"));
} else {
	$hostname = trim(`hostname`);
}

if (is_object($user)) {
	$username = "$user->username ($user->id)";
	if($firm) {
		$firm = "$firm->name ($firm->id)";
	} else {
		$firm = 'Not found'; // selectedFirmId seems to not be getting initialised sometimes
	}
} else {
	$username = 'Not logged in';
	$firm = 'Not logged in';
}

$commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD"));
?>
Server: <?php echo $hostname?>

Date: <?php echo date('d.m.Y H:i:s')?>

Commit: <?php echo $commit?>

User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?>

Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?>

Username: <?php echo $username?>

Firm: <?php echo $firm?>

-->

Check firm object exists to avoid error

Check firm object exists to avoid error


<?php

namespace GeniusTS\Preferences\Models;

use Illuminate\Contracts\View\View;

/**
 * Class Element
 *
 * @package GeniusTS\Preferences
 * @property string $name
 * @property string $namespace
 * @property string $rules
 * @property View   $view
 */
class Element
{

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $namespace;

    /**
     * @var string
     */
    protected $rules;

    /**
     * Element constructor.
     *
     * @param string $name
     * @param null   $rules
     */
    public function __construct($name, $rules = null)
    {
        $this->name = $name;

        if (is_string($rules))
        {
            $this->rules = $rules;
        }
    }

    /**
     * Set the name space of element
     *
     * @param string $namespace
     *
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @param string $property
     *
     * @return null
     */
    public function __get($property)
    {
        if (property_exists($this, $property))
        {
            return $this->{$property};
        }

        return null;
    }
}

<?php

namespace GeniusTS\Preferences\Models;

use Illuminate\Contracts\View\View;

/**
 * Class Element
 *
 * @package GeniusTS\Preferences
 * @property string $name
 * @property string $namespace
 * @property string $rules
 * @property View   $view
 */
class Element
{

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $namespace;

    /**
     * @var string
     */
    protected $rules;

    /**
     * Element constructor.
     *
     * @param string $name
     * @param string $rules
     */
    public function __construct($name, $rules = '')
    {
        $this->name = $name;

        if (is_string($rules))
        {
            $this->rules = $rules;
        }
    }

    /**
     * Set the name space of element
     *
     * @param string $namespace
     *
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @param string $property
     *
     * @return null
     */
    public function __get($property)
    {
        if (property_exists($this, $property))
        {
            return $this->{$property};
        }

        return null;
    }
}

Make the default rules as string

Make the default rules as string


<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

Use fullpath for validator facade

Use fullpath for validator facade

Added fullpath import for the validator facade.


<?php

use App\Controllers\HomeController;
use App\Controllers\LeadController;
use App\Controllers\ErrorController;
use App\Controllers\ThanksController;

$app->get('/', [HomeController::class, 'index']);
$app->post('/store', [LeadController::class, 'store']);
$app->get('/error', [ErrorControllerController::class, 'index']);
$app->get('/thanks', [ThanksController::class, 'index']);

<?php

use App\Controllers\HomeController;
use App\Controllers\LeadController;
use App\Controllers\ErrorController;
use App\Controllers\ThanksController;

$app->get('/', [HomeController::class, 'index']);
$app->post('/store', [LeadController::class, 'store']);
$app->get('/error', [ErrorController::class, 'index']);
$app->get('/thanks', [ThanksController::class, 'index']);

Fix typo in route error

Fix typo in route error


<?php

namespace Northstar\Auth\Repositories;

use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use Northstar\Auth\Entities\ClientEntity;
use Northstar\Models\Client;

class ClientRepository implements ClientRepositoryInterface
{
    /**
     * Get a client.
     *
     * @param string      $clientIdentifier   The client's identifier
     * @param string      $grantType          The grant type used
     * @param null|string $clientSecret       The client's secret (if sent)
     * @param bool        $mustValidateSecret If true the client must attempt to validate the secret unless the client
     *                                        is confidential
     *
     * @return \League\OAuth2\Server\Entities\ClientEntityInterface
     */
    public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
    {
        // Fetch client from the database.
        $model = Client::where('client_id', $clientIdentifier)->first();
        if (! $model) {
            return null;
        }

        // If the grant requires us to check the client secret, do that.
        if ($mustValidateSecret && $model->client_secret !== $clientSecret) {
            return null;
        }

        return new ClientEntity($model->client_id, $model->scope);
    }
}

<?php

namespace Northstar\Auth\Repositories;

use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use Northstar\Auth\Entities\ClientEntity;
use Northstar\Models\Client;

class ClientRepository implements ClientRepositoryInterface
{
    /**
     * Get a client.
     *
     * @param string      $clientIdentifier   The client's identifier
     * @param string      $grantType          The grant type used
     * @param null|string $clientSecret       The client's secret (if sent)
     * @param bool        $mustValidateSecret If true the client must attempt to validate the secret unless the client
     *                                        is confidential
     *
     * @return \League\OAuth2\Server\Entities\ClientEntityInterface
     */
    public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
    {
        // Fetch client from the database.
        $model = Client::where('client_id', $clientIdentifier)->first();
        if (! $model) {
            return null;
        }

        // Is this client allowed to use this grant type?
        if (! $this->clientCanUseGrant($model, $grantType)) {
            return null;
        }

        // If the grant requires us to check the client secret, do that.
        if ($mustValidateSecret && $model->client_secret !== $clientSecret) {
            return null;
        }

        return new ClientEntity($model->client_id, $model->scope);
    }

    /**
     * Is the given client allowed to use the given grant type?
     *
     * @param $client
     * @param $grantType
     * @return bool
     */
    public function clientCanUseGrant($client, $grantType)
    {
        // @TODO: Limit this based on the 'allowed_grants' field on the Client.
        return true;
    }
}

Add method for limiting clients by grant.


<?php

namespace Noodlehaus\FileParser;

use Exception;
use Noodlehaus\Exception\ParseException;
use Noodlehaus\Exception\UnsupportedFormatException;

/**
 * PHP file parser
 *
 * @package    Config
 * @author     Jesus A. Domingo <jesus.domingo@gmail.com>
 * @author     Hassan Khan <contact@hassankhan.me>
 * @link       https://github.com/noodlehaus/config
 * @license    MIT
 */
class Php implements FileParserInterface
{
    /**
     * {@inheritDoc}
     * Loads a PHP file and gets its' contents as an array
     *
     * @throws ParseException             If the PHP file throws an exception
     * @throws UnsupportedFormatException If the PHP file does not return an array
     */
    public function parse($path)
    {
        // Require the file, if it throws an exception, rethrow it
        try {
            $temp = require $path;
        } catch (Exception $exception) {
            throw new ParseException(
                array(
                    'message'   => 'PHP file threw an exception',
                    'exception' => $exception,
                )
            );
        }

        // If we have a callable, run it and expect an array back
        if (is_callable($temp)) {
            $temp = call_user_func($temp);
        }

        // Check for array, if its anything else, throw an exception
        if (!$temp || !is_array($temp)) {
            throw new UnsupportedFormatException('PHP file does not return an array');
        }

        return $temp;
    }

    /**
     * {@inheritDoc}
     */
    public function getSupportedExtensions()
    {
        return array('php');
    }
}

<?php

namespace Noodlehaus\FileParser;

use Exception;
use Noodlehaus\Exception\ParseException;
use Noodlehaus\Exception\UnsupportedFormatException;

/**
 * PHP file parser
 *
 * @package    Config
 * @author     Jesus A. Domingo <jesus.domingo@gmail.com>
 * @author     Hassan Khan <contact@hassankhan.me>
 * @link       https://github.com/noodlehaus/config
 * @license    MIT
 */
class Php implements FileParserInterface
{
    /**
     * {@inheritDoc}
     * Loads a PHP file and gets its' contents as an array
     *
     * @throws ParseException             If the PHP file throws an exception
     * @throws UnsupportedFormatException If the PHP file does not return an array
     */
    public function parse($path)
    {
        // Require the file, if it throws an exception, rethrow it
        try {
            $temp = require $path;
        } catch (Exception $exception) {
            throw new ParseException(
                array(
                    'message'   => 'PHP file threw an exception',
                    'exception' => $exception,
                )
            );
        }

        // If we have a callable, run it and expect an array back
        if (is_callable($temp)) {
            $temp = call_user_func($temp);
        }

        // Check for array, if its anything else, throw an exception
        if (!is_array($temp)) {
            throw new UnsupportedFormatException('PHP file does not return an array');
        }

        return $temp;
    }

    /**
     * {@inheritDoc}
     */
    public function getSupportedExtensions()
    {
        return array('php');
    }
}

Remove !$temp check to fix loading an empty array


<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;

class Paragraph extends Node implements NodeAcceptorInterface
{

    /**
     * @var Collection
     */
    protected $lines;

    public function __construct(Text $text)
    {
        $this->lines = new Collection([$text]);
    }

    public function getText()
    {
        return (new Text($this->lines->join("\n")))->trim();
    }

    public function acceptParagraph(Paragraph $paragraph)
    {
        $paragraph->lines->each(function (Text $line) {
            $this->lines->add($line);
        });

        return $this;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        return $this->parent;
    }

    public function acceptCodeBlock(CodeBlock $codeBlock)
    {
        $codeBlock->getLines()->each(function (Text $line) {
            $this->lines->add($line->prepend('    '));
        });

        return $this;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->enterParagraph($this);

        $visitor->leaveParagraph($this);
    }

}

<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;

class Paragraph extends Node implements NodeAcceptorInterface
{

    /**
     * @var Collection
     */
    protected $lines;

    public function __construct(Text $text)
    {
        $this->lines = new Collection([$text]);
    }

    public function getText()
    {
        return (new Text($this->lines->apply(function (Text $line) {
            return $line->copy()->ltrim();
        })->join("\n")))->trim();
    }

    public function acceptParagraph(Paragraph $paragraph)
    {
        $paragraph->lines->each(function (Text $line) {
            $this->lines->add($line);
        });

        return $this;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        return $this->parent;
    }

    public function acceptCodeBlock(CodeBlock $codeBlock)
    {
        $codeBlock->getLines()->each(function (Text $line) {
            $this->lines->add($line->prepend('    '));
        });

        return $this;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->enterParagraph($this);

        $visitor->leaveParagraph($this);
    }

}

Trim beginning of every line in a paragraph.


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

trait Escaper
{
    /**
     * Escape all values of row.
     *
     * @param array $row
     *
     * @return array
     */
    protected function escapeRow(array $row): array
    {
        $arrayDot = array_filter(array_dot($row));

        foreach ($arrayDot as $key => $value) {
            $arrayDot[$key] = e($value);
        }

        foreach ($arrayDot as $key => $value) {
            array_set($row, $key, $value);
        }

        return $row;
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

trait Escaper
{
    /**
     * Escape all values.
     *
     * @param array $data
     *
     * @return array
     */
    protected function escape(array $data): array
    {
        $arrayDot = array_filter(array_dot($data));

        foreach ($arrayDot as $key => $value) {
            $arrayDot[$key] = e($value);
        }

        foreach ($arrayDot as $key => $value) {
            array_set($data, $key, $value);
        }

        return $data;
    }
}

Rename "escapeRow" method to just "escape"


<?php

namespace CartRover;

class Orders extends APIObject {

	/**
	 * Insert one or more orders into CartRover
	 * @param string $api_user
	 * @param string $api_key
	 * @param array $orders_array Array of orders, even if only one
	 * @return array
	 */
	public static function CreateOrders($api_user, $api_key, $orders_array){
		$endpoint = '/cart/orders/cartrover';
		return APIObject::make_api_call($api_user, $api_key, $endpoint, $orders_array);
	}

	/**
	 * Cancel an order in CartRover. This may fail if you wait too long to cancel the order after its creation
	 * @param string $api_user
	 * @param string $api_key
	 * @param array $cust_ref cust_ref of order to cancel
	 * @return array
	 */
	public static function CancelOrder($api_user, $api_key, $cust_ref){
		$endpoint = '/cart/orders/cancel/cartrover';
		$post_array = array(
			array(
				'cust_ref' => $cust_ref
			)
		);
		return APIObject::make_api_call($api_user, $api_key, $endpoint, $post_array);
	}

}

<?php

namespace CartRover;

class Orders extends APIObject {

	/**
	 * Insert one or more orders into CartRover
	 * @param string $api_user
	 * @param string $api_key
	 * @param array $orders_array Array of orders, even if only one
	 * @return array
	 */
	public static function CreateOrders($api_user, $api_key, $orders_array){
		$endpoint = '/cart/orders/cartrover';
		return APIObject::make_api_call($api_user, $api_key, $endpoint, $orders_array);
	}

	/**
	 * Cancel an order in CartRover. This may fail if you wait too long to cancel the order after its creation
	 * @param string $api_user
	 * @param string $api_key
	 * @param array $cust_ref cust_ref of order to cancel
	 * @return array
	 */
	public static function CancelOrder($api_user, $api_key, $cust_ref){
		$endpoint = '/cart/orders/cancel/cartrover';
		$post_array = array(
			'cust_ref' => $cust_ref
		);
		return APIObject::make_api_call($api_user, $api_key, $endpoint, $post_array);
	}

}

Order cancel - don't pass mutli-D array

Order cancel - don't pass mutli-D array


<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class TasksMassEditType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('priority', ChoiceType::class, array(
                'choices' => array(
                    -1 => 'Low',
                    0 => 'Normal',
                    1 => 'Important',
                ),
                'expanded' => true,
                'label_attr' => array('class' => 'radio-inline')
            ))
            ->add('urgency', ChoiceType::class, array(
                'choices' => array(
                    0 => 'Not Urgent',
                    1 => 'Urgent',
                ),
                'expanded' => true,
                'label_attr' => array('class' => 'radio-inline')
            ))
            ->add('taskList', EntityType::class, array('class' => \AppBundle\Entity\TaskLists::class, 'choice_label' => 'name'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => \AppBundle\Entity\Tasks::class
        ));
    }

}

<?php

namespace AppBundle\Form;

use AppBundle\Entity\TaskLists;
use AppBundle\Entity\Tasks;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class TasksMassEditType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('priority', ChoiceType::class, array(
                'choices' => [
                    'Low' => -1,
                    'Normal' => 0,
                    'Important' => 1,
                ],
                'expanded' => true,
                'label_attr' => array('class' => 'radio-inline')
            ))
            ->add('urgency', ChoiceType::class, array(
                'choices' => array(
                    'Not Urgent' => 0,
                    'Urgent' => 1,
                ),
                'expanded' => true,
                'label_attr' => array('class' => 'radio-inline')
            ))
            ->add('taskList', EntityType::class, array('class' => TaskLists::class, 'choice_label' => 'name'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Tasks::class
        ));
    }

}

Manage list task priority & urgency bug fix


Improve phonenumber formats for nl_NL

Improve phonenumber formats for nl_NL


<?php

namespace Tests\Functional;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class NavigationTest extends \Tests\TestCase {

    use DatabaseMigrations;

    public function testGuestNavigation()
    {
        $this->get('/')
            ->assertSee('Log In')
            ->assertSee('href="/login"')
            ->assertDontSee('My List')
            ->assertDontSee('/list');
    }

    public function testUserListNavigation()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('My List')
            ->assertSee('/list')
            ->assertDontSee('Login')
            ->assertDontSee('href="/login"');
    }

    public function testUserAccountNavigation()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee($user->username)
            ->assertSee('href="/account"');
    }

    public function testUserAccountLogOut()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('Log Out')
            ->assertSee('href="/logout"');
    }

}

<?php

namespace Tests\Functional;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class NavigationTest extends \Tests\TestCase {

    use DatabaseMigrations;

    public function testGuestNavigation()
    {
        $this->get('/')
            ->assertSee('Log In')
            ->assertSee('href="/login"')
            ->assertDontSee('My List')
            ->assertDontSee('/list');
    }

    public function testUserListNavigation()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('My List')
            ->assertSee('/list')
            ->assertDontSee('Login')
            ->assertDontSee('href="/login"');
    }

    public function testUserAccountNavigation()
    {
        $user = factory(User::class)->create();
        $encodedUsername = htmlentities(
            $user->username,
            ENT_COMPAT | ENT_HTML401 | ENT_QUOTES
        );

        $this->actingAs($user)
            ->get('/')
            ->assertSee($encodedUsername)
            ->assertSee('href="/account"');
    }

    public function testUserAccountLogOut()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->get('/')
            ->assertSee('Log Out')
            ->assertSee('href="/logout"');
    }

}

Fix tests when username has a ' character in it

Laravel HTML entity encodes the username, so we need to do the same
thing in the test so the HTML output will match.


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Event\TestRunner;

use function array_merge;
use function asort;
use function extension_loaded;
use function get_loaded_extensions;
use ArrayIterator;
use IteratorAggregate;

final class Extensions implements IteratorAggregate
{
    public function loaded(string $name): bool
    {
        return extension_loaded($name);
    }

    public function getIterator()
    {
        $all = array_merge(
            get_loaded_extensions(true),
            get_loaded_extensions(false)
        );

        asort($all);

        return new ArrayIterator($all);
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Event\TestRunner;

use function array_merge;
use function asort;
use function extension_loaded;
use function get_loaded_extensions;
use ArrayIterator;
use IteratorAggregate;

final class Extensions implements IteratorAggregate
{
    public function loaded(string $name): bool
    {
        return extension_loaded($name);
    }

    /**
     * @return ArrayIterator<int, string>
     */
    public function getIterator(): ArrayIterator
    {
        $all = array_merge(
            get_loaded_extensions(true),
            get_loaded_extensions(false)
        );

        asort($all);

        return new ArrayIterator($all);
    }
}

Enhancement: Add return type declaration and DocBlock

Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>


<?php

namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;

use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;

class NavigationExtensionTest extends TestCase
{
    /**
     * @dataProvider provideGetAncestorData
     */
    public function testGetAncestor(Item $item, $level, ?Item $ancestor)
    {
        $ext = new NavigationExtension('foo.bar.twig');
        $this->assertSame($ancestor, $ext->getAncestor($item, $level));
    }

    public function provideGetAncestorData()
    {
        $root = new Item();
        $level1 = new Item();
        $level1->setParent($root);
        $level2 = new Item();
        $level2->setParent($level1);

        return [
            [$root, 0, $root],
            [$root, 1, null],
            [$root, -1, null],

            [$level1, 0, $root],
            [$level1, -1, $root],
            [$level1, '-1', $root],
            [$level1, '-9', null],
            [$level1, 9, null],

            [$level2, 1, $level1],
            [$level2, '2', $level2],
            [$level2, '0', $root],
            [$level2, 'foo', null],
        ];
    }
}

<?php

namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;

use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;

class NavigationExtensionTest extends TestCase
{
    /**
     * @dataProvider provideGetAncestorData
     */
    public function testGetAncestor(Item $item, $level, Item $ancestor = null)
    {
        $ext = new NavigationExtension('foo.bar.twig');
        $this->assertSame($ancestor, $ext->getAncestor($item, $level));
    }

    public function provideGetAncestorData()
    {
        $root = new Item();
        $level1 = new Item();
        $level1->setParent($root);
        $level2 = new Item();
        $level2->setParent($level1);

        return [
            [$root, 0, $root],
            [$root, 1, null],
            [$root, -1, null],

            [$level1, 0, $root],
            [$level1, -1, $root],
            [$level1, '-1', $root],
            [$level1, '-9', null],
            [$level1, 9, null],

            [$level2, 1, $level1],
            [$level2, '2', $level2],
            [$level2, '0', $root],
            [$level2, 'foo', null],
        ];
    }
}

Fix a test to work on php 7.1

Fix a test to work on php 7.1


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Markdown\Listener;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;

class FormatMarkdown
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'addMarkdownFormatter']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function addMarkdownFormatter(ConfigureFormatter $event)
    {
        $event->configurator->Litedown;
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Markdown\Listener;

use Flarum\Formatter\Event\Configuring;
use Illuminate\Contracts\Events\Dispatcher;

class FormatMarkdown
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(Configuring::class, [$this, 'addMarkdownFormatter']);
    }

    /**
     * @param Configuring $event
     */
    public function addMarkdownFormatter(Configuring $event)
    {
        $event->configurator->Litedown;
    }
}

Update namespaces for beta 8

Update namespaces for beta 8

Refs flarum/core#1235.


<?php

namespace Michaeljennings\Carpenter\Tests;

use Michaeljennings\Carpenter\Carpenter;
use PHPUnit_Framework_TestCase;

class TestCase extends PHPUnit_Framework_TestCase
{
	public function __construct()
    {
        // Fixes error with session_start() and phpunit
        ob_start();
    }

    public function setUp()
    {
        // Fixes issues with session_start and phpunit
        @session_start();
    }

	protected function makeCarpenter()
    {
        $config = $this->getConfig();

        return new Carpenter($config);
    }

    protected function makeTable()
    {
        $carpenter = $this->makeCarpenter();

        return $carpenter->make('test', function ($table) {});
    }

    protected function getConfig()
    {
        return require __DIR__ . '/../config/config.php';
    }
}

<?php

namespace Michaeljennings\Carpenter\Tests;

use Michaeljennings\Carpenter\Carpenter;
use PHPUnit_Framework_TestCase;

class TestCase extends PHPUnit_Framework_TestCase
{
	public function __construct()
    {
        // Fixes error with session_start() and phpunit
        ob_start();
    }

    public function setUp()
    {
        // Fixes issues with session_start and phpunit
        @session_start();
    }

	protected function makeCarpenter()
    {
        $config = $this->getConfig();

        return new Carpenter($config);
    }

    protected function makeTable()
    {
        $carpenter = $this->makeCarpenter();

        return $carpenter->make('test', function ($table) {});
    }

    protected function getData()
    {
        return [
            [
                'test' => 'Test',
                'foo' => 'bar',
                'baz' => 'qux',
            ],
            [
                'test' => 'Test',
                'foo' => 'bar',
                'baz' => 'qux',
            ],
            [
                'test' => 'Test',
                'foo' => 'bar',
                'baz' => 'qux',
            ],
        ];
    }

    protected function getConfig()
    {
        return require __DIR__ . '/../config/config.php';
    }
}

Add get data method to test case

Add get data method to test case


<?php

namespace Recruiter;

use MongoDB;

class FactoryTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->factory = new Factory();
        $this->dbHost = 'localhost:27017';
        $this->dbName = 'recruiter';
    }

    public function testShouldCreateAMongoDatabaseConnection()
    {
        $this->assertInstanceOf(
            'MongoDB',
            $this->creationOfDefaultMongoDb()
        );
    }

    public function testWriteConcernIsMajorityByDefault()
    {
        $mongoDb = $this->creationOfDefaultMongoDb();
        $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']);
    }

    public function testShouldOverwriteTheWriteConcernPassedInTheOptions()
    {
        $mongoDb = $this->factory->getMongoDb(
                $host = 'localhost:27017',
                $options = [
                    'connectTimeoutMS' => '1000',
                    'w' => '0',
                ],
                $dbName = 'recruiter'
        );

        $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']);
    }

    private function creationOfDefaultMongoDb()
    {
        return $this->factory->getMongoDb(
             $host = $this->dbHost,
             $options = ['connectTimeoutMS' => '1000'],
             $dbName = $this->dbName
        );
    }
}

<?php

namespace Recruiter;

use MongoDB;

class FactoryTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->factory = new Factory();
        $this->dbHost = 'localhost:27017';
        $this->dbName = 'recruiter';
    }

    public function testShouldCreateAMongoDatabaseConnection()
    {
        $this->assertInstanceOf(
            'MongoDB',
            $this->creationOfDefaultMongoDb()
        );
    }

    public function testWriteConcernIsMajorityByDefault()
    {
        $mongoDb = $this->creationOfDefaultMongoDb();
        $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']);
    }

    public function testShouldOverwriteTheWriteConcernPassedInTheOptions()
    {
        $mongoDb = $this->factory->getMongoDb(
                $host = 'localhost:27017',
                $options = [
                    'connectTimeoutMS' => 1000,
                    'w' => '0',
                ],
                $dbName = 'recruiter'
        );

        $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']);
    }

    private function creationOfDefaultMongoDb()
    {
        return $this->factory->getMongoDb(
             $host = $this->dbHost,
             $options = ['connectTimeoutMS' => 1000],
             $dbName = $this->dbName
        );
    }
}

Fix wrong type (Travis complaint)

Fix wrong type (Travis complaint)


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\AdminBundle\EmailManager;

use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;

final class ShipmentEmailManager implements ShipmentEmailManagerInterface
{
    /** @var SenderInterface */
    private $emailSender;

    public function __construct(SenderInterface $emailSender)
    {
        $this->emailSender = $emailSender;
    }

    /**
     * {@inheritdoc}
     */
    public function sendConfirmationEmail(ShipmentInterface $shipment): void
    {
        /** @var OrderInterface $order */
        $order = $shipment->getOrder();

        $this->emailSender->send(Emails::SHIPMENT_CONFIRMATION, [$order->getCustomer()->getEmail()], [
            'shipment' => $shipment,
            'order' => $order,
        ]);
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\AdminBundle\EmailManager;

use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;

final class ShipmentEmailManager implements ShipmentEmailManagerInterface
{
    /** @var SenderInterface */
    private $emailSender;

    public function __construct(SenderInterface $emailSender)
    {
        $this->emailSender = $emailSender;
    }

    /**
     * {@inheritdoc}
     */
    public function sendConfirmationEmail(ShipmentInterface $shipment): void
    {
        /** @var OrderInterface $order */
        $order = $shipment->getOrder();

        $this->emailSender->send(Emails::SHIPMENT_CONFIRMATION, [$order->getCustomer()->getEmail()], [
            'shipment' => $shipment,
            'order' => $order,
            'channel' => $order->getChannel(),
        ]);
    }
}

Add documentation for customising emails per channel


<?php

declare(strict_types=1);

namespace Rector\Core\Error;

use PHPStan\AnalysedCodeException;
use Rector\Core\Contract\Rector\RectorInterface;
use Throwable;

final class ExceptionCorrector
{
    public function matchRectorClass(Throwable $throwable): ?string
    {
        if (! isset($throwable->getTrace()[0])) {
            return null;
        }

        if (! isset($throwable->getTrace()[0]['class'])) {
            return null;
        }

        /** @var string $class */
        $class = $throwable->getTrace()[0]['class'];
        if (! is_a($class, RectorInterface::class, true)) {
            return null;
        }

        return $class;
    }

    public function getAutoloadExceptionMessageAndAddLocation(AnalysedCodeException $analysedCodeException): string
    {
        return sprintf(
            'Analyze error: "%s". Include your files in "parameters > autoload_paths".%sSee https://github.com/rectorphp/rector#configuration',
            $analysedCodeException->getMessage(),
            PHP_EOL
        );
    }
}

<?php

declare(strict_types=1);

namespace Rector\Core\Error;

use PHPStan\AnalysedCodeException;
use Rector\Core\Contract\Rector\RectorInterface;
use Throwable;

final class ExceptionCorrector
{
    public function matchRectorClass(Throwable $throwable): ?string
    {
        if (! isset($throwable->getTrace()[0])) {
            return null;
        }

        if (! isset($throwable->getTrace()[0]['class'])) {
            return null;
        }

        /** @var string $class */
        $class = $throwable->getTrace()[0]['class'];
        if (! is_a($class, RectorInterface::class, true)) {
            return null;
        }

        return $class;
    }

    public function getAutoloadExceptionMessageAndAddLocation(AnalysedCodeException $analysedCodeException): string
    {
        return sprintf(
            'Analyze error: "%s". Include your files in "$parameters->set(Option::AUTOLOAD_PATHS, [...]));" in "rector.php" config.%sSee https://github.com/rectorphp/rector#configuration',
            $analysedCodeException->getMessage(),
            PHP_EOL
        );
    }
}

Improve autoload paths parameter name

[DX] Improve autoload paths parameter name


<?php

class FacebookMetadataSiteConfig extends DataExtension {

    static $db = array(
        'SkipToMainContentAccessKey' => 'VarChar(1)'
    );

    static $has_one = array(
        'FacebookLogo' => 'Image'
    );

    public function updateCMSFields(FieldList $fields) {
	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.FacebookMetadata', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
        $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square')));
	}

}
?>

<?php

class FacebookMetadataSiteConfig extends DataExtension {

    static $db = array(
        'SkipToMainContentAccessKey' => 'VarChar(1)'
    );

    static $has_one = array(
        'FacebookLogo' => 'Image'
    );

    public function updateCMSFields(FieldList $fields) {

	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
        $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO',
            'Image that will show in facebook when linking to this site. The image should be a square of minimum size 200px')));
	}

}
?>

FIX: Remove empty field, hangover from access keys module


<?php

namespace Edge\Filter;

use Zend\Filter\FilterInterface;

class StrReplace implements FilterInterface
{
    protected $search;

    protected $replace;

    public function __construct($search, $replace)
    {
        $this->search  = $search;
        $this->replace = $replace;
    }

    public function filter($value)
    {
        if (null !== $value) {
            $value = str_replace($this->search, $this->replace, $value);
        }
        return $value;
    }
}

<?php

namespace Edge\Filter;

use Zend\Filter\FilterInterface;

class StrReplace implements FilterInterface
{
    protected $search;

    protected $replace;

    public function __construct($search, $replace)
    {
        $this->search  = $search;
        $this->replace = $replace;
    }

    public function filter($value)
    {
        if (is_string($value)) {
            $value = str_replace($this->search, $this->replace, $value);
        }

        return $value;
    }
}

Check if value is a string first

Check if value is a string first


<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Field\Scalar;

use InvalidArgumentException;

/**
 * @package ActiveCollab\DatabaseStructure\Field\Scalar
 */
class EnumField extends Field
{
    /**
     * @var string[]
     */
    private $possibilities = [];

    /**
     * @return string[]
     */
    public function getPossibilities()
    {
        return $this->possibilities;
    }

    /**
     * @param  string ...$possibilities
     * @return $this
     */
    public function &possibilities(...$possibilities)
    {
        if ($this->getDefaultValue() !== null && !in_array($this->getDefaultValue(), $possibilities)) {
            throw new InvalidArgumentException('Default value ' . var_export($this->getDefaultValue(), true) . ' needs to be in the list of possibilities');
        }

        $this->possibilities = $possibilities;

        return $this;
    }
}

<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Field\Scalar;

use InvalidArgumentException;

/**
 * @package ActiveCollab\DatabaseStructure\Field\Scalar
 */
class EnumField extends Field
{
    /**
     * @var string[]
     */
    private $possibilities = [];

    /**
     * @return string[]
     */
    public function getPossibilities()
    {
        return $this->possibilities;
    }

    /**
     * Set a list of possible values.
     *
     * @param  string[] $possibilities
     * @return $this
     */
    public function &possibilities(...$possibilities)
    {
        if ($this->getDefaultValue() !== null && !in_array($this->getDefaultValue(), $possibilities)) {
            throw new InvalidArgumentException('Default value ' . var_export($this->getDefaultValue(), true) . ' needs to be in the list of possibilities');
        }

        $this->possibilities = $possibilities;

        return $this;
    }
}

Improve doc block enum field definition

Improve doc block enum field definition


<?php
namespace Gbox\base;
use Gbox;
interface IndentityInterface
{
    public static function findIdentity ($id);
    public static function findIdentityByAccessToken ($token, $type = null);
    public static function keyId ();
    public function getId ();
    public function getAuthKey ();
    public function validateAuthKey ($authKey);
}

<?php
namespace Gbox\base;
use Gbox;
interface IdentityInterface
{
    public static function findIdentity ($id);
    public static function findIdentityByAccessToken ($token, $type = null);
    public static function keyId ();
    public function getId ();
    public function getAuthKey ();
    public function validateAuthKey ($authKey);
}

Change name (have error, again)

Change name (have error, again)


<?php

namespace ZpgRtf\Methods;

use GuzzleHttp\Client;

/**
 * The listing method allows you to list, update or delete listings on the ZPG rtf.
 */
abstract class AbstractMethod
{
    /** @var string */
    const BASE_URI = 'https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/';

    /** @var Client */
    private $client;

    /**
     * @param string $certificate
     */
    public function __construct($certificate)
    {
        $this->client = new Client([
            'base_uri' => self::BASE_URI,
            'cert' => $certificate,
        ]);
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param Client $client
     *
     * @return static
     */
    public function setClient(Client $client)
    {
        $this->client = $client;

        return $this;
    }
}

<?php

namespace ZpgRtf\Methods;

use GuzzleHttp\Client;

/**
 * The listing method allows you to list, update or delete listings on the ZPG rtf.
 */
abstract class AbstractMethod
{
    /** @var string */
    const BASE_URI = 'https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/';

    /** @var Client */
    private $client;

    /**
     * @param string $certificate
     */
    public function __construct($certificate)
    {
        $this->client = new Client([
            'base_uri' => self::BASE_URI,
            'cert' => $certificate,
        ]);
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param Client $client
     *
     * @return static
     */
    public function setClient(Client $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * @param string $schemaUri
     * @param string $uri
     * @param \JsonSerializable $object
     *
     * @return \GuzzleHttp\Psr7\Response
     *
     * @throws \Exception If validation fails. Needs a custom exception type.
     */
    protected function validateAndSend($schemaUri, $uri, \JsonSerializable $object)
    {
        $payload = json_encode($object);
        $schema = Dereferencer::draft4()->dereference($schemaUri);
        $validator = new Validator(json_decode($payload), $schema);

        if ($validator->fails()) {
            throw new \Exception('Fails validation');
        }

        return $this->getClient()->request('POST', $uri, [
            'body' => $payload
        ]);
    }
}

Update abstract method with new function for validating and sending a request


    id }}">{{ $post->title }}
    [id }}/edit">{{ trans('messages.edit') }}]

Add links to posts (not edit form).

Add links to posts (not edit form).


<?php

	session_start();

	if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == true)
	{
		echo "you're an admin";

	}
	else{

		header("Location: static_homepage.php", true, 301);
		die();
	}
?>

<!DOCTYPE html>

		<title>Welcome to the admin page</title>

Admin page!

	<form action="admin_logout.php">
	  		<input type="submit" value="Logout" />
	  </form>

<?php

	session_start();

	if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == true)
	{
		echo "you're an admin";

	}
	else{

		header("Location: static_homepage.php", true, 301);
		die();
	}
?>

<!DOCTYPE html>

		<title>Welcome to the admin page</title>

		  <?php

			  include 'nav_bar.php';

  		?>

Admin page

	<form align="center"action="admin_logout.php">
	  		<input type="submit" value="Logout" />
	  </form>

Add nav bar, align contents to the center


<?php namespace Anomaly\TagsFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;

/**
 * Class TagsFieldTypePresenter
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\TagsFieldType
 */
class TagsFieldTypePresenter extends FieldTypePresenter
{

    /**
     * The decorated object.
     * This is for IDE support.
     *
     * @var TagsFieldType
     */
    protected $object;

    /**
     * Return the tags wrapped in labels.
     *
     * @param string $class
     * @return string
     */
    public function labels($class = 'label-default')
    {
        array_map(
            function ($tag) use ($class) {
                return '' . $tag . '';
            },
            $this->object->getValue()
        );
    }

    /**
     * Return the string form of the value.
     *
     * @return string
     */
    public function __toString()
    {
        if (!$value = $this->object->getValue()) {
            return '';
        }

        return json_encode($value);
    }
}

<?php namespace Anomaly\TagsFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;

/**
 * Class TagsFieldTypePresenter
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class TagsFieldTypePresenter extends FieldTypePresenter
{

    /**
     * The decorated object.
     * This is for IDE support.
     *
     * @var TagsFieldType
     */
    protected $object;

    /**
     * Return the tags wrapped in labels.
     *
     * @param  string $class
     * @return string
     */
    public function labels($class = 'label-default')
    {
        return array_map(
            function ($tag) use ($class) {
                return '' . $tag . '';
            },
            $this->object->getValue()
        );
    }

    /**
     * Return the string form of the value.
     *
     * @return string
     */
    public function __toString()
    {
        if (!$value = $this->object->getValue()) {
            return '';
        }

        return json_encode($value);
    }
}

Fix issue where array was not being returnedgit checkout master


<?php
	# Member template for the 'medlem' shortcode function

	# The $meta includes member info
	# Uses a $content variable if available, otherwise the meta description of the actual member.

	$year = $meta['it_year'];
	$role = $meta['it_post'];
	$description = ($content != null) ? $content : $meta['description'];
	$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
?>

		<?php echo get_avatar($id, $avatar_size); ?>

		<?php if($role) : ?>
		<hgroup>

<?php user_fullname(get_userdata($id));?>

<?php echo $role;?>

		</hgroup>
		<?php else : ?>

<?php user_fullname(get_userdata($id));?>

		<?php endif;?>

			<?php echo strip_tags($description);?>

<?php
	# Member template for the 'medlem' shortcode function

	# The $meta includes member info
	# Uses a $content variable if available, otherwise the meta description of the actual member.

	$year = $meta['it_year'];
	$description = ($content != null) ? $content : $meta['description'];
	$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
?>

		<?php echo get_avatar($id, $avatar_size); ?>

		<?php if($role) : ?>
		<hgroup>

<?php user_fullname(get_userdata($id));?>

<?php echo $role;?>

		</hgroup>
		<?php else : ?>

<?php user_fullname(get_userdata($id));?>

		<?php endif;?>

			<?php echo strip_tags($description);?>

Use shortcode attribute instead of user role when showing members


<?php if(!defined('SYSTEM')) die('no access');  ?>

<img  src="<?php echo TEMPLATE_PATH; ?>/images/download-now.gif" width="200" />

Change example home page download button to point to the Github repo.


<?php

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

namespace Symfony\Bridge\PhpUnit\Legacy;

/**
 * @internal
 */
trait ConstraintTraitForV7
{
    public function count(): int
    {
        return $this->doCount();
    }

    public function toString(): string
    {
        return $this->doToString();
    }

    protected function additionalFailureDescription($other): string
    {
        return $this->doAdditionalFailureDescription($other);
    }

    protected function failureDescription($other): string
    {
        return $this->doFailureDescription($other);
    }

    protected function matches($other): bool
    {
        return $this->doMatches($other);
    }

    private function doAdditionalFailureDescription($other): string
    {
        return '';
    }

    private function doCount(): int
    {
        return 1;
    }

    private function doFailureDescription($other): string
    {
        return $this->exporter()->export($other).' '.$this->toString();
    }

    private function doMatches($other): bool
    {
        return false;
    }

    private function doToString(): string
    {
        return '';
    }
}

<?php

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

namespace Symfony\Bridge\PhpUnit\Legacy;

use SebastianBergmann\Exporter\Exporter;

/**
 * @internal
 */
trait ConstraintTraitForV7
{
    public function count(): int
    {
        return $this->doCount();
    }

    public function toString(): string
    {
        return $this->doToString();
    }

    protected function additionalFailureDescription($other): string
    {
        return $this->doAdditionalFailureDescription($other);
    }

    protected function exporter(): Exporter
    {
        if (null !== $this->exporter) {
            $this->exporter = new Exporter();
        }

        return $this->exporter;
    }

    protected function failureDescription($other): string
    {
        return $this->doFailureDescription($other);
    }

    protected function matches($other): bool
    {
        return $this->doMatches($other);
    }

    private function doAdditionalFailureDescription($other): string
    {
        return '';
    }

    private function doCount(): int
    {
        return 1;
    }

    private function doFailureDescription($other): string
    {
        return $this->exporter()->export($other).' '.$this->toString();
    }

    private function doMatches($other): bool
    {
        return false;
    }

    private function doToString(): string
    {
        return '';
    }
}

Add missing exporter function for PHPUnit 7


<?php
namespace exussum12\CoverageChecker\Outputs;

use exussum12\CoverageChecker\Output;

class Text implements Output
{
    public function output($coverage, $percent, $minimumPercent)
    {

        printf("%.2f%% Covered\n", $percent);

        $output = '';
        foreach ($coverage as $filename => $lines) {
            $output .= "\n\n'$filename' has no coverage for the following lines:\n";
            foreach ($lines as $line => $message) {
                $output .= $this->generateOutputLine($line, $message);
            }
        }

        echo trim($output);
    }

    private function generateOutputLine($line, $message)
    {
        $output = "Line $line:\n";
        if (!empty($message)) {
            foreach ($message as $part) {
                $output .= "\t$part\n";
            }
        }

        return $output . "\n";
    }
}

<?php
namespace exussum12\CoverageChecker\Outputs;

use exussum12\CoverageChecker\Output;

class Text implements Output
{
    public function output($coverage, $percent, $minimumPercent)
    {

        printf("%.2f%% Covered\n", $percent);

        $output = '';
        foreach ($coverage as $filename => $lines) {
            $output .= "\n\n'$filename' has no coverage for the following lines:\n";
            foreach ($lines as $line => $message) {
                $output .= $this->generateOutputLine($line, $message);
            }
        }

        echo trim($output) . "\n";
    }

    private function generateOutputLine($line, $message)
    {
        $output = "Line $line:\n";
        if (!empty($message)) {
            foreach ($message as $part) {
                $output .= "\t$part\n";
            }
        }

        return $output . "\n";
    }
}

Add a space between end of text output

Add a space between end of text output


<?php

namespace BrazilianDddToUF;

trait TraitValidator {

    protected static function validate(array $arrayDDD, $ddd){
        if( !array_key_exists($ddd, $arrayDDD) ) {
            return false;
            throw new \InvalidArgumentException('DDD inexistente');
        }

        return true;
    }
}

Update after Analysis of Insight SensioLabs


<?php namespace Nord\Lumen\Core\Infrastructure;

use Doctrine\ORM\EntityRepository as BaseRepository;
use Nord\Lumen\Core\Domain\Model\Entity;

class EntityRepository extends BaseRepository
{

    /**
     * @param string $objectId
     *
     * @return Entity|null
     */
    public function findByDomainId($objectId)
    {
        return $this->findOneBy(['objectId' => $objectId]);
    }

    /**
     * @param $domainId
     *
     * @return int
     */
    public function domainIdExists($domainId)
    {
        return (int) $this->createQueryBuilder('t')
            ->select('COUNT(t.domainId)')
            ->where('t.domainId = :domainId')
            ->setParameter('domainId', $domainId)
            ->getQuery()
            ->getSingleScalarResult();
    }
}

<?php namespace Nord\Lumen\Core\Infrastructure;

use Doctrine\ORM\EntityRepository as BaseRepository;
use Nord\Lumen\Core\Domain\Model\Entity;

class EntityRepository extends BaseRepository
{

    /**
     * @param string $domainId
     *
     * @return Entity|null
     */
    public function findByDomainId($domainId)
    {
        return $this->findOneBy(['domainId' => $domainId]);
    }

    /**
     * @param $domainId
     *
     * @return int
     */
    public function domainIdExists($domainId)
    {
        return (int) $this->createQueryBuilder('t')
            ->select('COUNT(t.domainId)')
            ->where('t.domainId = :domainId')
            ->setParameter('domainId', $domainId)
            ->getQuery()
            ->getSingleScalarResult();
    }
}

Rename findByDomainId's parameter to match new function name


<?php

/**
 * ownCloud
 *
 * @author Jakob Sack
 * @copyright 2011 Jakob Sack kde@jakobsack.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
	/**
	 * Validates a username and password
	 *
	 * This method should return true or false depending on if login
	 * succeeded.
	 *
	 * @return bool
	 */
	protected function validateUserPass($username, $password){
		OC_Util::setUpFS();//login hooks may need early access to the filesystem
		if(OC_User::login($username,$password)){
			OC_Util::setUpFS();
			return true;
		}
		else{
			return false;
		}
	}
}

<?php

/**
 * ownCloud
 *
 * @author Jakob Sack
 * @copyright 2011 Jakob Sack kde@jakobsack.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
	/**
	 * Validates a username and password
	 *
	 * This method should return true or false depending on if login
	 * succeeded.
	 *
	 * @return bool
	 */
	protected function validateUserPass($username, $password){
		OC_Util::setUpFS();//login hooks may need early access to the filesystem
		if(OC_User::login($username,$password)){
			OC_Util::setUpFS($username);
			return true;
		}
		else{
			return false;
		}
	}
}

Fix initialization of OC_Filesystem setup from DAV


<?php

namespace Zizaco\FactoryMuff\Kind;

use Zizaco\FactoryMuff\Kind;

class Integer extends Kind
{
    public function generate()
    {
        $length = (int) $this->getOption(0, 5);

        return $this->randomNumber($length);
    }

    private function randomNumber($length)
    {
        $integer = null;
        for ($i = 0; $i < $length; $i++) {
            $integer .= mt_rand(1, 9);
        }

        return (int) $integer;
    }
}

<?php

namespace Zizaco\FactoryMuff\Kind;

use Zizaco\FactoryMuff\Kind;

class Integer extends Kind
{
    public function generate()
    {
        $length = (int) $this->getOption(0, 5);
        return $this->faker->randomNumber($length, true);
    }
}

Use randomNumber() from faker in strict mode


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

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

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

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

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

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

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

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

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

CC-5781: Upgrade script for new storage quota implementation

Include propel library


<?php

/**
 * This file is part of the Miny framework.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENCE file.
 */

namespace Modules\Templating\Extensions;

use Miny\Application\Application;
use Miny\Application\BaseApplication;
use Modules\Templating\Compiler\Functions\MethodFunction;
use Modules\Templating\Extension;

class Miny extends Extension
{
    /**
     * @var BaseApplication
     */
    private $application;

    public function __construct(Application $app)
    {
        parent::__construct();
        $this->application = $app;
    }

    public function getExtensionName()
    {
        return 'miny';
    }

    public function getFunctions()
    {
        return array(
            new MethodFunction('route', 'routeFunction'),
            new MethodFunction('request', 'requestFunction'),
        );
    }

    public function routeFunction($route, array $parameters = array())
    {
        return $this->application->router->generate($route, $parameters);
    }

    public function requestFunction($url, $method = 'GET', array $post = array())
    {
        $main = $this->application->response;
        $main->addContent(ob_get_clean());

        $request  = $this->application->request->getSubRequest($method, $url, $post);
        $response = $this->application->dispatch($request);

        $main->addResponse($response);
        ob_start();
    }
}

<?php

/**
 * This file is part of the Miny framework.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENCE file.
 */

namespace Modules\Templating\Extensions;

use Miny\Application\Application;
use Miny\Application\BaseApplication;
use Modules\Templating\Compiler\Functions\MethodFunction;
use Modules\Templating\Compiler\Functions\SimpleFunction;
use Modules\Templating\Extension;

class Miny extends Extension
{
    /**
     * @var BaseApplication
     */
    private $application;

    public function __construct(Application $app)
    {
        parent::__construct();
        $this->application = $app;
    }

    public function getExtensionName()
    {
        return 'miny';
    }

    public function getFunctions()
    {
        $functions = array(
            new MethodFunction('route', 'routeFunction'),
            new MethodFunction('request', 'requestFunction'),
        );
        if($this->application->isDeveloperEnvironment()) {
            $functions[] = new SimpleFunction('dump', 'var_dump');
        }
        return $functions;
    }

    public function routeFunction($route, array $parameters = array())
    {
        return $this->application->router->generate($route, $parameters);
    }

    public function requestFunction($url, $method = 'GET', array $post = array())
    {
        $main = $this->application->response;
        $main->addContent(ob_get_clean());

        $request  = $this->application->request->getSubRequest($method, $url, $post);
        $response = $this->application->dispatch($request);

        $main->addResponse($response);
        ob_start();
    }
}

Add dump function in development environment.


<?php

/**
 * Plugin Name: Twitter API Widget
 * Plugin URI: https://github.com/jakebellacera/wordpress-twitter-api-widget
 * Description: A simple widget for Wordpress that displays your Twitter feed through the Twitter API.
 * Version: 1.0.0
 * Author: Jake Bellacera
 * Author URI: http://jakebellacera.com/
 * License: MIT
 */

defined('ABSPATH') or die();

<?php

/**
 * Plugin Name: Twitter API Widget
 * Plugin URI: https://github.com/jakebellacera/wordpress-twitter-api-widget
 * Description: A simple widget for Wordpress that displays your Twitter feed through the Twitter API.
 * Version: 1.0.0
 * Author: Jake Bellacera
 * Author URI: http://jakebellacera.com/
 * License: MIT
 */

// Prevent access to the plugin
defined('ABSPATH') or die();

Add comment about ABSPATH requirement

Add comment about ABSPATH requirement


<?php
/**
 * Navigation template
 *
 * @package ZnWP Bootstrap Theme
 */

global $znwp_theme;
?>

              <a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>">
                <?php
                $brand = $znwp_theme->theme_mod('navbar_brand');
                if ('home-icon' == $brand) {
                    echo '';
                } elseif ('site-title' == $brand) {
                    bloginfo('name');
                } elseif ('none' == $brand) {
                    // Show nothing
                }
                ?>

              <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="nav">
                Toggle navigation

              </button>

              <?php
              // Output only if navigation menu is set
              if (has_nav_menu('primary')) {
                  wp_nav_menu(array(
                      'theme_location' => 'primary',
                      'container'      => false,
                      'menu_class'     => 'nav navbar-nav',
                  ));
              }
              ?>

<?php
/**
 * Navigation template
 *
 * @package ZnWP Bootstrap Theme
 */

global $znwp_theme;
?>

              <?php
              get_template_part('navbar-brand');
              get_template_part('navbar-toggle');
              ?>

              <?php get_template_part('navbar-menu'); ?>

Use template parts for brand, toggle, menu


<?php

namespace Feedme\FeedmeUserBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use \FOS\UserBundle\Form\Type\RegistrationFormType as FOSUserRegistrationFormType;
use Symfony\Component\Validator\Constraints\NotBlank;

class RegistrationFormType extends FOSUserRegistrationFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('firstname', null,['constraints' => $this->getValidators('firstname'), 'translation_domain' => 'messages'])
            ->add('lastname', null, ['constraints' => $this->getValidators('lastname'), 'translation_domain' => 'messages'])
        ;
    }

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

    private function getValidators($name)
    {
        $validators = [];
        $validator = new NotBlank(['groups' => ['Registration', 'Profile']]);
        $validator->message = sprintf('form.validation.%s.notblank', $name);
        $validators[] = $validator;

        return $validators;
    }
}

<?php

namespace Feedme\FeedmeUserBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use \FOS\UserBundle\Form\Type\RegistrationFormType as FOSUserRegistrationFormType;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * Class RegistrationFormType
 * @package Feedme\FeedmeUserBundle\Form\Type
 */
class RegistrationFormType extends FOSUserRegistrationFormType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('firstname', null,['constraints' => $this->getValidators('firstname'), 'translation_domain' => 'messages'])
            ->add('lastname', null, ['constraints' => $this->getValidators('lastname'), 'translation_domain' => 'messages'])
        ;
    }

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

    private function getValidators($name)
    {
        $validators = [];
        $validator = new NotBlank(['groups' => ['Registration', 'Profile']]);
        $validator->message = sprintf('form.validation.%s.notblank', $name);
        $validators[] = $validator;

        return $validators;
    }
}

Add phpdoc for registration form

Add phpdoc for registration form


<?php

namespace Puphpet\Domain\PuppetModule;

class Server extends PuppetModuleAbstract implements PuppetModuleInterface
{
    protected $disallowedPackages = ['python-software-properties'];
    protected $server;

    public function __construct($server)
    {
        $this->server = is_array($server) ? $server : array();
    }

    /**
     * Return ready to use server array
     *
     * @return array
     */
    public function getFormatted()
    {
        if (empty($this->server)) {
            return array();
        }

        $this->formatBashAliases()
             ->formatPackages();

        return $this->server;
    }

    /**
     * Submitted .bash_aliases contents
     *
     * @return self
     */
    protected function formatBashAliases()
    {
        $this->server['bashaliases'] = !empty($this->server['bashaliases'])
            ? trim(str_replace("\r\n", "\n", $this->server['bashaliases']))
            : '';

        return $this;
    }

    /**
     * A comma-delimited string of package names
     *
     * @return self
     */
    protected function formatPackages()
    {
        $this->server['packages'] = !empty($this->server['packages'])
            ? explode(',', $this->server['packages'])
            : array();

        foreach ($this->disallowedPackages as $disallowed) {
            unset($this->server['packages'][$disallowed]);
        }

        $this->server['packages'] = $this->quoteArray($this->server['packages']);

        return $this;
    }
}

<?php

namespace Puphpet\Domain\PuppetModule;

class Server extends PuppetModuleAbstract implements PuppetModuleInterface
{
    protected $server;

    public function __construct($server)
    {
        $this->server = is_array($server) ? $server : array();
    }

    /**
     * Return ready to use server array
     *
     * @return array
     */
    public function getFormatted()
    {
        if (empty($this->server)) {
            return array();
        }

        $this->formatBashAliases()
             ->formatPackages();

        return $this->server;
    }

    /**
     * Submitted .bash_aliases contents
     *
     * @return self
     */
    protected function formatBashAliases()
    {
        $this->server['bashaliases'] = !empty($this->server['bashaliases'])
            ? trim(str_replace("\r\n", "\n", $this->server['bashaliases']))
            : '';

        return $this;
    }

    /**
     * A comma-delimited string of package names
     *
     * @return self
     */
    protected function formatPackages()
    {
        $this->server['packages'] = !empty($this->server['packages'])
            ? explode(',', $this->server['packages'])
            : array();

        $key = array_search('python-software-properties', $this->server['packages']);

        // python-software-properties is installed by default, remove to prevent duplicate Puppet function
        if ($key !== FALSE) {
            unset($this->server['packages'][$key]);
        }

        $this->server['packages'] = $this->quoteArray($this->server['packages']);

        return $this;
    }
}

Revert "Unsetting non-existant key does not throw notice/error, so unset without checking"

This reverts commit 532b3e771755fda3909fc46a02211dfc3317730d.


<?php

namespace Stfalcon\Bundle\PaymentBundle\Entity;

use Doctrine\ORM\EntityRepository;

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

<?php

namespace Stfalcon\Bundle\PaymentBundle\Entity;

use Doctrine\ORM\EntityRepository;

use Application\Bundle\UserBundle\Entity\User;

/**
 * PaymentsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PaymentRepository extends EntityRepository
{
    /**
     * Find tickets of active events for some user
     *
     * @param User $user
     *
     * @return array
     */
    public function findPaidPaymentsForUser(User $user)
    {
        return $this->getEntityManager()
            ->createQuery('
                SELECT p
                FROM StfalconPaymentBundle:Payment p
                WHERE p.status = :status
                    AND p.user = :user
            ')
            ->setParameters(array(
                 'status' => Payment::STATUS_PAID,
                 'user'   => $user
            ))
            ->getResult();
    }
}

Add new method to Payment repository

Add new method to Payment repository


<?php
    $options      = get_option('plugin_options');
    $social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss');
?>

        <?php foreach ($social_media as $i => $name) {
                  if (!empty( $options['vobe_' . $name . '_link'] )) {
                      echo '

';
                  }
              }
        ?>

    <?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?>

Fix social media icon links.

Fix social media icon links.


<?php namespace GenericCollections\Tests;

use GenericCollections\Collection;
use GenericCollections\Interfaces\CollectionInterface;
use GenericCollections\Set;

/*
 * As a Set uses the same code as the collection
 * and only changes the add method this is the only thing tested
 */
class SetStrictTest extends \PHPUnit_Framework_TestCase
{

    public function testInheritance()
    {
        $set = new Set('int');
        $this->assertInstanceOf(CollectionInterface::class, $set);
        $this->assertInstanceOf(Collection::class, $set);
    }

    public function testAdd()
    {
        $foo = new Samples\Foo(100);
        $set = new Set(Samples\Foo::class);

        // first insert is fine
        $this->assertTrue($set->add($foo));

        // second insert returns false
        $this->assertFalse($set->add($foo));

        // contents are correct
        $this->assertEquals([$foo], $set->toArray());

        // insert a non identical but equal object
        $bar = new Samples\Foo(100);
        $this->assertTrue($set->add($bar));
    }

    public function testAddWithEqual()
    {
        $set = new Set(Samples\Foo::class, [], false);

        // are not identical but equal
        $this->assertTrue($set->add(new Samples\Foo(100)));
        $this->assertFalse($set->add(new Samples\Foo(100)));
    }
}

<?php namespace GenericCollections\Tests;

use GenericCollections\Collection;
use GenericCollections\Interfaces\CollectionInterface;
use GenericCollections\Set;

/*
 * As a Set uses the same code as the collection
 * and only changes the add method this is the only thing tested
 */
class SetStrictTest extends \PHPUnit_Framework_TestCase
{

    public function testInheritance()
    {
        $set = new Set('int');
        $this->assertInstanceOf(CollectionInterface::class, $set);
        $this->assertInstanceOf(Collection::class, $set);
    }

    public function testAdd()
    {
        $foo = new Samples\Foo(100);
        $set = new Set(Samples\Foo::class);

        // first insert is fine
        $this->assertTrue($set->add($foo));

        // second insert returns false
        $this->assertFalse($set->add($foo));

        // contents are correct
        $this->assertEquals([$foo], $set->toArray());

        // insert a non identical but equal object
        $bar = new Samples\Foo(100);
        $this->assertTrue($set->add($bar));
    }

    public function testAddCannotAddItself()
    {
        $set = new Set('mixed');

        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('It is not allowed for a set to contain itself as an element');
        $set->add($set);
    }

    public function testAddWithEqual()
    {
        $set = new Set(Samples\Foo::class, [], false);

        // are not identical but equal
        $this->assertTrue($set->add(new Samples\Foo(100)));
        $this->assertFalse($set->add(new Samples\Foo(100)));
    }
}

Build test to check that a Set cannot contain itself


<?php

namespace Tests\Stub;

/**
 * Class SegFaultTestStub
 * @package Tests\Stub
 */
class SegFaultTestStub extends BrokenTestBase implements BrokenTestInterface
{
    public function testBrokenTest()
    {
        if (extension_loaded('sigsegv')) {
            sigsegv();
        } else {
            preg_match("/http:\/\/(.)+\.ru/i", str_repeat('http://google.ru', 2000));
        }
    }
}

<?php

namespace Tests\Stub;

/**
 * Class SegFaultTestStub
 * @package Tests\Stub
 */
class SegFaultTestStub extends BrokenTestBase implements BrokenTestInterface
{
    public function testBrokenTest()
    {
        exit(139);
    }
}

Remove usage of the sigsegv() function

Remove usage of the sigsegv() function


<?php

declare(strict_types=1);

namespace SignatureTest;

use PHPUnit_Framework_TestCase;
use Signature\Encoder\Base64Encoder;
use Signature\FileContentSigner;
use Signature\Hasher\Md5Hasher;
use SignatureTestFixture\UserClass;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\PropertyGenerator;

/**
 * @covers \Signature\FileContentSigner
 */
final class FileContentSignerTest extends PHPUnit_Framework_TestCase
{
    public function testSign()
    {
        $signer         = new FileContentSigner(new Base64Encoder(), new Md5Hasher());
        $classGenerator = $signer->sign(new ClassGenerator(UserClass::class), ['foo']);
        $properties     = $classGenerator->getProperties();

        self::assertCount(1, $properties);
        self::assertArrayHasKey('fileContentSignatureb888fe9c927e4c9abaa4b1f54a27fbca', $properties);
        self::assertInstanceOf(PropertyGenerator::class, $properties['fileContentSignatureb888fe9c927e4c9abaa4b1f54a27fbca']);
    }
}

<?php

declare(strict_types=1);

namespace SignatureTest;

use PHPUnit_Framework_TestCase;
use Signature\Encoder\Base64Encoder;
use Signature\FileContentSigner;
use Signature\Hasher\Md5Hasher;
use SignatureTestFixture\UserClass;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\PropertyGenerator;

/**
 * @coversNothing
 */
final class FileContentSignerTest extends PHPUnit_Framework_TestCase
{
    public function testSign()
    {
        $signer         = new FileContentSigner(new Base64Encoder(), new Md5Hasher());
        $classGenerator = $signer->sign(new ClassGenerator(UserClass::class), ['foo']);
        $properties     = $classGenerator->getProperties();

        self::assertCount(1, $properties);
        self::assertArrayHasKey('fileContentSignatureb888fe9c927e4c9abaa4b1f54a27fbca', $properties);
        self::assertInstanceOf(PropertyGenerator::class, $properties['fileContentSignatureb888fe9c927e4c9abaa4b1f54a27fbca']);
    }
}

Change cover to coversNothing as per @Ocramius review


<?php
declare(strict_types = 1);

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Tests\CarbonInterval;

use Carbon\CarbonInterval;
use Tests\AbstractTestCase;

class ComparisonTest extends AbstractTestCase
{
    public function testEqualToTrue()
    {
        $this->assertTrue(CarbonInterval::day()->eq(CarbonInterval::hours(24)));
    }

    public function testEqualToFalse()
    {
        $this->assertFalse(CarbonInterval::day()->eq(CarbonInterval::hours(23)));
    }
}

<?php
declare (strict_types = 1);

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Tests\CarbonInterval;

use Carbon\CarbonInterval;
use DateInterval;
use Tests\AbstractTestCase;

class ComparisonTest extends AbstractTestCase
{
    public function testEqualToTrue()
    {
        $oneDay = CarbonInterval::day();
        $this->assertTrue($oneDay->eq($oneDay));
        $this->assertTrue($oneDay->eq(CarbonInterval::day()));
        $this->assertTrue($oneDay->eq(new DateInterval('P1D')));
        $this->assertTrue($oneDay->eq(CarbonInterval::hours(24)));
        $this->assertTrue($oneDay->eq(CarbonInterval::hours(23)->minutes(60)));
        $this->assertTrue($oneDay->eq('24 hours'));
        $this->assertTrue($oneDay->eq('P1D'));
    }

    public function testEqualToFalse()
    {
        $oneDay = CarbonInterval::day();
        $this->assertFalse($oneDay->eq(CarbonInterval::hours(24)->microsecond(1)));
        $this->assertFalse($oneDay->eq(CarbonInterval::hours(23)->minutes(59)->seconds(59)->microseconds(999999)));
    }
}

Add test cases for equalsTo method.

Add test cases for equalsTo method.


<?php

use Phinx\Migration\AbstractMigration;

class AddTelegramSendPhotoTable extends AbstractMigration
{
    public function up()
    {
        $table = $this->table('telegram_send_photo');

        $table->addColumn('chat_id', 'string');
        $table->addColumn('path', 'string');
        $table->addColumn('published_at', 'timestamp');
        $table->addColumn('status', 'string');
        $table->addColumn('file_id', 'string');
        $table->addColumn('created_at', 'timestamp', [
            'default' => 'CURRENT_TIMESTAMP',
            'update' => ''
        ]);

        $table->create();
    }
}

<?php

use Phinx\Migration\AbstractMigration;

class AddTelegramSendPhotoTable extends AbstractMigration
{
    public function up()
    {
        $table = $this->table('telegram_send_photo');

        $table->addColumn('chat_id', 'string');
        $table->addColumn('path', 'string');
        $table->addColumn('published_at', 'timestamp');
        $table->addColumn('created_at', 'timestamp', [
            'default' => 'CURRENT_TIMESTAMP',
            'update' => ''
        ]);

        $table->create();
    }
}

Remove unused fields from telegram_send_photo table


<?php

return [
    'url' => 'http://domain.com',
    'token' => '',
    'debug' => env('APP_DEBUG', false)
];

<?php

return [
    'url' => env('PRESTASHOP_URL', 'http://domain.com'),
    'token' => env('PRESTASHOP_TOKEN', ''),
    'debug' => env('APP_DEBUG', false)
];

Use env variables for prestashop url/token


<script type="text/javascript" charset="utf-8">
    function loadScript(src) {
        var async = arguments[1] === undefined ? true : arguments[1];
        var ref = window.document.getElementsByTagName('script')[0];
        var script = window.document.createElement('script');
        script.src = src;
        if(async) script.async = async;
        ref.parentNode.insertBefore(script, ref);
    }

    var supportsMQ = window.matchMedia && window.matchMedia( "only all" ) !== null && window.matchMedia( "only all" ).matches;
    if (!supportsMQ) {
        loadScript('{{ asset('assets/vendor/respond.min.js') }}', false)
    }

    if ('querySelector' in document && 'addEventListener' in window) {
        loadScript('{{ asset('js/bundle.js') }}');
    }
</script>

<!--[if lte IE 8]>
    <script type="text/javascript" charset="utf-8" src="{{ asset('assets/vendor/html5shiv.min.js') }}"></script>
<![endif]-->

<script type="text/javascript" charset="utf-8">
    function loadScript(src) {
        var async = arguments[1] === undefined ? true : arguments[1];
        var ref = window.document.getElementsByTagName('script')[0];
        var script = window.document.createElement('script');
        script.src = src;
        if(async) script.async = async;
        ref.parentNode.insertBefore(script, ref);
    }

    var supportsMQ = window.matchMedia && window.matchMedia( "only all" ) !== null && window.matchMedia( "only all" ).matches;
    if (!supportsMQ) {
        loadScript('{{ asset('assets/vendor/respond.min.js') }}', false)
    }

    if ('querySelector' in document && 'addEventListener' in window) {
        loadScript('{{ asset('js/app.js') }}');
    }
</script>

<!--[if lte IE 8]>
    <script type="text/javascript" charset="utf-8" src="{{ asset('assets/vendor/html5shiv.min.js') }}"></script>
<![endif]-->

Update script file name. Laravel Elixir now outputs scripts using their source name, rather than renaming to `bundle.js`, so we need to update our script tag.