<?php

use Marquine\Etl\Container;

$container = Container::getInstance();

// Database
$container->singleton(Marquine\Etl\Database\Manager::class);
$container->alias(Marquine\Etl\Database\Manager::class, 'db');

// Extractors
$container->bind('extractor.collection', Marquine\Etl\Extractors\Collection::class);
$container->bind('extractor.csv', Marquine\Etl\Extractors\Csv::class);
$container->bind('extractor.fixed_width', Marquine\Etl\Extractors\FixedWidth::class);
$container->bind('extractor.json', Marquine\Etl\Extractors\Json::class);
$container->bind('extractor.query', Marquine\Etl\Extractors\Query::class);
$container->bind('extractor.table', Marquine\Etl\Extractors\Table::class);
$container->bind('extractor.xml', Marquine\Etl\Extractors\Xml::class);

// Transformers
$container->bind('transformer.json_encode', Marquine\Etl\Transformers\JsonEncode::class);
$container->bind('transformer.trim', Marquine\Etl\Transformers\Trim::class);

// Loaders
$container->bind('loader.insert', Marquine\Etl\Loaders\Insert::class);
$container->bind('loader.insert_update', Marquine\Etl\Loaders\InsertUpdate::class);

<?php

use Marquine\Etl\Container;

$container = Container::getInstance();

// Database
$container->singleton(Marquine\Etl\Database\Manager::class);
$container->alias(Marquine\Etl\Database\Manager::class, 'db');

// Extractors
$container->bind('extractor.collection', Marquine\Etl\Extractors\Collection::class);
$container->bind('extractor.csv', Marquine\Etl\Extractors\Csv::class);
$container->bind('extractor.fixed_width', Marquine\Etl\Extractors\FixedWidth::class);
$container->bind('extractor.json', Marquine\Etl\Extractors\Json::class);
$container->bind('extractor.query', Marquine\Etl\Extractors\Query::class);
$container->bind('extractor.table', Marquine\Etl\Extractors\Table::class);
$container->bind('extractor.xml', Marquine\Etl\Extractors\Xml::class);

// Transformers
$container->bind('transformer.json_decode', Marquine\Etl\Transformers\JsonDecode::class);
$container->bind('transformer.json_encode', Marquine\Etl\Transformers\JsonEncode::class);
$container->bind('transformer.trim', Marquine\Etl\Transformers\Trim::class);

// Loaders
$container->bind('loader.insert', Marquine\Etl\Loaders\Insert::class);
$container->bind('loader.insert_update', Marquine\Etl\Loaders\InsertUpdate::class);

Add binding to json decode transformer

Add binding to json decode transformer


<?
function cssTags(){
	global $config, $css_files;
	$css_tags = '';

	if($config['env'] == 'prod'){
		$css_tags = '<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/master'.$deploy_id.'.css" media="screen">';
	}else{
		foreach($css_files as $css_file) {
			$css_tags = $css_tags.'<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/'.$css_file.'.css" media="screen">'."\n";
		}
	}

	return $css_tags;
}

function jsTags(){
	global $config, $js_files;
	$js_tags = '';

	if($config['env'] == 'prod'){
		$js_tags = '<script type="text/javascript" src="'.$config['address'].'/assets/js/master'.$deploy_id.'.js"></script>';
	}else{
		foreach($js_files as $js_file) {
			$js_tags = $js_tags.'<script type="text/javascript" src="'.$config['address'].'/assets/js/'.$js_file.'.js"></script>'."\n";
		}
	}

	return $js_tags;
}
?>

<?
function cssTags(){
	global $config, $css_files;
	$css_tags = '';

	if($config['env'] == 'prod'){
		$css_tags = '<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/master'.$deploy_id.'.css" media="screen">';
	}else{
		foreach($css_files as $css_file) {
			$css_tags = $css_tags.'<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/'.$css_file.'.css" media="screen">'."\n";
		}
	}

	return $css_tags;
}

function cssTagsForDeploy(){
	global $config, $css_files;
	foreach($css_files as $css_file) {
		$css_tags = $css_tags.$css_file.'.css ';
	}
	echo $css_tags;
}

function jsTags(){
	global $config, $js_files;
	$js_tags = '';

	if($config['env'] == 'prod'){
		$js_tags = '<script type="text/javascript" src="'.$config['address'].'/assets/js/master'.$deploy_id.'.js"></script>';
	}else{
		foreach($js_files as $js_file) {
			$js_tags = $js_tags.'<script type="text/javascript" src="'.$config['address'].'/assets/js/'.$js_file.'.js"></script>'."\n";
		}
	}

	return $js_tags;
}

function jsTagsForDeploy(){
	global $config, $js_files;
	foreach($js_files as $js_file) {
		$js_tags = $js_tags.$js_file.'.js ';
	}
	echo $js_tags;
}
?>

Add method to get css and jss files for deploy


#!/usr/local/bin/php -f
<?php

	/* upgrade embedded users serial console */
	require_once("globals.inc");
	require_once("config.inc");
	require_once("functions.inc");

	if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) {
		if(!empty($config['system']['gitsync']['repositoryurl']))
			exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl']));
		if(!empty($config['system']['gitsync']['branch']))
			system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading");
	}

	$newslicedir = "";
	if ($argv[1] != "")
		$newslicedir = '/tmp/' . $argv[1];

	if($g['enableserial_force'] || file_exists("{$newslicedir}/enableserial_force")) {
		$config['system']['enableserial'] = true;
		write_config();
	}

	system("echo \"Adding serial port settings ({$newslicedir})...\" >> /conf/upgrade_log.txt");
	setup_serial_port("upgrade", $newslicedir);

?>

#!/usr/local/bin/php -f
<?php

	/* upgrade embedded users serial console */
	require_once("globals.inc");
	require_once("config.inc");
	require_once("functions.inc");

	if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) {
		if(!empty($config['system']['gitsync']['repositoryurl']))
			exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl']));
		if(!empty($config['system']['gitsync']['branch']))
			system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading");
	}

	$newslicedir = "";
	if (isset($argv[1]) && $argv[1] != "")
		$newslicedir = '/tmp/' . $argv[1];

	if($g['enableserial_force'] || file_exists("{$newslicedir}/enableserial_force")) {
		$config['system']['enableserial'] = true;
		write_config();
	}

	system("echo \"Adding serial port settings ({$newslicedir})...\" >> /conf/upgrade_log.txt");
	setup_serial_port("upgrade", $newslicedir);

?>

Check if array is set

Check if array is set


<?php namespace App\Http\Requests;

class PostRequest extends Request {

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		$id = $this->segment(2) ? ',' . $this->segment(2) : '';
		return [
			'title' => 'required|max:255',
			'summary' => 'required|max:65000',
			'content' => 'required|max:65000',
			'slug' => 'required|unique:posts,slug' . $id,
			'tags' => 'tags'
		];
	}

}

<?php namespace App\Http\Requests;

use App\Models\Post;

class PostRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		if(!parent::authorize()) return false;

	    return Post::where('id', $this->route('blog'))
	                  ->where('user_id', $this->user()->id)->exists();
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		$id = $this->segment(2) ? ',' . $this->segment(2) : '';
		return [
			'title' => 'required|max:255',
			'summary' => 'required|max:65000',
			'content' => 'required|max:65000',
			'slug' => 'required|unique:posts,slug' . $id,
			'tags' => 'tags'
		];
	}

}

Set authorization on post update

Set authorization on post update


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Inventoryitem extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('inventoryitem', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number');
            $table->string('name');
            $table->string('version');
            $table->string('bundleid');
            $table->string('bundlename');
            $table->text('path');

            $table->index(['name', 'version']);
            $table->index('serial_number');

//            $table->timestamps();
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('inventoryitem');
    }
}

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Inventoryitem extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('inventoryitem', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number');
            $table->string('name');
            $table->string('version');
            $table->string('bundleid');
            $table->string('bundlename');
            $table->text('path');

            $table->index(['name', 'version']);
            $table->index('serial_number');
            $table->index('bundleid');
            $table->index('bundlename');
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('inventoryitem');
    }
}

Add indexes to inventoryitem migration

Add indexes to inventoryitem migration


<?php

use Illuminate\Database\Seeder;
use Fenos\Notifynder\Facades\Notifynder;

class NotifynderCategoriesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Notifynder::addCategory('user.visitedShowroom', '{from.username} visited showroom');
        Notifynder::addCategory('user.registeredBusiness', '{from.username} registered :business');
        Notifynder::addCategory('user.suscribedBusiness', '{from.username} suscribed to business');
        Notifynder::addCategory('user.checkingVacancies', '{from.username} checks vacancies');
        Notifynder::addCategory('user.updatedBusinessPreferences', '{from.username} updated :business preferences');
        Notifynder::addCategory('user.importedContacts', '{from.username} imported :count contacts');
        Notifynder::addCategory('appointment.reserve', '{from.username} made a reservation for :business');
        Notifynder::addCategory('appointment.annulate', '{from.username} annulated appointment');
        Notifynder::addCategory('appointment.confirm', '{from.username} confirmed appointment');
        Notifynder::addCategory('appointment.serve', '{from.username} served appointment');
    }
}

<?php

use Illuminate\Database\Seeder;
use Fenos\Notifynder\Facades\Notifynder;

class NotifynderCategoriesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Notifynder::addCategory('user.visitedShowroom', '{from.username} visited showroom');
        Notifynder::addCategory('user.registeredBusiness', '{from.username} registered :business');
        Notifynder::addCategory('user.subscribedBusiness', '{from.username} subscribed to business');
        Notifynder::addCategory('user.checkingVacancies', '{from.username} checks vacancies');
        Notifynder::addCategory('user.updatedBusinessPreferences', '{from.username} updated :business preferences');
        Notifynder::addCategory('user.importedContacts', '{from.username} imported :count contacts');
        Notifynder::addCategory('appointment.reserve', '{from.username} made a reservation for :business');
        Notifynder::addCategory('appointment.annulate', '{from.username} annulated appointment');
        Notifynder::addCategory('appointment.confirm', '{from.username} confirmed appointment');
        Notifynder::addCategory('appointment.serve', '{from.username} served appointment');
    }
}

Fix TYPO suscribedBusiness to subscribedBusiness


<!-- Date Picker CSS -->
<link rel="stylesheet" href="../css/date-time-picker/jquery-ui-1.10.0.custom.css">
<link rel="stylesheet" href="../css/date-time-picker/jquery-ui-timepicker-addon.css">

<!-- Date Picker CSS -->
<link href="../assets/css/date-time-picker/jquery-ui-1.10.0.custom.css" rel="stylesheet">
<link href="../assets/css/date-time-picker/jquery-ui-timepicker-addon.css" rel="stylesheet">

Remove css rule on p tag

Remove css rule on p tag


<?php

namespace PHPOrchestra\BackofficeBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Class TinymceCompilerPass
 */
class TinymceCompilerPass implements CompilerPassInterface
{
    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        if ($container->hasDefinition('twig.extension.stfalcon_tinymce')) {
            $param = $container->getParameter('stfalcon_tinymce.config');

            $param['tinymce_jquery'] = false;
            $param['include_jquery'] = false;
            $param['selector'] = ".tinymce";
            $param['theme'] = array(
                'simple' => array(
                    "theme"        => "modern",
                    "plugins"      => array(
                        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                        "searchreplace wordcount visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor"
                    ),
                    "toolbar1"     => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
                    "toolbar2"     => "print preview | forecolor backcolor",
                    "menubar"      => false,
                    "image_advtab" => true,
                )
            );

            $container->setParameter('stfalcon_tinymce.config', $param);
        }
    }
}

<?php

namespace PHPOrchestra\BackofficeBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Class TinymceCompilerPass
 */
class TinymceCompilerPass implements CompilerPassInterface
{
    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        if ($container->hasDefinition('twig.extension.stfalcon_tinymce')) {
            $param = $container->getParameter('stfalcon_tinymce.config');

            $param['tinymce_jquery'] = false;
            $param['include_jquery'] = false;
            $param['selector'] = ".tinymce";
            $param['theme'] = array(
                'simple' => array(
                    "theme"        => "modern",
                    "plugins"      => array(
                        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                        "searchreplace wordcount visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor"
                    ),
                    "toolbar1"     => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
                    "toolbar2"     => "print preview | forecolor backcolor",
                    "menubar"      => false,
                )
            );

            $container->setParameter('stfalcon_tinymce.config', $param);
        }
    }
}

Fix Tiny MCE menu bug

Fix Tiny MCE menu bug


<?php

namespace Eye4web\Zf2BoardAbac\Assertion;

use Eye4web\Zf2Abac\Assertion\AssertionInterface;
use Eye4web\Zf2Abac\Provider\ProviderInterface;
use Eye4web\Zf2Abac\Exception;
use Zend\Validator\ValidatorPluginManager;

class BaseAssertion implements AssertionInterface
{
    /** @var ProviderInterface */
    protected $provider;

    protected $permissionName = false;

    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
     * @param string $value
     * @param array $attributes
     * @return bool
     * @throws \Eye4web\Zf2Abac\Exception\RuntimeException
     */
    public function hasPermission($value, array $attributes)
    {
        if (!$this->permissionName || empty($this->permissionName)) {
            throw new \Exception('Please provide a permission name');
        }

        $permissionGroups = $this->provider->getPermissions($this->permissionName, $value);

        if (!count($permissionGroups)) {
            return true;
        }

        foreach ($permissionGroups as $group) {
            foreach ($group as $permission) {
                if (!isset($attributes[$permission->getValueId()])) {
                    return false;
                }

                $validator = $this->provider->getValidator($permission);

                if (!$validator->isValid($attributes[$permission->getValueId()])) {
                    return false;
                }
            }
        }

        return true;
    }
}

<?php

namespace Eye4web\Zf2BoardAbac\Assertion;

use Eye4web\Zf2Abac\Assertion\AssertionInterface;
use Eye4web\Zf2Abac\Provider\ProviderInterface;
use Eye4web\Zf2Abac\Exception;
use Zend\Validator\ValidatorPluginManager;

class BaseAssertion implements AssertionInterface
{
    /** @var ProviderInterface */
    protected $provider;

    protected $permissionName = false;

    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
     * @param string $value
     * @param array $attributes
     * @return bool
     * @throws \Eye4web\Zf2Abac\Exception\RuntimeException
     */
    public function hasPermission($value, array $attributes)
    {
        if (!$this->permissionName || empty($this->permissionName)) {
            throw new \Exception('Please provide a permission name');
        }

        $permissionGroups = $this->provider->getPermissions($this->permissionName, $value);

        if (!count($permissionGroups)) {
            return true;
        }

        foreach ($permissionGroups as $group) {
            foreach ($group as $permission) {
                if (!isset($attributes[$permission->getValueId()])) {
                    continue;
                }

                $validator = $this->provider->getValidator($permission);

                if (!$validator->isValid($attributes[$permission->getValueId()])) {
                    break 2;
                }
            }

            // if we reach this, all rules in this group have passed, so we are allowed
            return true;
        }

        return false;
    }
}

Fix assertion to check all permission groups


<?php

/**
 * Email
 */
class CommentsEmail
{
  public $to;
  public $subject;
  public $message;
  private $comment;

  function __construct($comment)
  {
    $this->comment = $comment;
    $this->to = Comments::option('email.to');
    $this->subject = $this->format(Comments::option('email.subject'));
    $this->message = strip_tags($comment->message());
  }

  public function format($x)
  {
    $placeholders = array(
      'comment.user.name' => $this->comment->name(),
      'comment.user.email' => $this->comment->email(),
      'comment.user.website' => $this->comment->website(),
      'comment.message' => strip_tags($this->comment->message()),
      'page.name' => $this->comment->content_page->{Comments::option('setup.page.title_key')}(),
      'page.url' => $this->comment->content_page->url()
    );

    return preg_replace_callback('/\{\{\s*(\S+)\s*\}\}/', function ($matches) use ($placeholders)
    {
      return $placeholders[$matches[1]];
    }, $x);
  }

  public function send()
  {

  }
}

<?php

/**
 * Email
 */
class CommentsEmail
{
  public $to;
  public $subject;
  public $message;
  private $comment;

  function __construct($to, $subject, $comment)
  {
    $this->comment = $comment;
    $this->to = $to;
    $this->subject = $this->format($subject);
    $this->message = strip_tags($comment->message());
  }

  public function format($x)
  {
    $placeholders = array(
      'comment.user.name' => $this->comment->name(),
      'comment.user.email' => $this->comment->email(),
      'comment.user.website' => $this->comment->website(),
      'comment.message' => strip_tags($this->comment->message()),
      'page.name' => $this->comment->content_page->{Comments::option('setup.page.title_key')}(),
      'page.url' => $this->comment->content_page->url()
    );

    return preg_replace_callback('/\{\{\s*(\S+)\s*\}\}/', function ($matches) use ($placeholders)
    {
      return $placeholders[$matches[1]];
    }, $x);
  }

  public function send()
  {

  }
}

Make CommentsEmail Constructor more Generic


<?php

declare(strict_types=1);

namespace BEAR\Package;

use BEAR\AppMeta\Meta;
use BEAR\Package\Context\CliModule;
use BEAR\Package\Module\AppMetaModule;
use BEAR\Sunday\Extension\Application\AppInterface;
use FakeVendor\HelloWorld\Module\AppModule;
use FakeVendor\HelloWorld\Module\ProdModule;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Ray\Di\AbstractModule;
use Ray\Di\Injector;
use Ray\PsrCacheModule\Annotation\Shared;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

use function assert;
use function serialize;
use function unserialize;

class NewAppTest extends TestCase
{
    public function testGetInstanceByHand(): AppInterface
    {
        $module = new AppMetaModule(new Meta('FakeVendor\HelloWorld'), new ProdModule(new CliModule(new AppModule())));
        $module->override(new class extends AbstractModule{
            protected function configure()
            {
                $this->bind(CacheItemPoolInterface::class)->annotatedWith(Shared::class)->to(FilesystemAdapter::class);
            }
        });
        $app = (new Injector($module, __DIR__ . '/tmp'))->getInstance(AppInterface::class);
        $this->assertInstanceOf(AppInterface::class, $app);
        assert($app instanceof AppInterface);

        return $app;
    }

    /**
     * @depends testGetInstanceByHand
     */
    public function testSerializable(AppInterface $app): void
    {
        $this->assertInstanceOf(AppInterface::class, unserialize(serialize($app)));
    }
}

<?php

declare(strict_types=1);

namespace BEAR\Package;

use BEAR\AppMeta\Meta;
use BEAR\Package\Context\CliModule;
use BEAR\Package\Module\AppMetaModule;
use BEAR\Sunday\Extension\Application\AppInterface;
use FakeVendor\HelloWorld\Module\AppModule;
use FakeVendor\HelloWorld\Module\ProdModule;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Ray\Di\AbstractModule;
use Ray\Di\Injector;
use Ray\PsrCacheModule\Annotation\Shared;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

use function assert;
use function serialize;
use function unserialize;

class NewAppTest extends TestCase
{
    public function testGetInstanceByHand(): AppInterface
    {
        $module = new AppMetaModule(new Meta('FakeVendor\HelloWorld'), new ProdModule(new CliModule(new AppModule())));
        $module->override(new class extends AbstractModule{
            protected function configure()
            {
                $this->bind(CacheItemPoolInterface::class)->annotatedWith(Shared::class)->to(FilesystemAdapter::class);
            }
        });
        $app = (new Injector($module, __DIR__ . '/tmp'))->getInstance(AppInterface::class);
        $this->assertInstanceOf(AppInterface::class, $app);
        assert($app instanceof AppInterface);

        return $app;
    }

    /**
     * @depends testGetInstanceByHand
     */
    public function testSerializable(AppInterface $app): void
    {
        $this->assertInstanceOf(AppInterface::class, unserialize(serialize(unserialize(serialize($app)))));
    }
}

Add unserialized cache component test

Add unserialized cache component test


<?php

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

/**
 * Creates the runtime config database schema
 */
class CreateRuntimeConfigTable extends Migration
{
    /**
     * Runs the Migration
     *
     * @return void
     */
    public function up()
    {
        Schema::create('config', function(Blueprint $table)) {
            $table->pk('id');
            $table->string('key');
            $table->longText('value');

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

    /**
     * Reverts the migrations
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('config');
    }
}

<?php

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

/**
 * Creates the runtime config database schema
 */
class CreateRuntimeConfigTable extends Migration
{
    /**
     * Runs the Migration
     *
     * @return void
     */
    public function up()
    {
        Schema::create('config', function (Blueprint $table) {
            $table->pk('id');
            $table->string('key');
            $table->longText('value');

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

    /**
     * Reverts the migrations
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('config');
    }
}

Fix syntax error in migration

Fix syntax error in migration


<?php

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

class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
    /**
     * Table name.
     *
     * @var string
     */
    protected $table;

    /**
     * Construct a new password reminder schema.
     */
    public function __construct()
    {
        $this->table = Config::get('auth.reminder.table');
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->table);
    }
}

<?php

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

class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
    /**
     * Table name.
     *
     * @var string
     */
    protected $table;

    /**
     * Construct a new password reminder schema.
     */
    public function __construct()
    {
        $this->table = Config::get('auth.password.table');
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->table);
    }
}

Update table name for master branch.

Update table name for master branch.

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


<?php

/**
 * YAWIK
 * Module Configuration
 *
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
 * @license   MIT
 */

return [
    'Core',
    'Auth',
    'Cv',
    'Applications',
    'Jobs',
    'Settings',
    'Pdf',
    'Organizations',
    'ReleaseTools'
];

<?php

/**
 * YAWIK
 * Module Configuration
 *
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
 * @license   MIT
 */

return [
    'Core',
    'Auth',
    'Cv',
    'Applications',
    'Jobs',
    'Settings',
    'Pdf',
    'Geo',
    'Organizations',
    'ReleaseTools'
];

Revert "removes Geo module from cross-solution/yawik. Module was moved to yawik/geo"

Geo Modul is needed by Travis tests

This reverts commit ca2838cca5223b205c69de23a3c9c2277caceb60.


<?php

namespace OParl\Website\API\Controllers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;

class EndpointApiController
{
    public function index(Request $request, Filesystem $fs)
    {
        $page = 0;
        $itemsPerPage = 25;

        if ($request->has('page')) {
            $page = intval($request->get('page'));
        }

        $endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))
            ->sortBy('name')
            ->map(function ($endpoint) {
                return [
                    'url'         => $endpoint['url'],
                    'title'       => $endpoint['title'],
                    'description' => isset($endpoint['description']) ? $endpoint['description'] : null,
                ];
            });

        $data = $endpoints->forPage($page, $itemsPerPage);

        $pageCount = floor($endpoints->count() / $itemsPerPage);

        return response()->json([
            'data' => $data,
            'meta' => [
                'page'  => $page,
                'total' => $pageCount,
                'next'  => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null,
            ],
        ]);
    }
}

<?php

namespace OParl\Website\API\Controllers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;

class EndpointApiController
{
    public function index(Request $request, Filesystem $fs)
    {
        $page = 0;
        $itemsPerPage = 25;

        if ($request->has('page')) {
            $page = intval($request->get('page'));
        }

        $endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))
            ->sortBy('name')
            ->map(function ($endpoint) {
                return [
                    'url'         => $endpoint['url'],
                    'title'       => $endpoint['title'],
                    'description' => isset($endpoint['description']) ? $endpoint['description'] : null,
                ];
            })
            ->values();

        $data = $endpoints->forPage($page, $itemsPerPage);

        $pageCount = floor($endpoints->count() / $itemsPerPage);

        return response()->json([
            'data' => $data,
            'meta' => [
                'page'  => $page,
                'total' => $pageCount,
                'next'  => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null,
            ],
        ]);
    }
}

Return /api/endpoints data as array instead of dict


<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class RemoveOldSchema implements Migration, OrderedMigrationInterface
{
    /**
     * {@inheritDoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::execute($schema);
    }

    /**
     * @param Schema $schema
     *
     * @throws \Doctrine\DBAL\Schema\SchemaException
     */
    public static function execute(Schema $schema)
    {
        $schema->dropTable('oro_user_email_origin');
        $schema->dropTable('oro_email_to_folder');

        $emailTable = $schema->getTable('oro_email');
        $emailTable->dropColumn('is_seen');
        $emailTable->dropColumn('received');
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 2;
    }
}

<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class RemoveOldSchema implements Migration, OrderedMigrationInterface
{
    /**
     * {@inheritDoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $schema->dropTable('oro_user_email_origin');

        self::execute($schema);
    }

    /**
     * @param Schema $schema
     *
     * @throws \Doctrine\DBAL\Schema\SchemaException
     */
    public static function execute(Schema $schema)
    {
        $schema->dropTable('oro_email_to_folder');

        $emailTable = $schema->getTable('oro_email');
        $emailTable->dropColumn('is_seen');
        $emailTable->dropColumn('received');
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 2;
    }
}

CRM-3483: Change origin syncs (IMAP/EWS) to use origin
- Fix Installer


<?php

/* @var $this yii\web\View */

use yii\helpers\Html;
use yii\bootstrap\Tabs;

$this->title = 'Home';
?>

<title>Home</title> <!-- For Pjax's sake -->
<div class="site-index">
<?=
Tabs::widget([
    'items' => [
        [
            'label' => 'Profile',
            'content' => $this->render('profile'),
            'active' => true
        ],
        [
            'label' => 'Notifications',
            'content' => $this->render('notifications'),
            'headerOptions' => [],
            'options' => ['id' => 'tab-notifications'],
        ],
    ],
]);
?>
</div>

<?php

/* @var $this yii\web\View */

use yii\helpers\Html;
use yii\bootstrap\Tabs;
use app\models\ProfileForm;

$this->title = 'Home';
?>

<title>Home</title> <!-- For Pjax's sake -->
<div class="site-index">
<?=
Tabs::widget([
    'items' => [
        [
            'label' => 'Profile',
            'content' => $this->render('profile', ['model' => new ProfileForm()]),
            'headerOptions' => ['id' => 'profile-tab'],
            'active' => true
        ],
        [
            'label' => 'Log Book',
            'content' => $this->render('logbook'),
            'headerOptions' => ['id' => 'logbook-tab'],
            'options' => ['id' => 'tab-logbook'],
        ],
        [
            'label' => 'Notifications',
            'content' => $this->render('notifications'),
            'headerOptions' => ['id' => 'notifications-tab'],
            'options' => ['id' => 'tab-notifications'],
        ],
    ],
]);
?>
</div>

Add tab for filling logbook

Add tab for filling logbook


<?php

// controlador de sessão
if ($cfg->db->connect) {
	if (isset($_COOKIE[$cfg->system->cookie]) && !empty($_COOKIE[$cfg->system->cookie])) {
		$cookie = explode(".", $_COOKIE[$cfg->system->cookie]);
		if (count($cookie) === 2) {
			$cookie[0] = intval($cookie[0]);
			$cookie[1] = $mysqli->real_escape_string($cookie[1]);

			$query = sprintf(
				"SELECT * FROM %s_users WHERE id = '%s' AND password = '%s' LIMIT %s",
				$cfg->db->prefix, $cookie[0], $cookie[1], 1
			);
			$source = $mysqli->query($query);
			$nr = $source->num_rows;

			if ($nr === 1) {
				$auth = true;
				$authData = $source->fetch_assoc();
			} else {
				$auth = false;
			}
		}
	} else {
		$auth = false;
	}
} else {
	$auth = false;
}

<?php

if ($cfg->db->connect) {
	if (isset($_COOKIE[$cfg->system->cookie]) && !empty($_COOKIE[$cfg->system->cookie])) {
		$cookie = explode(".", $_COOKIE[$cfg->system->cookie]);
		if (count($cookie) === 2) {
			$cookie[0] = intval($cookie[0]);
			$cookie[1] = $mysqli->real_escape_string($cookie[1]);

			$query = sprintf(
				"SELECT * FROM %s_users WHERE id = '%s' AND password = '%s' LIMIT %s",
				$cfg->db->prefix, $cookie[0], $cookie[1], 1
			);
			$source = $mysqli->query($query);

			if ($source->num_rows == 1) {
				$auth = true;
				$authData = $source->fetch_assoc();
			} else {
				$auth = false;
			}
		}
	} else {
		$auth = false;
	}
} else {
	$auth = false;
}

Remove comment, and remove an unnecessary variable


@unless(Butler::providers()->isEmpty())

Or, login with

            @foreach (\Butler::providers() as $code => $details)
                class }}">
                    @if ($details->icon)
                        icon }}">
                    @endif
                    {{ $details->name }}

            @endforeach

@endunless

@unless(Butler::providers()->isEmpty())

            @foreach (\Butler::providers() as $code => $details)
                class }}">
                    @if ($details->icon)
                        icon }}">
                    @endif
                    {{ $details->name }}

            @endforeach

@endunless

Remove 'Or Login with' text from the list view. Make it more reusable.


<?php

namespace Kunstmaan\AdminBundle\Tests\EventListener;

use Kunstmaan\AdminBundle\Command\ApplyAclCommand;
use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ConsoleExceptionSubscriberTest extends TestCase
{
    public function testListener()
    {
        if (!class_exists(ConsoleErrorEvent::class)) {
            // Nothing to test
            return;
        }

        $logger = $this->createMock(LoggerInterface::class);
        $logger->expects($this->once())->method('critical')->willReturn(true);
        $subscriber = new ConsoleExceptionSubscriber($logger);

        $command = new ApplyAclCommand();
        $exception = new \Exception();

        $input = $this->createMock(InputInterface::class);
        $output = $this->createMock(OutputInterface::class);
        $event = new ConsoleErrorEvent($input, $output, $exception, $command);

        $subscriber->onConsoleError($event);
    }
}

<?php

namespace Kunstmaan\AdminBundle\Tests\EventListener;

use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\OutputInterface;

class ConsoleExceptionSubscriberTest extends TestCase
{
    public function testListener()
    {
        // Remove when sf3.4 support is removed
        if (!class_exists(ConsoleErrorEvent::class)) {
            // Nothing to test
            return;
        }

        $error = new \TypeError('An error occurred');
        $output = $this->createMock(OutputInterface::class);
        $logger = $this->createMock(LoggerInterface::class);
        $logger->expects($this->once())->method('critical');

        $subscriber = new ConsoleExceptionSubscriber($logger);
        $subscriber->onConsoleError(new ConsoleErrorEvent(new ArgvInput(['console.php', 'test:run', '--foo=baz', 'buzz']), $output, $error, new Command('test:run')));
    }
}

[AdminBundle] Test console exception subscriber without instantiating a specific command


<img src="<?= $this->url->dir() ?>/plugins/GitlabWebhook/gitlab-icon.png"/> <?= t('Gitlab webhooks') ?>

<input type="text" class="auto-select" readonly="readonly" value="<?= $this->url->href('webhook', 'handler', array('plugin' => 'GitlabWebhook', 'token' => $webhook_token, 'project_id' => $project['id']), false, '', true) ?>"/>

<?= t('Help on Gitlab webhooks') ?>

<img src="<?= $this->url->dir() ?>plugins/GitlabWebhook/gitlab-icon.png"/> <?= t('Gitlab webhooks') ?>

<input type="text" class="auto-select" readonly="readonly" value="<?= $this->url->href('webhook', 'handler', array('plugin' => 'GitlabWebhook', 'token' => $webhook_token, 'project_id' => $project['id']), false, '', true) ?>"/>

<?= t('Help on Gitlab webhooks') ?>

Remove useless slash in icon url

Remove useless slash in icon url


<?php

namespace Palmtree\CanonicalUrlBundle\DependencyInjection;

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

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

        $container->setParameter('palmtree.canonical_url.site_url', $config['site_url']);
        $container->setParameter('palmtree.canonical_url.redirect_code', $config['redirect_code']);

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

<?php

namespace Palmtree\CanonicalUrlBundle\DependencyInjection;

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

class PalmtreeCanonicalUrlExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config        = $this->processConfiguration($configuration, $configs);

        $container->setParameter('palmtree.canonical_url.site_url', $config['site_url']);
        $container->setParameter('palmtree.canonical_url.redirect_code', $config['redirect_code']);

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

Use DI Extension instead of HttpKernel

Use DI Extension instead of HttpKernel


Include autoload.php if it exists

Include autoload.php if it exists


<?php

echo "
\n";
echo "
Freeze!
\n";
echo "The exchange isn't currently frozen.
\n";
echo "
\n";

?>

<?php

require_once 'util.php';

if (isset($_POST['set_freeze'])) {
    if (isset($_POST['csrf_token'])) {
        if ($_SESSION['csrf_token'] != $_POST['csrf_token'])
            throw new Error("csrf", "csrf token mismatch!");
    } else
        throw new Error("csrf", "csrf token missing!");
}

echo "
\n";
echo "
Freeze!
\n";

if (isset($_POST['set_freeze'])) {
    $state = post('set_freeze');

    if ($state == 'freeze') {
        set_frozen(true);
        echo "
Exchange has been frozen. continue
\n";
    } else if ($state == 'unfreeze') {
        set_frozen(false);
        echo "
Exchange has been unfrozen. continue
\n";
    } else
        throw Error("Unknown state", "State $state should be 'freeze' or 'unfreeze'.");
} else {
    $is_frozen = is_frozen();
    if ($is_frozen)
        echo "
The exchange is currently frozen.
\n";
    else
        echo "
The exchange isn't currently frozen.
\n";
?>
    <form action='' class='indent_form' method='post'>
        <input type='hidden' name='csrf_token' value="<?php echo $_SESSION['csrf_token']; ?>" />
        <input type='hidden' name='set_freeze'' value='<?php echo $is_frozen ? "unfreeze" : "freeze" ?>' />
        <input type='submit' value='<?php echo $is_frozen ? "Unfreeze" : "Freeze" ?>' />
    </form>
<?php
}

echo "
\n";
?>

Add form to allow freezing and unfreezing the exchange.


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

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Articles
 */
class ComArticlesControllerCategory extends ComDefaultControllerDefault
{
    protected function _actionGet(KCommandContext $context)
    {
        $view = $this->getView();

	    //Set the layout
        if($view instanceof KViewTemplate)
	    {
	        $layout = clone $view->getIdentifier();
	        $layout->package  = 'categories';
	        $layout->name     = $view->getLayout();

	        //Force re-creation of the filepath to load the category templates
	        $layout->filepath = '';

	        $view->setLayout($layout);
	    }

	    //Set the toolbar
	    if($this->isCommandable()) {
	        $this->setToolbar('admin::com.categories.controller.toolbar.'.$view->getName());
	    }

        return parent::_actionGet($context);
    }

    public function setModel($model)
    {
        $model = parent::setModel($model);
        $model->package = 'categories';

        return $model;
    }

	public function getRequest()
	{
		$this->_request['section'] = 'com_content';
	    return $this->_request;
	}
}

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

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Articles
 */
class ComArticlesControllerCategory extends ComCategoriesControllerCategory
{
    public function getRequest()
	{
		$this->_request['section'] = 'com_content';
	    return $this->_request;
	}
}

Extend from new ComCategoriesControllerCategory controller.


<?php
/**
 * Atom Publishing Protocol support
 *
 * @author  Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license MIT
 */
namespace Mekras\AtomPub\Document;

use Mekras\Atom\Document\Document as AtomDocument;
use Mekras\AtomPub\AtomPub;

/**
 * AtomPub Document.
 *
 * @since 1.0
 *
 * @link  https://tools.ietf.org/html/rfc5023#section-6
 */
abstract class Document extends AtomDocument
{
    /**
     * Create document.
     *
     * @param \DOMDocument|null $document
     *
     * @throws \InvalidArgumentException
     *
     * @since 1.0
     */
    public function __construct($document = null)
    {
        parent::__construct($document);
        $this->getDomDocument()->documentElement
            ->setAttributeNS(self::XMLNS, 'xmlns:atom', self::ATOM);
    }

    /**
     * Return node main namespace.
     *
     * @return string
     *
     * @since 1.0
     */
    public function ns()
    {
        return AtomPub::NS;
    }
}

<?php
/**
 * Atom Publishing Protocol support
 *
 * @author  Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license MIT
 */
namespace Mekras\AtomPub\Document;

use Mekras\Atom\Atom;
use Mekras\Atom\Document\Document as AtomDocument;
use Mekras\AtomPub\AtomPub;

/**
 * AtomPub Document.
 *
 * @since 1.0
 *
 * @link  https://tools.ietf.org/html/rfc5023#section-6
 */
abstract class Document extends AtomDocument
{
    /**
     * Create document.
     *
     * @param \DOMDocument|null $document
     *
     * @throws \InvalidArgumentException
     *
     * @since 1.0
     */
    public function __construct($document = null)
    {
        parent::__construct($document);
        $this->getDomDocument()->documentElement
            ->setAttributeNS(Atom::XMLNS, 'xmlns:atom', Atom::NS);
    }

    /**
     * Return node main namespace.
     *
     * @return string
     *
     * @since 1.0
     */
    public function ns()
    {
        return AtomPub::NS;
    }
}

Update to latest Atom package version.

Update to latest Atom package version.


<?php get_header('private'); ?>

                        <?php
                            foreach($faq as $f){
                        ?>

<?php echo $f->question; ?>

                                    <?php echo $f->answer; ?>

                        <?php
                            }
                        ?>

<?php get_footer('private'); ?>

<?php get_header('faq'); ?>

                        <?php
                            foreach($faq as $f){
                        ?>

<?php echo $f->question; ?>

                                    <?php echo $f->answer; ?>

                        <?php
                            }
                        ?>

<?php get_footer('private'); ?>

Update view dengan template header faq

Update view dengan template header faq


<?php

declare(strict_types=1);

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

class AddMetadataFieldsToUsers extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping(
            'enum',
            'string'
        );

        Schema::table('users', static function (Blueprint $table): void {
            $table->string('create_reason', 255)->default('cas_login');
            $table->boolean('has_ever_logged_in')->default(true);
            $table->boolean('is_service_account')->default(false);
            $table->string('primary_affiliation')->nullable();
            $table->timestamp('last_login')->nullable();
            $table->string('gtDirGUID')->nullable();
        });

        Schema::table('users', static function (Blueprint $table): void {
            $table->string('create_reason', 255)->default(null)->change();
            $table->boolean('has_ever_logged_in')->default(null)->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', static function (Blueprint $table): void {
            $table->dropColumn('create_reason');
            $table->dropColumn('has_ever_logged_in');
            $table->dropColumn('is_service_account');
            $table->dropColumn('primary_affiliation');
            $table->dropColumn('last_login');
        });
    }
}

<?php

declare(strict_types=1);

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

class AddMetadataFieldsToUsers extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping(
            'enum',
            'string'
        );

        Schema::table('users', static function (Blueprint $table): void {
            $table->string('create_reason', 255)->default('cas_login');
            $table->boolean('has_ever_logged_in')->default(true);
            $table->boolean('is_service_account')->default(false);
            $table->string('primary_affiliation')->nullable();
            $table->timestamp('last_login')->nullable();
            $table->string('gtDirGUID')->nullable();
        });

        Schema::table('users', static function (Blueprint $table): void {
            $table->string('create_reason', 255)->default(null)->change();
            $table->boolean('has_ever_logged_in')->default(null)->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', static function (Blueprint $table): void {
            $table->dropColumn('create_reason');
            $table->dropColumn('has_ever_logged_in');
            $table->dropColumn('is_service_account');
            $table->dropColumn('primary_affiliation');
            $table->dropColumn('last_login');
            $table->dropColumn('gtDirGUID');
        });
    }
}

Fix down migration for gtDirGUID

Fix down migration for gtDirGUID


<?php

namespace Egrajeda\ReclineJsBundle\Tests;

use Egrajeda\ReclineJsBundle\Helper\ArrayToCsvTransformer;

class ArrayToCsvTransformerTest extends \PHPUnit_Framework_TestCase
{
    public function testTransform()
    {
        $data = array(
            array("a" => "Hello", "b" => "World"),
            array("a" => "Goodbye", "b" => "World"),
        );

        $transformer = new ArrayToCsvTransformer();
        $csv = $transformer->transform($data);

        $this->assertEquals("a,b\nHello,World\nGoodbye,World\n", $csv);
    }
}

<?php

namespace Egrajeda\ReclineJsBundle\Tests\Helper;

use Egrajeda\ReclineJsBundle\Helper\ArrayToCsvTransformer;

class ArrayToCsvTransformerTest extends \PHPUnit_Framework_TestCase
{
    public function testTransform()
    {
        $data = array(
            array("a" => "Hello", "b" => "World"),
            array("a" => "Goodbye", "b" => "World"),
        );

        $transformer = new ArrayToCsvTransformer();
        $csv = $transformer->transform($data);

        $this->assertEquals("a,b\nHello,World\nGoodbye,World\n", $csv);
    }
}

Fix typo in namespace of tests

Fix typo in namespace of tests


<?php

namespace Flow\Adapter;

use Flow\Adapter;

final class FileAdapter implements Adapter
{
    private $source;

    public function __construct($source)
    {
        if (!($this->source = realpath($source)) || !is_dir($this->source)) {
            throw new \RuntimeException(sprintf(
                'source directory %s not found',
                $source
            ));
        }
    }

    public function isReadable(string $path) : bool
    {
        return is_readable($this->source. '/' . $path);
    }

    public function lastModified(string $path) : int
    {
        return filemtime($this->source. '/' . $path);
    }

    public function getContents(string $path) : string
    {
        return file_get_contents($this->source . '/' . $path);
    }
}

<?php

namespace Flow\Adapter;

use Flow\Adapter;

final class FileAdapter implements Adapter
{
    private $directory;

    public function __construct($directory)
    {
        if (!($this->directory = realpath($directory)) || !is_dir($this->directory)) {
            throw new \RuntimeException(sprintf(
                'directory %s not found',
                $directory
            ));
        }
    }

    public function isReadable(string $path) : bool
    {
        return is_readable($this->directory . '/' . $path);
    }

    public function lastModified(string $path) : int
    {
        return filemtime($this->directory . '/' . $path);
    }

    public function getContents(string $path) : string
    {
        return file_get_contents($this->directory . '/' . $path);
    }
}

Rename member variable to better reflect its usage and abstraction


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Generators;

use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\PathGenerator\BasePathGenerator;

class PathGenerator extends BasePathGenerator
{
    protected function getBasePath(Media $media): string
    {
        return str_plural(str_slug($media->model->getMorphClass())).'/'.str_plural($media->getTypeAttribute()).'/'.$media->getKey();
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Generators;

use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\PathGenerator\BasePathGenerator;

class PathGenerator extends BasePathGenerator
{
    protected function getBasePath(Media $media): string
    {
        return str_plural(str_slug($media->model->getMorphClass())).'/'.$media->collection_name.'/'.$media->getKey();
    }
}

Change default media path generator to use collections instead of media types


<?php

namespace common\models\comments;

use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;

abstract class Comment extends ActiveRecord
{
    public static function commentClassName()
    {
        return AdjacencyListComment::className();
    }

    public static function instantiate($row)
    {
        $className = static::commentClassName();
        return new $className();
    }

    /**
     * @param mixed[] $config
     * @return Comment
     */
    public static function create($config = [])
    {
        $className = static::commentClassName();
        return new $className($config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false],
        ];
    }

    public function rules()
    {
        return [
            ['text', 'filter', 'filter' => 'trim'],
            ['text', 'required'],
            ['text', 'string', 'min' => 5, 'max' => 10000],
        ];
    }

    public static function findByPostInternal($postId)
    {
        throw new Exception('Method is not implemented');
    }

    public static function findByPost($postId)
    {
        return call_user_func([static::commentClassName(), 'findByPostInternal'], $postId);
    }
}

<?php

namespace common\models\comments;

use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;

abstract class Comment extends ActiveRecord
{
    public static function commentClassName()
    {
        return AdjacencyListComment::className();
    }

    public static function instantiate($row)
    {
        $className = static::commentClassName();
        return new $className();
    }

    /**
     * @param mixed[] $config
     * @return Comment
     */
    public static function create($config = [])
    {
        $className = static::commentClassName();
        return new $className($config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false],
        ];
    }

    public function rules()
    {
        return [
            ['text', 'filter', 'filter' => 'trim'],
            ['text', 'required'],
            ['text', 'string', 'min' => 5, 'max' => 10000],

            ['parent_id', 'required'],
            ['parent_id', 'exist', 'targetAttribute' => 'id'],
        ];
    }

    public static function findByPostInternal($postId)
    {
        throw new Exception('Method is not implemented');
    }

    public static function findByPost($postId)
    {
        return call_user_func([static::commentClassName(), 'findByPostInternal'], $postId);
    }
}

Add parent ID validation rule.

Add parent ID validation rule.


<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

?>

        Page Header
        Optional description

 Level

Here

<?php

require_once('page_template_dash_foot.php');

?>

<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

?>

      	Dashboard

 Dashboard

<?php

require_once('page_template_dash_foot.php');

?>

Make main dashboard slightly better

Make main dashboard slightly better


<?php

namespace SoliantConsulting\Apigility\Server\Hydrator\Strategy;

use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Persistence\ProvidesObjectManager;
use DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy;
use ZF\Hal\Collection as HalCollection;
use ZF\Hal\Link\Link;

class Collection extends AbstractCollectionStrategy
    implements StrategyInterface, ObjectManagerAwareInterface
{
    use ProvidesObjectManager;

    public function extract($value)
    {
        $link = new Link($this->getCollectionName());

        return $link;
#        $self->setRoute($route);

#        $self->setRouteParams($routeParams);
#        $resource->getLinks()->add($self, true);

#        print_r(get_class_methods($value));

#        print_r(($value->count() . ' count'));
#die();
die($this->getCollectionName());
        return new HalCollection($this->getObject());

        return array(
            '_links' => array(
                'asdf' => 'fdas',
                'asdfasdf' => 'fdasfdas',
            ),
        );
        // extract
        print_r(get_class($value));
        die('extract apigility collection');
    }

    public function hydrate($value)
    {
        // hydrate
        die('hydrate apigility collection');
    }
}

<?php

namespace SoliantConsulting\Apigility\Server\Hydrator\Strategy;

use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Persistence\ProvidesObjectManager;
use DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy;
use ZF\Hal\Collection as HalCollection;
use ZF\Hal\Link\Link;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

class Collection extends AbstractCollectionStrategy
    implements StrategyInterface, ServiceManagerAwareInterface //, ObjectManagerAwareInterface
{
    use ProvidesObjectManager;

    protected $serviceManager;

    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }

    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    public function extract($value)
    {
        $config = $this->getServiceManager()->get('Config');
        $config = $config['zf-hal']['metadata_map'][$value->getTypeClass()->name];

        $link = new Link($this->getCollectionName());
        $link->setRoute($config['route_name']);
        $link->setRouteParams(array('id' => null));

        $mapping = $value->getMapping();

        $link->setRouteOptions(array(
            'query' => array(
                'query' => array(
                    array('field' =>$mapping['mappedBy'], 'type'=>'eq', 'value' => $value->getOwner()->getId()),
                ),
            ),
        ));

        return $link;
    }

    public function hydrate($value)
    {
        // hydrate
        die('hydrate apigility collection');
    }
}

Return a Link for collection fields

Return a Link for collection fields


<?php

use Psr\Log\LogLevel;

return [

    'delete' => array(
        'error' => 'There was an error while deleting the log.',
        'success' => 'Log deleted successfully!',
        'text' => 'Delete Current Log',
    ),
    'empty_file'  => ':sapi log for :date appears to be empty. Did you manually delete the contents?',
    'levels' => [
        'all' => 'all',
        'emergency' => LogLevel::EMERGENCY,
        'alert' => LogLevel::ALERT,
        'critical' => LogLevel::CRITICAL,
        'error' => LogLevel::ERROR,
        'warning' => LogLevel::WARNING,
        'notice' => LogLevel::NOTICE,
        'info' => LogLevel::INFO,
        'debug' => LogLevel::DEBUG,
    ],
    'no_log'  => 'No :sapi log available for :date.',
    'sapi'   => [
        'apache' => 'Apache',
        'cli' => 'CLI'
    ],

];

<?php

use Psr\Log\LogLevel;

return array(

    'delete' => array(
        'error' => 'There was an error while deleting the log.',
        'success' => 'Log deleted successfully!',
        'text' => 'Delete Current Log',
    ),
    'empty_file'  => ':sapi log for :date appears to be empty. Did you manually delete the contents?',
    'levels' => array(
        'all' => 'all',
        'emergency' => LogLevel::EMERGENCY,
        'alert' => LogLevel::ALERT,
        'critical' => LogLevel::CRITICAL,
        'error' => LogLevel::ERROR,
        'warning' => LogLevel::WARNING,
        'notice' => LogLevel::NOTICE,
        'info' => LogLevel::INFO,
        'debug' => LogLevel::DEBUG,
    ),
    'no_log'  => 'No :sapi log available for :date.',
    // @TODO Find out what sapi nginx, IIS, etc. show up as.
    'sapi'   => array(
        'apache' => 'Apache',
        'cgi-fcgi' => 'Fast CGI',
        'cli' => 'CLI',
    ),

);

Stop using PHP 5.4 short array syntax. Package only requires 5.3.7


<?php
$db = new mysqli('localhost', 'appd2dpr_php', '9&3mPMjCJM8+uKy6o', 'appd2dpr_mobileApp');
$userID=$db->real_escape_string($_GET["userID"]);

$formIDQuery = 'SELECT * FROM users_forms WHERE userID="'.$userID.'"';
if(!$allFormIds=$db->query($formIDQuery)){
	die("Error: " . $db->error);
}
$form_list=array();
while($row = $allFormIds->fetch_assoc()){
	$formNamesQuery = 'SELECT * FROM forms WHERE formID="'.$row["formID"].'"';
	if(!$formNames=$db->query($formNamesQuery)){
		die("Error: " . $db->error);
	}
	while($nameRow = $formNames->fetch_assoc()){
		array_push($form_list, array($nameRow["frmName"],$nameRow["formID"]));
	}
}
echo json_encode($form_list);
?>

<?php
$db = new mysqli('localhost', 'appd2dpr_php', '9&3mPMjCJM8+uKy6o', 'appd2dpr_mobileApp');
$userID=$db->real_escape_string($_GET["userID"]);

$formIDQuery = 'SELECT * FROM users_forms WHERE userID="'.$userID.'"';
if(!$allFormIds=$db->query($formIDQuery)){
	die("Error: " . $db->error);
}
$form_list=array();
while($row = $allFormIds->fetch_assoc()){
	$formNamesQuery = 'SELECT * FROM forms WHERE formID="'.$row["formID"].'"';
	if(!$formNames=$db->query($formNamesQuery)){
		die("Error: " . $db->error);
	}
	while($nameRow = $formNames->fetch_assoc()){
		//array_push($form_list, array($nameRow["frmName"],));
	$formID = $nameRow["formID"];
	$getFormFieldIDQuery='SELECT * FROM form_fields WHERE formID="'.$formID.'" ORDER BY formFieldID ASC';
	if(!$FFIDR=$db->query($getFormFieldIDQuery)){
		die("Error: " . $db->error);
	}

	$fFID_arr= $FFIDR->fetch_assoc();
	$fFID = $fFID_arr["formFieldID"];
    $subid=array();
	$subIDsQuery = 'SELECT * FROM submission WHERE formID="'.$formID.'" AND userID="'+$userID+'"';
	if(!$submissionIDs=$db->query($subIDsQuery)){
		die("Error: " . $db->error);
	}

	while($subIDRow = $submissionIDs->fetch_assoc()){

		array_push($subid, array($subIDRow["timeStamp"],$subIDRow["subID"]));
	}
		array_push($form_list, array($row["frmName"],$row["formID"],$subid));
	}
}
echo json_encode($form_list);
?>

Put more data into one request, trying to reduce errors and speed things up.


{{ $interest_form->firstname }} {{ $interest_form->lastname }} is interested
in joining the {{ $interest_form->vision_team ? ' Vision ' : "" }}
{{ $interest_form->vision_team && $interest_form->regional_statistician_team ? " and " : "Team" }}
{{$interest_form->regional_statistician_team ? " Regional Statistician Team " : "" }}

Summary

{{ $interest_form->firstname }} {{ $interest_form->lastname }}

{{ $interest_form->email }}

{{ $interest_form->phone }}

{{ $interest_form->team }}

Best,

The Vision Team

{{ $interest_form->firstname }} {{ $interest_form->lastname }} is interested
in joining the {{ $interest_form->vision_team ? " Vision " : "" }}
{{ $interest_form->vision_team && $interest_form->regional_statistician_team ? " and " : "Team" }}
{{$interest_form->regional_statistician_team ? " Regional Statistician Team " : "" }}

Summary

{{ $interest_form->firstname }} {{ $interest_form->lastname }}

{{ $interest_form->email }}

{{ $interest_form->phone }}

{{ $interest_form->team }}

Best,

The Vision Team

Add Interest Form For Weekend

Add Interest Form For Weekend

+ fix email body and subject


<?php

namespace Adldap\Classes;

interface QueryableInterface
{
    /**
     * Finds a record from AD.
     *
     * @param string $name
     * @param array  $fields
     *
     * @return bool|\Adldap\Models\Entry
     */
    public function find($name, $fields = []);

    /**
     * Get all of the records from AD.
     *
     * @param array     $fields
     * @param bool|true $sorted
     * @param string    $sortBy
     *
     * @return array|bool
     */
    public function all($fields = [], $sorted = true, $sortBy = 'cn');

    /**
     * Creates a new Search limited to the current classes object type.
     *
     * @return Search
     */
    public function search();
}

<?php

namespace Adldap\Classes;

interface QueryableInterface
{
    /**
     * Finds a record from AD.
     *
     * @param string $name
     * @param array  $fields
     *
     * @return bool|\Adldap\Models\Entry
     */
    public function find($name, $fields = []);

    /**
     * Get all of the records from AD.
     *
     * @param array     $fields
     * @param bool|true $sorted
     * @param string    $sortBy
     *
     * @return array|bool
     */
    public function all($fields = [], $sorted = true, $sortBy = 'cn');

    /**
     * Creates a new Search limited to the current classes object type.
     *
     * @return \Adldap\Query\Builder
     */
    public function search();
}

Fix code doc return type

Fix code doc return type


<?php

namespace Bundle\DoctrineUserBundle\Auth;

use Symfony\Components\HttpFoundation\Session;
use Symfony\Framework\EventDispatcher;
use Symfony\Components\EventDispatcher\Event;
use Doctrine\ORM\EntityManager;

class Listener
{
    /**
     * @var Session
     */
    protected $session;
    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @var EventDispatcher
     */
    protected $eventDispatcher = null;

    public function __construct(Session $session, EntityManager $em, EventDispatcher $eventDispatcher)
    {
        $this->session = $session;
        $this->em = $em;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function connect()
    {
        $this->eventDispatcher->connect('doctrine_user.login', array($this, 'listenToUserLoginEvent'));
        $this->eventDispatcher->connect('doctrine_user.logout', array($this, 'listenToUserLogoutEvent'));
    }

    public function listenToUserLoginEvent(Event $event)
    {
        $this->session->setAttribute('identity_username', $event['user']->getUsername());

        $event['user']->setLastLogin(new \DateTime());
        $this->em->flush();
    }

    public function listenToUserLogoutEvent(Event $event)
    {
        $this->session->setAttribute('identity_username', null);
    }
}

<?php

namespace Bundle\DoctrineUserBundle\Auth;

use Symfony\Components\HttpFoundation\Session;
use Symfony\Framework\EventDispatcher;
use Symfony\Components\EventDispatcher\Event;
use Bundle\DoctrineUserBundle\DAO\UserRepository;

class Listener
{
    /**
     * @var Session
     */
    protected $session;

    /**
     * @var UserRepository
     */
    protected $repo;

    /**
     * @var EventDispatcher
     */
    protected $eventDispatcher = null;

    public function __construct(Session $session, UserRepository $repo, EventDispatcher $eventDispatcher)
    {
        $this->session = $session;
        $this->repo = $repo;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function connect()
    {
        $this->eventDispatcher->connect('doctrine_user.login', array($this, 'listenToUserLoginEvent'));
        $this->eventDispatcher->connect('doctrine_user.logout', array($this, 'listenToUserLogoutEvent'));
    }

    public function listenToUserLoginEvent(Event $event)
    {
        $this->session->setAttribute('identity/user_id', $event['user']->getId());

        try {
            $event['user']->setLastLogin(new \DateTime());
            $this->repo->getObjectManager()->flush();
        }
        catch(\Exception $e) {}
    }

    public function listenToUserLogoutEvent(Event $event)
    {
        $this->session->setAttribute('identity/user_id', null);
    }
}

Make the auth listener work with bot ORM and ODM


<?php
/**
 * Created by PhpStorm.
 * User: GeoMash
 * Date: 3/17/14
 * Time: 3:03 PM
 */

<?php
namespace application\nutsNBolts\controller\rest\pageType
{
	use application\nutsNBolts\base\RestController;

	class Index extends RestController
	{
		public function init()
		{
			$this->bindPaths
			(
				array
				(
					''						=>'getAll',
					'{int}/{string}'		=>'getByRef',
					'{int}'					=>'getById'
				)
			);
		}

		/*
		 * sample request: $.getJSON('/rest/pageType/.json');
		 */
		public function getAll()
		{
			$this->respond
			(
				true,
				'OK',
				$this->model->PageType->read([])
			);
		}

		/*
		 * sample request: $.getJSON('/rest/pageType/home.json');
		 */
		public function getByRef()
		{
			$pageRef=$this->getFullRequestPart(3);
			if(isset($pageRef))
			{
				$page=$this->model->PageType->read(['ref'=>$pageRef]);
				if(count($page))
				{
					$this->setResponseCode(200);
					$this->respond
					(
						true,
						'OK',
						$page[0]
					);
				}
				else
				{
					// no page by that Ref
					$this->setResponseCode(404);
					$this->respond
					(
						true,
						'***Page not found'
					);
				}
			}
			else
			{
				$this->setResponseCode(404);
				$this->respond
				(
					false,
					'Expecting page ref to be a string.'
				);
			}
		}
		/*
		 * sample request: $.getJSON('/rest/pageType/1.json');
		 */
		public function getById()
		{
			$pageId=$this->getFullRequestPart(2);
			if(isset($pageId) && is_numeric($pageId))
			{
				$page=$this->model->PageType->read(['id'=>$pageId]);
				if(count($page))
				{
					$this->setResponseCode(200);
					$this->respond
					(
						true,
						'OK',
						$page[0]
					);
				}
				else
				{
					// no page by that id
					$this->setResponseCode(404);
					$this->respond
					(
						true,
						'Not Found',
						'Page not found'
					);
				}
			}
			else
			{
				$this->setResponseCode(404);
				$this->respond
				(
					false,
					'Expecting page id to be an integer.'
				);
			}
		}
	}
}
?>

Add pageType to rest controller

Add pageType to rest controller


<?php

/*
 * This file is part of SmartGas, an iOS app to find the best gas station nearby.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 * (c) Mateus Silva <mateusgsilva_@hotmail.com>
 * (c) Fábio Marques <fabio1956.epo@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

class CreateTypesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('value');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('types');
    }
}

<?php

/*
 * This file is part of SmartGas, an iOS app to find the best gas station nearby.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 * (c) Mateus Silva <mateusgsilva_@hotmail.com>
 * (c) Fábio Marques <fabio1956.epo@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

class CreateTypesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('value');
            $table->integer('parent_id')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('types');
    }
}

Add a column to set a "parent" fuel

Add a column to set a "parent" fuel


<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class SendToLaravelShift
{
    public function send(array $payload): bool
    {
        info('Sharing stats with stats.laravelshift.com', $payload);

        if (app()->environment('testing')) {
            return true;
        }

        try {
            $client = new Client([
                'base_uri' => 'https://laravelshift.com',
                'timeout' => 1,
                'headers' => ['Accept' => 'application/json'],
            ]);

            $response = $client->request('POST', '/api/stat', [
                'json' => $payload,
            ]);
        } catch (GuzzleException $exception) {
            info('Unable to share stats: ' . $exception->getMessage());
            return false;
        }

        if (in_array($response->getStatusCode(), [201, 204])) {
            info("Thanks for sharing your project data with the community!");
            return true;
        }

        return false;
    }
}

<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class SendToLaravelShift
{
    public function send(array $payload): bool
    {
        info('Sharing stats with stats.laravelshift.com', $payload);

        if (app()->environment('testing')) {
            return true;
        }

        try {
            $client = new Client([
                'base_uri' => 'https://laravelshift.com',
                'timeout' => 5,
                'headers' => ['Accept' => 'application/json'],
            ]);

            $response = $client->request('POST', '/api/stat', [
                'json' => $payload,
            ]);
        } catch (GuzzleException $exception) {
            info('Unable to share stats: ' . $exception->getMessage());
            return false;
        }

        if (in_array($response->getStatusCode(), [201, 204])) {
            info("Thanks for sharing your project data with the community!");
            return true;
        }

        return false;
    }
}

Increment Timeout to Share API

Increment Timeout to Share API


<?php

namespace Test\Unit;

use Test\TestCase;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class CrudApiHelperTest extends TestCase
{
    public function testGetRelatedFieldForUserId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('user_id');
        $this->assertEquals('user', $related_field);
    }

    public function testGetRelatedFieldForOrganisationId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('organisation_id');
        $this->assertEquals('organisation', $related_field);
    }

    public function testGetModelDisplayNameWithoutAnInstance()
    {
        $options = [
            'namespace' => null,
            'model' => 'User'
        ];
        $crudApi = new CrudApi($options);
        $display = $crudApi->getModelDisplayName();
        $this->assertEquals('User', $display);
    }

    public function testAuthorUserModelBinding()
    {
        $crudApi = new CrudApi(['namespace' => 'Test\\Models\\', 'model' => 'Post']);
        $related_field = $crudApi->getRelatedField('author_id');
        $this->assertEquals('author', $related_field);
        $relation = $crudApi->getRelatedModel($related_field);
        $class = get_class($relation);
        $this->assertEquals('Test\\Models\\User', $class);
    }
}

<?php

namespace Test\Unit;

use Test\TestCase;
use \Mockery as m;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class CrudApiHelperTest extends TestCase
{
    public function testGetRelatedFieldForUserId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('user_id');
        $this->assertEquals('user', $related_field);
    }

    public function testGetRelatedFieldForOrganisationId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('organisation_id');
        $this->assertEquals('organisation', $related_field);
    }

    public function testGetModelDisplayNameWithoutAnInstance()
    {
        $options = [
            'namespace' => null,
            'model' => 'User'
        ];
        $crudApi = new CrudApi($options);
        $display = $crudApi->getModelDisplayName();
        $this->assertEquals('User', $display);
    }

    public function testAuthorUserModelBinding()
    {
        $crudApi = new CrudApi(['namespace' => 'Test\\Models\\', 'model' => 'Post']);
        $related_field = $crudApi->getRelatedField('author_id');
        $this->assertEquals('author', $related_field);
        $relation = $crudApi->getRelatedModel($related_field);
        $class = get_class($relation);
        $this->assertEquals('Test\\Models\\User', $class);
    }

    public function testSetModelHelper()
    {
        $options = ['namespace' => null];
        $crudApi = new CrudApi($options);
        $crudApi->setModelHelper('test');
        $this->assertEquals('test', $crudApi->modelHelper);
    }
}

Test set model helper method.

Test set model helper method.


<?php

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

$php = new PHPPHP\PHP;

if (isset($argv[1]) && !isset($argv[2])) {
    $file = realpath($argv[1]);
    $php->executeFile($file);
} elseif (isset($argv[1]) && $argv[1] == '-r') {
    $code = $argv[2];
    $php->execute('<?php ' . $code);
}

<?php

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

$php = new PHPPHP\PHP;

list($options, $args) = parseCliArgs($argv);

if (isset($options['f'])) {
    $php->executeFile(realpath($options['f']));
} elseif (isset($options['r'])) {
    $php->execute('<?php ' . $options['r']);
} elseif (isset($args[0])) {
    $php->executeFile(realpath($args[0]));
} else {
    echo "Invalid arguments\n";
}

function parseCliArgs(array $args) {
    // first element is script name
    array_shift($args);

    $options = array();
    $arguments = array();

    $currentOption = null;
    foreach ($args as $arg) {
        if ($currentOption) {
            $options[$currentOption] = $arg;
            $currentOption = null;
        } elseif (strlen($arg) == 2 && $arg[0] == '-') {
            $currentOption = $arg[1];
        } else {
            $arguments[] = $arg;
        }
    }

    return array($options, $arguments);
}

Add support for -f option

Add support for -f option

Now it's possible to use php.php as a test executable for run-tests.php


<?php

namespace Luxury\Foundation\Cli\Tasks;

use Luxury\Cli\Task;

/**
 * Class ClearCompiledTask
 *
 * @package Luxury\Foundation\Cli
 */
class ClearCompiledTask extends Task
{
    /**
     * @description Clear compilation.
     */
    public function mainAction()
    {
        $compileDir = $this->config->paths->base . 'bootstrap/compile/';

        if (file_exists($compileDir . 'loader.php')) {
            @unlink($compileDir . 'loader.php');
        }

        $this->info('The compiled loader has been removed.');
    }
}

<?php

namespace Luxury\Foundation\Cli\Tasks;

use Luxury\Cli\Task;

/**
 * Class ClearCompiledTask
 *
 * @package Luxury\Foundation\Cli
 */
class ClearCompiledTask extends Task
{
    /**
     * @description Clear compilation.
     */
    public function mainAction()
    {
        $compileDir = $this->config->paths->base . 'bootstrap/compile/';

        if (file_exists($compileDir . 'loader.php')) {
            @unlink($compileDir . 'loader.php');
        }

        $this->info('The compiled loader has been removed.');
    }

    /**
     * Handle the post-[install|update] Composer event.
     *
     * @return void
     */
    public static function composerClearCompiled()
    {
        $compileDir = getcwd() . DIRECTORY_SEPARATOR . 'bootstrap/compile/';

        if (file_exists($compileDir . 'loader.php')) {
            @unlink($compileDir . 'loader.php');
        }
    }
}

Add static method to handle post-install & post-update composer event


<?php

return [
    'adminEmail' => getenv('ADMIN_EMAIL'),

    'hh.clientId' => getenv('HH_CLIENT_ID'),
    'hh.clientSecret' => getenv('HH_CLIENT_SECRET'),
    'hh.returnUrl' => getenv('HH_CLIENT_RETURN_URL'),
    'hh.userAgent' => getenv('HH_USER_AGENT'),
];

<?php

return [
    'adminEmail' => getenv('ADMIN_EMAIL'),

    'hh.clientId' => getenv('HH_CLIENT_ID'),
    'hh.clientSecret' => getenv('HH_CLIENT_SECRET'),
    'hh.returnUrl' => getenv('HH_RETURN_URL'),
    'hh.userAgent' => getenv('HH_USER_AGENT'),
];

Fix return url env var name

Fix return url env var name


<?php

namespace ActiveCollab\Payments\Subscription\SubscriptionEvent;

use ActiveCollab\Payments\Gateway\GatewayInterface;
use ActiveCollab\Payments\Subscription\SubscriptionInterface;
use RuntimeException;

/**
 * @package ActiveCollab\Payments\Subscription\SubscriptionEvent
 */
trait Implementation
{
    /**
     * @var string
     */
    private $subscription_reference;

    /**
     * Return subscription reference (subscription ID)
     *
     * @return string
     */
    public function getSubscriptionReference()
    {
        return $this->subscription_reference;
    }

    /**
     * Return subscription by subscription reference
     *
     * @return SubscriptionInterface
     */
    public function getSubscription()
    {
        if ($this->getGateway() instanceof GatewayInterface) {
            return $this->getGateway()->getOrderByReference($this->getSubscriptionReference());
        }

        throw new RuntimeException('Gateway is not set');
    }

    /**
     * Return parent gateway
     *
     * @return GatewayInterface
     */
    abstract public function &getGateway();
}

<?php

namespace ActiveCollab\Payments\Subscription\SubscriptionEvent;

use ActiveCollab\Payments\Gateway\GatewayInterface;
use ActiveCollab\Payments\Subscription\SubscriptionInterface;
use RuntimeException;

/**
 * @package ActiveCollab\Payments\Subscription\SubscriptionEvent
 */
trait Implementation
{
    /**
     * @var string
     */
    private $subscription_reference;

    /**
     * Return subscription reference (subscription ID)
     *
     * @return string
     */
    public function getSubscriptionReference()
    {
        return $this->subscription_reference;
    }

    /**
     * Return subscription by subscription reference
     *
     * @return SubscriptionInterface
     */
    public function getSubscription()
    {
        if ($this->getGateway() instanceof GatewayInterface) {
            return $this->getGateway()->getSubscriptionByReference($this->getSubscriptionReference());
        }

        throw new RuntimeException('Gateway is not set');
    }

    /**
     * Return parent gateway
     *
     * @return GatewayInterface
     */
    abstract public function &getGateway();
}


<?php
declare(strict_types = 1);
/**
 * /src/Validator/Constraints/UniqueUsernameValidator.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Validator\Constraints;

use App\Entity\Interfaces\UserInterface;
use App\Repository\UserRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class UniqueUsernameValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class UniqueUsernameValidator extends ConstraintValidator
{
    private UserRepository $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * {@inheritdoc}
     *
     * @throws NonUniqueResultException
     */
    public function validate($value, Constraint $constraint): void
    {
        if ($value instanceof UserInterface
            && !$this->repository->isUsernameAvailable($value->getUsername(), $value->getId())
        ) {
            $this->context
                ->buildViolation(UniqueUsername::MESSAGE)
                ->setCode(UniqueUsername::IS_UNIQUE_USERNAME_ERROR)
                ->addViolation();
        }
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Validator/Constraints/UniqueUsernameValidator.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Validator\Constraints;

use App\Entity\Interfaces\UserInterface;
use App\Repository\UserRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class UniqueUsernameValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class UniqueUsernameValidator extends ConstraintValidator
{
    public function __construct(
        private UserRepository $repository,
    ) {
    }

    /**
     * {@inheritdoc}
     *
     * @throws NonUniqueResultException
     */
    public function validate($value, Constraint $constraint): void
    {
        if ($value instanceof UserInterface
            && !$this->repository->isUsernameAvailable($value->getUsername(), $value->getId())
        ) {
            $this->context
                ->buildViolation(UniqueUsername::MESSAGE)
                ->setCode(UniqueUsername::IS_UNIQUE_USERNAME_ERROR)
                ->addViolation();
        }
    }
}

Use PHP 8 constructor property promotion


<?php
	function navigation()
	{
		$navigation = Array();
		$navigation[] = (object) Array('url' => 'ingredients/table', 'label' => 'Ingredients');
		$navigation[] = (object) Array('url' => 'effects/table', 'label' => 'Effects');
		$navigation[] = (object) Array('url' => 'ingredients/tips', 'label' => 'Tips');
		$navigation[] = (object) Array('url' => 'ingredients/calculator', 'label' => 'Calculator');
		return $navigation;
	}
?>

<?php
	function navigation()
	{
		$navigation = Array();
		$navigation[] = (object) Array('url' => 'ingredients/table', 'label' => 'Ingredients');
		$navigation[] = (object) Array('url' => 'effects/table', 'label' => 'Effects');
		$navigation[] = (object) Array('url' => 'ingredients/tips', 'label' => 'Tips');
		$navigation[] = (object) Array('url' => 'ingredients/calculator', 'label' => 'Calculator');
		$navigation[] = (object) Array('url' => 'ingredients/matrix', 'label' => 'Matrix');
		return $navigation;
	}
?>

Add ingredients matrix to navigation

Add ingredients matrix to navigation


<?php

// basic if - else
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

// if with a negation
if (! $expr1) {
    // if  body
}

// if with an operand
if ($expr1 && $expr2) {
    // if body
} else {
    // else body;
}

// if with long expression
if ($expr1 &&
    $expr2 &&
    $expr3 &&
    $expr4 &&) {
    // if  body
}

// switch statement
switch ($expr) {
    case 0:
        echo 'First case, with a break';
        break;
    case 1:
        echo 'Second case, which falls through';
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        return;
    default:
        echo 'Default case';
        break;
}

// for loop
for ($i = 0; $i < 10; $i++) {
    // for body
}

// foreach loop
foreach ($iterable as $key => $value) {
    // foreach body
}

// try - catch
try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}

<?php

// basic if - else
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

// if with a negation
if (!$expr1) {
    // if  body
}

// if with an operand
if ($expr1 && $expr2) {
    // if body
} else {
    // else body;
}

// if with long expression
if ($expr1 &&
    $expr2 &&
    $expr3 &&
    $expr4 &&) {
    // if  body
}

// switch statement
switch ($expr) {
    case 0:
        echo 'First case, with a break';
        break;
    case 1:
        echo 'Second case, which falls through';
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        return;
    default:
        echo 'Default case';
        break;
}

// for loop
for ($i = 0; $i < 10; $i++) {
    // for body
}

// foreach loop
foreach ($iterable as $key => $value) {
    // foreach body
}

// try - catch
try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}

Update control statement negation example


<?php
namespace Rbs\Commerce\Blocks;

use Change\Presentation\Blocks\Information;

/**
 * @name \Rbs\Commerce\Blocks\OrderProcessInformation
 */
class OrderProcessInformation extends Information
{
	public function onInformation(\Change\Events\Event $event)
	{
		parent::onInformation($event);
		$i18nManager = $event->getApplicationServices()->getI18nManager();
		$ucf = array('ucf');
		$this->setSection($i18nManager->trans('m.rbs.commerce.admin.module_name', $ucf));
		$this->setLabel($i18nManager->trans('m.rbs.commerce.admin.cart_label', $ucf));
		$this->addInformationMeta('realm', Property::TYPE_STRING, true, 'web')
			->setLabel($i18nManager->trans('m.rbs.user.admin.login_realm', $ucf));
		$this->setFunctions(array(
			'Rbs_Commerce_OrderProcess' => $i18nManager->trans('m.rbs.commerce.admin.order_process_function', $ucf)
		));
	}
}

<?php
namespace Rbs\Commerce\Blocks;

use Change\Documents\Property;
use Change\Presentation\Blocks\Information;

/**
 * @name \Rbs\Commerce\Blocks\OrderProcessInformation
 */
class OrderProcessInformation extends Information
{
	public function onInformation(\Change\Events\Event $event)
	{
		parent::onInformation($event);
		$i18nManager = $event->getApplicationServices()->getI18nManager();
		$ucf = array('ucf');
		$this->setSection($i18nManager->trans('m.rbs.commerce.admin.module_name', $ucf));
		$this->setLabel($i18nManager->trans('m.rbs.commerce.admin.cart_label', $ucf));
		$this->addInformationMeta('realm', Property::TYPE_STRING, true, 'web')
			->setLabel($i18nManager->trans('m.rbs.user.admin.login_realm', $ucf));
		$this->setFunctions(array(
			'Rbs_Commerce_OrderProcess' => $i18nManager->trans('m.rbs.commerce.admin.order_process_function', $ucf)
		));
	}
}

Fix admin page content editor

Fix admin page content editor


<?php

/*
 * This file is part of the Ivory CKEditor package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\CKEditorBundle\DependencyInjection;

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

/**
 * Ivory CKEditor extension
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class IvoryCKEditorExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $container->setParameter('twig.form.resources', array_merge(
            $container->getParameter('twig.form.resources'),
            array('IvoryCKEditorBundle:Form:ckeditor_widget.html.twig')
        ));

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

<?php

/*
 * This file is part of the Ivory CKEditor package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\CKEditorBundle\DependencyInjection;

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

/**
 * Ivory CKEditor extension
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class IvoryCKEditorExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $container->setParameter('twig.form.resources', array_merge(
            $container->getParameter('twig.form.resources'),
            array('IvoryCKEditorBundle:Form:ckeditor_widget.html.twig')
        ));

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

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'ivory_ckeditor';
    }
}

[DependencyInjection] Use ivory_ckeditor instead of ivory_ck_editor as alias


<?php
/*
    Copyright 2014 Victor Hurdugaci (http://victorhurdugaci.com)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
?>

<div id="sidebar-footer" class="sidebar row">
	<?php
        if (!dynamic_sidebar(Sidebars::Footer)) {
        }
	?>
</div>

<?php
/*
    Copyright 2014 Victor Hurdugaci (http://victorhurdugaci.com)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
?>

<div id="sidebar-footer" class="sidebar row hidden-xs">
	<?php
        if (!dynamic_sidebar(Sidebars::Footer)) {
        }
	?>
</div>

Hide footer sidebar on xs screen

Hide footer sidebar on xs screen


@extends('layouts.app')

@section('wrap')

文言文語譯

            @for ($i =  1; $i <= min(10, count($links)); $i += 1)
                {{ $links[$i] }}
            @endfor

2014文憑試口語

            @for ($i =  10; $i <= min(16, count($links)); $i += 1)
                {{ $links[$i] }}
            @endfor

@endsection

@section('scripts')
    @parent

@endsection

@extends('layouts.app')

@section('wrap')

文言文語譯

            @for ($i =  1; $i <= min(10, count($links)); $i += 1)
                {{ $links[$i] }}
            @endfor

2014文憑試口語

            @for ($i =  11; $i <= min(16, count($links)); $i += 1)
                {{ $links[$i] }}
            @endfor

@endsection

@section('scripts')
    @parent

@endsection

Fix the one offset error

Fix the one offset error