<?php
/**
 * Class Google\Site_Kit\Core\Assets\External\GoogleCharts
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Assets\External;

use Google\Site_Kit\Context;
use Google\Site_Kit\Core\Assets\Script;

/**
 * Class representing the Google Charts script.
 *
 * @since n.e.x.t
 * @access private
 * @ignore
 */
class GoogleCharts extends Script {

	/**
	 * Registers the asset.
	 *
	 * @since n.e.x.t
	 *
	 * @param Context $context Plugin context.
	 */
	public function register( Context $context ) {
		wp_register_script( // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
			$this->handle,
			'https://www.gstatic.com/charts/loader.js',
			(array) $this->args['dependencies'],
			null,
			$this->args['in_footer']
		);

		wp_add_inline_script(
			$this->handle,
			'google.charts.load( "current", { packages: [ "corechart" ] } );'
		);
	}

}

<?php
/**
 * Class Google\Site_Kit\Core\Assets\External\GoogleCharts
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Assets\External;

use Google\Site_Kit\Context;
use Google\Site_Kit\Core\Assets\Script;

/**
 * Class representing the Google Charts script.
 *
 * @since n.e.x.t
 * @access private
 * @ignore
 */
class GoogleCharts extends Script {

	/**
	 * Registers the asset.
	 *
	 * @since n.e.x.t
	 *
	 * @param Context $context Plugin context.
	 */
	public function register( Context $context ) {
		wp_register_script( // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
			$this->handle,
			'https://www.gstatic.com/charts/loader.js',
			(array) $this->args['dependencies'],
			null,
			$this->args['in_footer']
		);

		wp_add_inline_script(
			$this->handle,
			'google.charts.load( "current", { packages: [ "corechart" ] } );'
		);
	}

}

Fix typo in the file header.

Fix typo in the file header.


<?php namespace Dingo\Api\Http\ResponseFormat;

class JsonpResponseFormat extends JsonResponseFormat
{
    /**
     * Name of JSONP callback paramater.
     *
     * @var string
     */
    protected $callbackName = 'callback';

    /**
     * Determine if a callback is valid.
     *
     * @return bool
     */
    protected function hasValidCallback()
    {
        return $this->request->query->has($this->callbackName);
    }

    /**
     * Get the callback from the query string.
     *
     * @return string
     */
    protected function getCallback()
    {
        return $this->request->query->get($this->callbackName);
    }

    /**
     * Get the response content type.
     *
     * @return string
     */
    public function getContentType()
    {
        if ($this->hasValidCallback()) {
            return 'application/javascript';
        }

        return parent::getContentType();
    }

    /**
     * Encode the content to its JSON representation.
     *
     * @param  string  $content
     * @return string
     */
    protected function encode($content)
    {
        if ($this->hasValidCallback()) {
            return sprintf('%s(%s);', $this->getCallback(), json_encode($content));
        }

        return parent::encode($content);
    }
}

<?php namespace Dingo\Api\Http\ResponseFormat;

class JsonpResponseFormat extends JsonResponseFormat
{
    /**
     * Name of JSONP callback paramater.
     *
     * @var string
     */
    protected $callbackName = 'callback';

    /**
     * Create a new JSONP response formatter instance.
     *
     * @param  string  $callbackName
     * @return void
     */
    public function __construct($callbackName = 'callback')
    {
        $this->callbackName = $callbackName;
    }

    /**
     * Determine if a callback is valid.
     *
     * @return bool
     */
    protected function hasValidCallback()
    {
        return $this->request->query->has($this->callbackName);
    }

    /**
     * Get the callback from the query string.
     *
     * @return string
     */
    protected function getCallback()
    {
        return $this->request->query->get($this->callbackName);
    }

    /**
     * Get the response content type.
     *
     * @return string
     */
    public function getContentType()
    {
        if ($this->hasValidCallback()) {
            return 'application/javascript';
        }

        return parent::getContentType();
    }

    /**
     * Encode the content to its JSON representation.
     *
     * @param  string  $content
     * @return string
     */
    protected function encode($content)
    {
        if ($this->hasValidCallback()) {
            return sprintf('%s(%s);', $this->getCallback(), json_encode($content));
        }

        return parent::encode($content);
    }
}

Allow the callback parameter name to be changed in the constructor.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
@yield('head')
@yield('meta')
@yield('styles')
</head>
<body>
@include('themes::paladindigital.laravel-bootstrap._nav')
@yield('content')
<aside>
@yield('sidebar')
@yield('widgets')
</aside>
@include('themes::paladindigital.laravel-bootstrap._footer')
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@yield('scripts')
</body>
</html>

<?php
/*
 * Theme Name: Bootstrap
 * Author: Paladin Digital
 */
$theme = 'themes::paladindigital.laravel-bootstrap';

?><!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
@yield('head')
@yield('meta')
@yield('styles')
</head>
<body>
@include($theme . '._nav')
@yield('content')
<aside>
@yield('sidebar')
@yield('widgets')
</aside>
@include($theme . '._footer')
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@yield('scripts')
</body>
</html>

Update to use theme header.

Update to use theme header.


<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/text-button.php';
require_once __DIR__ . '/../../lib/utils.php';

class UserProfileView extends RawDataContainer implements Component {
  public function render(): Component {
    $urlQuery = $this->get('url-query');

    return HtmlElement::emmetTop('a#login-anchor.login', [
      'href' => $urlQuery->assign([
        'page' => 'login',
        'previous-page' => $this->get('page'),
      ])->getUrlQuery(),
      new PrimaryButton('Đăng nhập'),
    ]);
  }
}
?>

<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/text-button.php';
require_once __DIR__ . '/../../lib/utils.php';

class UserProfileView extends RawDataContainer implements Component {
  public function render(): Component {
    $urlQuery = $this->get('url-query');
    $login = $this->get('login');

    return $login->isLoggedIn()
      ? HtmlElement::emmetTop('#user-profile-view.logged-in', [
        HtmlElement::emmetBottom('button#profile-button>img#profile-image', [
          'src' => 'Your Image Here...',
        ]),
        HtmlElement::emmetTop('#profile-setting', [
          HtmlElement::emmetBottom('button.logout>a', [
            'href' => $urlQuery->assign([
              'page' => 'logout',
              'previous-page' => $this->get('page'),
            ])->getUrlQuery(),
            'Đăng xuất',
          ]),
        ]),
      ])
      : HtmlElement::emmetTop('a#login-anchor.login', [
        'href' => $urlQuery->assign([
          'page' => 'login',
          'previous-page' => $this->get('page'),
        ])->getUrlQuery(),
        new PrimaryButton('Đăng nhập'),
      ])
    ;
  }
}
?>

Change UserProfileView base on logged-in value


<?php

namespace App\Models;

use ActiveRecord\DateTime;

/**
 * @property int      $id
 * @property int      $post_id
 * @property int      $reserved_by
 * @property int      $response_code
 * @property string   $failing_url
 * @property DateTime $created_at
 * @property DateTime $updated_at
 * @property Post     $post          (Via magic method)
 */
class BrokenPost extends NSModel {
  public static $belongs_to = [
    ['post']
  ];

  public static function record(int $post_id, int $response_code, string $failing_url, string $reserved_by) {
    self::create([
      'post_id' => $post_id,
      'response_code' => $response_code,
      'failing_url' => $failing_url,
      'reserved_by' => $reserved_by,
    ]);
  }
}

<?php

namespace App\Models;

use ActiveRecord\DateTime;

/**
 * @property int      $id
 * @property int      $post_id
 * @property int      $reserved_by
 * @property int      $response_code
 * @property string   $failing_url
 * @property DateTime $created_at
 * @property DateTime $updated_at
 * @property Post     $post          (Via magic method)
 */
class BrokenPost extends NSModel {
  public static $belongs_to = [
    ['post']
  ];

  public static function record(int $post_id, int $response_code, string $failing_url, ?string $reserved_by) {
    self::create([
      'post_id' => $post_id,
      'response_code' => $response_code,
      'failing_url' => $failing_url,
      'reserved_by' => $reserved_by,
    ]);
  }
}

Allow null reserved_by value for broken post records


<?php

namespace App\Actions;

use App\Shell;

class OpenInEditor
{
    public function __invoke()
    {
        app('console')->info('Opening your editor.');

        (new Shell)->execInProject($this->editor() . " .");
    }

    public function editor()
    {
        // For when we allow it to be customized
        return 'code';
    }
}

<?php

namespace App\Actions;

use App\Shell;

class OpenInEditor
{
    public function __invoke()
    {
        app('console')->info('Opening your editor.');

        if ($this->editor()) {
            (new Shell)->execInProject($this->editor() . " .");
        }
    }

    public function editor()
    {
        return app('console')->option('editor');
    }
}

Allow editor to be customized

Allow editor to be customized


<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2018 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

use OpenCFP\Environment;
use OpenCFP\Kernel;

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

$kernel = new Kernel((string) Environment::fromServer($_SERVER), false);
$kernel->boot();

$container = $kernel->getContainer();

return [
    'paths' => [
        'migrations' => '%%PHINX_CONFIG_DIR%%/migrations',
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_database'        => $kernel->getEnvironment(),
        $kernel->getEnvironment() => [
            'adapter' => 'mysql',
            'host'    => $container->getParameter('database.host'),
            'name'    => $container->getParameter('database.database'),
            'user'    => $container->getParameter('database.user'),
            'pass'    => $container->getParameter('database.password'),
        ],
    ],
];

<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2018 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

use OpenCFP\Environment;
use OpenCFP\Kernel;

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

$kernel = new Kernel((string) Environment::fromServer($_SERVER), false);
$kernel->boot();

$container = $kernel->getContainer();

return [
    'paths' => [
        'migrations' => '%%PHINX_CONFIG_DIR%%/migrations',
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_database'        => $kernel->getEnvironment(),
        $kernel->getEnvironment() => [
            'adapter' => 'mysql',
            'host'    => $container->getParameter('database.host'),
            'name'    => $container->getParameter('database.database'),
            'user'    => $container->getParameter('database.user'),
            'pass'    => $container->getParameter('database.password'),
            'charset' => 'utf8-mb4',
            'collation' => 'utf8-mb4_unicode_ci',
        ],
    ],
];

Set default charset for tables to utf-mb4

That way *all* Unicode-Characters can find their way into the CFP and not only those of the first Unicode-Plane. Which is missing f.e. the emojis… ;)


<?php

class Aplazame_Aplazame_Http_WpClient implements Aplazame_Sdk_Http_ClientInterface {

	public function send( Aplazame_Sdk_Http_RequestInterface $request ) {
		$rawHeaders = array();
		foreach ( $request->getHeaders() as $header => $value ) {
			$rawHeaders[ $header ] = implode( ', ', $value );
		}

	    $args = array(
			'headers' => $rawHeaders,
			'method'  => $request->getMethod(),
			'body'    => $request->getBody(),
		);

		$wpResponse = wp_remote_request( $request->getUri(), $args );
	    if ( is_wp_error( $wpResponse ) ) {
		    throw new RuntimeException( $wpResponse->get_error_message(), $wpResponse->get_error_code() );
		}

		$responseBody = wp_remote_retrieve_body( $wpResponse );

		$response = new Aplazame_Sdk_Http_Response(
	        wp_remote_retrieve_response_code( $wpResponse ),
			$responseBody
		);

		return $response;
	}
}

<?php

class Aplazame_Aplazame_Http_WpClient implements Aplazame_Sdk_Http_ClientInterface {

	public function send( Aplazame_Sdk_Http_RequestInterface $request ) {
		$rawHeaders = array();
		foreach ( $request->getHeaders() as $header => $value ) {
			$rawHeaders[ $header ] = implode( ', ', $value );
		}

	    $args = array(
			'headers' => $rawHeaders,
			'method'  => $request->getMethod(),
			'body'    => $request->getBody(),
		);

		$wpResponse = wp_remote_request( $request->getUri(), $args );
	    if ( is_wp_error( $wpResponse ) ) {
		    throw new RuntimeException( $wpResponse->get_error_message(), (int) $wpResponse->get_error_code() );
		}

		$responseBody = wp_remote_retrieve_body( $wpResponse );

		$response = new Aplazame_Sdk_Http_Response(
	        wp_remote_retrieve_response_code( $wpResponse ),
			$responseBody
		);

		return $response;
	}
}

Fix scenarios where WP_Error::get_error_code() return string


<?php

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

$config = [
    'id' => 'yii2-papertrail-log-target',
    'basePath' => __DIR__,
    'bootstrap' => ['log'],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => Rekurzia\Log\PapertrailTarget::class,
                    'levels' => ['error', 'warning'],
                    'host' => '0.0.0.0',
                    'port' => '1234',
                ],
            ]
        ]
    ]
];

(new yii\web\Application($config))->run();

<?php

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

$config = [
    'id' => 'yii2-papertrail-log-target',
    'basePath' => __DIR__,
    'bootstrap' => ['log'],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => Rekurzia\Log\PapertrailTarget::class,
                    'levels' => ['error', 'warning'],
                    'host' => 'localhost',
                    'port' => '1234',
                ],
            ]
        ]
    ]
];

(new yii\web\Application($config))->run();

Revert "Try to send to 0.0.0.0 instead of localhost"

This reverts commit 6eea8961661327251a086b8d1fef2813471a6fc8.


<?php

namespace StrictPhp\TypeFinder;

use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tag\VarTag;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\ContextFactory;
use ReflectionProperty;

final class PropertyTypeFinder
{
    /**
     * @param ReflectionProperty $reflectionProperty
     *
     * @return \phpDocumentor\Reflection\Type[]
     */
    public function __invoke(ReflectionProperty $reflectionProperty)
    {
        $typeResolver = new TypeResolver();
        $context      = (new ContextFactory())->createFromReflector($reflectionProperty->getDeclaringClass());

        return array_unique(array_filter(array_merge(
            [],
            [],
            ...array_map(
                function (VarTag $varTag) use ($typeResolver, $context) {
                    return array_map(
                        function ($type) use ($typeResolver, $context) {
                            return $typeResolver->resolve($type, $context);
                        },
                        $varTag->getTypes()
                    );
                },
                // note: this will not compute imports for us! Need a better alternative!
                (new DocBlock($reflectionProperty))->getTagsByName('var')
            )
        )));
    }
}

<?php

namespace StrictPhp\TypeFinder;

use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tag\VarTag;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\ContextFactory;
use ReflectionProperty;

final class PropertyTypeFinder
{
    /**
     * @param ReflectionProperty $reflectionProperty
     *
     * @return \phpDocumentor\Reflection\Type[]
     */
    public function __invoke(ReflectionProperty $reflectionProperty)
    {
        $typeResolver = new TypeResolver();
        $context      = (new ContextFactory())->createFromReflector($reflectionProperty);

        return array_unique(array_filter(array_merge(
            [],
            [],
            ...array_map(
                function (VarTag $varTag) use ($typeResolver, $context) {
                    return array_map(
                        function ($type) use ($typeResolver, $context) {
                            return $typeResolver->resolve(ltrim($type, '\\'), $context);
                        },
                        $varTag->getTypes()
                    );
                },
                // note: this will not compute imports for us! Need a better alternative!
                (new DocBlock($reflectionProperty))->getTagsByName('var')
            )
        )));
    }
}

Trim initial slash on names

Trim initial slash on names


<?php

namespace Vectorface\Cache\Common;

/**
 * Wraps (get|set|delete) operations with their multiple counterparts
 *
 * This is useful when the underlying cache doesn't implement multi ops
 */
trait MultipleTrait
{
    abstract protected function keys($keys);

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function getMultiple($keys, $default = null)
    {
        $values = [];
        foreach ($this->keys($keys) as $key) {
            $values[$key] = $this->get($key, $default);
        }

        return $values;
    }

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function setMultiple($values, $ttl = null)
    {
        $success = true;
        foreach ($this->values($values) as $key => $value) {
            $success = $this->set($key, $value, $ttl) && $success;
        }
        return $success;
    }

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function deleteMultiple($keys)
    {
        $success = true;
        foreach ($keys as $key) {
            $success = $this->delete($key) && $success;
        }
        return $success;
    }
}

<?php

namespace Vectorface\Cache\Common;

/**
 * Wraps (get|set|delete) operations with their multiple counterparts
 *
 * This is useful when the underlying cache doesn't implement multi ops
 */
trait MultipleTrait
{
    abstract public function get($key, $default);
    abstract public function set($key, $value, $ttl = null);
    abstract public function delete($key);
    abstract protected function keys($keys);
    abstract protected function values($values);

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function getMultiple($keys, $default = null)
    {
        $values = [];
        foreach ($this->keys($keys) as $key) {
            $values[$key] = $this->get($key, $default);
        }

        return $values;
    }

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function setMultiple($values, $ttl = null)
    {
        $success = true;
        foreach ($this->values($values) as $key => $value) {
            $success = $this->set($key, $value, $ttl) && $success;
        }
        return $success;
    }

    /**
     * @inheritDoc \Psr\SimpleCache\CacheInterface
     */
    public function deleteMultiple($keys)
    {
        $success = true;
        foreach ($keys as $key) {
            $success = $this->delete($key) && $success;
        }
        return $success;
    }
}

Add interface functions as abstract on trait to ensure correct operation


<?php
class changeSitetreeForm extends SitetreeForm
{
  public function setup()
  {
    parent::setup();

    // set sitetree for form
    $tree = siteManager::getInstance()->getSitetreeForForm($this->object->site, null, false, array('lft'=>$this->object->lft, 'rgt'=>$this->object->rgt));

    $this->widgetSchema['parent'] = new sfWidgetFormChoice(array('choices'=>$tree));
    $this->validatorSchema['parent'] = new sfValidatorCallback(array('callback'=>array($this, 'checkParent')), array('invalid'=>'This is already the parent page'));
    $this->widgetSchema->setHelp('parent', 'Select where you want to move this page to - the page you select will become the parent page');

    $this->useFields(array('parent'));
  }

  public function checkParent($validator, $value)
  {
    $currentParent = $this->object->getNode()->getParent();

    if ($value == $currentParent->route_name)
    {
      $error = new sfValidatorError($validator, 'invalid');
      throw new sfValidatorErrorSchema($validator, array('parent' => $error));
    }

    return $value;
  }

  public function doSave($con = null)
  {
    $parent = SitetreeTable::getInstance()->findOneByRouteName($this->getValue('parent'));
    $this->object->getNode()->moveAsLastChildOf($parent);
  }
}

<?php
class changeSitetreeForm extends SitetreeForm
{
  public function setup()
  {
    parent::setup();

    // set sitetree for form
    $tree = siteManager::getInstance()->getSitetreeForForm($this->object->site, null, false, array('lft'=>$this->object->lft, 'rgt'=>$this->object->rgt), 'id');

    $this->widgetSchema['parent'] = new sfWidgetFormChoice(array('choices'=>$tree));
    $this->validatorSchema['parent'] = new sfValidatorCallback(array('callback'=>array($this, 'checkParent')), array('invalid'=>'This is already the parent page'));
    $this->widgetSchema->setHelp('parent', 'Select where you want to move this page to - the page you select will become the parent page');

    $this->useFields(array('parent', 'site'));
  }

  public function checkParent($validator, $value)
  {
    $currentParent = $this->object->getNode()->getParent();

    if ($value == $currentParent->route_name)
    {
      $error = new sfValidatorError($validator, 'invalid');
      throw new sfValidatorErrorSchema($validator, array('parent' => $error));
    }

    return $value;
  }

  public function doSave($con = null)
  {
    $parent = SitetreeTable::getInstance()->findOneById($this->getValue('parent'));
    $this->object->getNode()->moveAsLastChildOf($parent);
  }
}

Fix for moving parent - accidentally moving site!


<?php

namespace Phansible\Roles;

use Phansible\BaseRole;
use Phansible\Model\VagrantBundle;

class Hhvm extends BaseRole
{
    protected $name = 'HHVM';
    protected $slug = 'hhvm';
    protected $role = 'hhvm';

    public function getInitialValues()
    {
        return [
          'install' => 0,
          'host' => '127.0.0.1',
          'port' => 9000,
        ];
    }

    public function setup(array $requestVars, VagrantBundle $vagrantBundle)
    {
        parent::setup($requestVars, $vagrantBundle);

        /*
        if ($requestVars[$this->getSlug()]['composer'] == 1) {
            $vagrantBundle->getPlaybook()->addRole('composer');
        }
        */
    }
}

<?php

namespace Phansible\Roles;

use Phansible\BaseRole;
use Phansible\Model\VagrantBundle;

class Hhvm extends BaseRole
{
    protected $name = 'HHVM';
    protected $slug = 'hhvm';
    protected $role = 'hhvm';

    public function getInitialValues()
    {
        return [
          'install' => 0,
          'host' => '127.0.0.1',
          'port' => 9000,
        ];
    }
}

Remove some kind of test from HHVM

Remove some kind of test from HHVM

Seems like someone left a test code here. to bad!


<?php

namespace Palmtree\Csv\Normalizer;

/**
 * NumberNormalizer converts numeric strings to ints and floats.
 */
class NumberNormalizer extends AbstractNormalizer
{
    protected $decimals;

    /**
     * NumberNormalizer constructor.
     *
     * @param null|NormalizerInterface $normalizer
     * @param null|int                 $decimals
     */
    public function __construct($normalizer = null, $decimals = null)
    {
        $this->setDecimals($decimals);

        parent::__construct($normalizer);
    }

    /**
     * @param null|int $decimals
     *
     * @return NumberNormalizer
     */
    public function setDecimals($decimals)
    {
        $this->decimals = $decimals;

        return $this;
    }

    /**
     * @return null|int
     */
    public function getDecimals()
    {
        return $this->decimals;
    }

    protected function getNormalizedValue($value)
    {
        $numberValue = is_numeric($value) ? trim($value) + 0 : 0;

        if ($this->getDecimals() !== null) {
            $numberValue = round($numberValue, $this->getDecimals());
        }

        return $numberValue;
    }
}

<?php

namespace Palmtree\Csv\Normalizer;

/**
 * NumberNormalizer converts numeric strings to integers and floats.
 */
class NumberNormalizer extends AbstractNormalizer
{
    protected $decimals;

    /**
     * NumberNormalizer constructor.
     *
     * @param null|NormalizerInterface $normalizer
     * @param null|int                 $decimals
     */
    public function __construct($normalizer = null, $decimals = null)
    {
        $this->setDecimals($decimals);

        parent::__construct($normalizer);
    }

    /**
     * @param null|int $decimals
     *
     * @return NumberNormalizer
     */
    public function setDecimals($decimals)
    {
        $this->decimals = $decimals;

        return $this;
    }

    /**
     * @return null|int
     */
    public function getDecimals()
    {
        return $this->decimals;
    }

    protected function getNormalizedValue($value)
    {
        if (!is_numeric($value)) {
            return 0;
        }

        $numberValue = trim($value) + 0;

        if ($this->getDecimals() !== null) {
            $numberValue = round($numberValue, $this->getDecimals());
        }

        return $numberValue;
    }
}

Check string is_numeric to stop PHP 7 error


<?
class DependencyTexts extends Dependency
{
	public function __construct(){
		$this->addPackage("Db");
		$this->addPlugin("Host", "Host");
		$this->addPlugin("Language", "HostLanguage");
	}
}
?>

<?
class DependencyTexts extends Dependency
{
	public function __construct(){
		$this->addPackage("Db");
		$this->addPackage("Filter");
		$this->addPlugin("Host", "Host");
		$this->addPlugin("Language", "HostLanguage");
	}
}
?>

Add dependency on Filter to texts module


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

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

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

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

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

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

Add Email Validation for Subscribtions

Add Email Validation for Subscribtions


<?php if ( ! defined('BASEPATH')) exit('Invalid file request.');

/**
 * OmniLog module tests.
 *
 * @author        Stephen Lewis <stephen@experienceinternet.co.uk>
 * @copyright     Experience Internet
 * @package       Omnilog
 */

require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) .'/../models/omnilog_model.php';

class Test_omnilog extends Testee_unit_test_case {

    private $_model;
    private $_subject;

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function setUp()
    {
        parent::setUp();

        Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
        $this->_ee->omnilog_model = $this->_get_mock('model');
        $this->_model   = $this->_ee->omnilog_model;
        $this->_subject = new Omnilog();
    }

}

/* End of file      : test.mod_omnilog.php */
/* File location    : third_party/omnilog/tests/test.mod_omnilog.php */

<?php if ( ! defined('BASEPATH')) exit('Invalid file request.');

/**
 * OmniLog module tests.
 *
 * @author        Stephen Lewis <stephen@experienceinternet.co.uk>
 * @copyright     Experience Internet
 * @package       Omnilog
 */

require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) .'/../models/omnilog_model.php';

class Test_omnilog extends Testee_unit_test_case {

    private $_model;
    private $_subject;

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function setUp()
    {
        parent::setUp();

        Mock::generate('Omnilog_model', get_class($this) .'_mock_model');

        $this->_ee->omnilog_model = $this->_get_mock('model');
        $this->_model   = $this->_ee->omnilog_model;
        $this->_subject = new Omnilog();
    }

}

/* End of file      : test.mod_omnilog.php */
/* File location    : third_party/omnilog/tests/test.mod_omnilog.php */

Use real model as basis for mock.

Use real model as basis for mock.


<?php

return [
    'database' => [
        'host' => 'localhost',
        'db_name' => 'test',
        'user' => 'root',
        'password' => ''
    ],
    'locale' => [
        'timezone' => 'Europe/Rome',
        'default_language' => 'en'
    ],
    'session' => [
        'id' => 'vela_id'
    ]
];

<?php
return [
    'database' => [
        'host' => 'localhost',
        'db_name' => 'test',
        'user' => 'root',
        'password' => ''
    ],
    'locale' => [
        'timezone' => 'Europe/Rome',
        'default_language' => 'en'
    ],
	'mailer' => [
		'system' => 'phpmail'
	],
    'session' => [
        'id' => 'vela_id'
    ]
];

Add mai configuration on filel

Add mai configuration on filel


<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class WizardController extends Controller
{
    public function getIndex()
    {
        return view('wizard');
    }

    public function getPricing()
    {
        return view('manager.pricing');
    }

    public function getTerms()
    {
        return view('manager.terms');
    }
}

<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;
use Redirect;

class WizardController extends Controller
{
    public function getIndex()
    {
        if (!Session::get('oldvisitor')) {
            Session::set('oldvisitor', true);
            return view('wizard');
        } else {
            return Redirect::route('user.businesses.list');
        }
    }

    public function getPricing()
    {
        return view('manager.pricing');
    }

    public function getTerms()
    {
        return view('manager.terms');
    }
}

Fix routing for first timers wizard

Fix routing for first timers wizard


<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * Creates the record if it does not exist and is a string
 *
 * @package    Jam
 * @category   Associations
 * @author     Ivan Kerin
 * @copyright  (c) 2013 Despark Ltd.
 * @license    http://www.opensource.org/licenses/isc-license.txt
 */
abstract class Kohana_Jam_Association_Autocreate extends Jam_Association_Belongsto {

	public function set(Jam_Validated $model, $value, $is_changed)
	{
		if ($is_changed AND $value AND is_string($value) AND ! is_numeric($value))
		{
			$value = Jam::find_or_create($this->foreign_model, array(
				':name_key' => $value
			));
		}

		return parent::set($model, $value, $is_changed);
	}
}

<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * Creates the record if it does not exist and is a string
 *
 * @package    Jam
 * @category   Associations
 * @author     Ivan Kerin
 * @copyright  (c) 2013 Despark Ltd.
 * @license    http://www.opensource.org/licenses/isc-license.txt
 */
abstract class Kohana_Jam_Association_Autocreate extends Jam_Association_Belongsto {

	public $default_fields;

	public function set(Jam_Validated $model, $value, $is_changed)
	{
		if ($is_changed AND $value AND is_string($value) AND ! is_numeric($value))
		{
			$value = Jam::find_or_create($this->foreign_model, array(
				':name_key' => $value
			));

			if ($default_fields)
			{
				$value->set($default_fields);
			}
		}

		return parent::set($model, $value, $is_changed);
	}
}

Add default_fields to auto create

Add default_fields to auto create


<?php

namespace Hub\Client\Model;

class SectionValue
{
    private $key;
    private $label;
    private $value;
    private $repeat;

    public function getKey()
    {
        return $this->key;
    }

    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    public function getLabel()
    {
        return $this->label;
    }

    public function setLabel($label)
    {
        $this->label = $label;
        return $this;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValue($value)
    {
        $this->value = $value;
        return $this;
    }

    public function getRepeat()
    {
        return $this->repeat;
    }

    public function setRepeat($repeat)
    {
        $this->repeat = $repeat;
        return $this;
    }
}

<?php

namespace Hub\Client\Model;

class SectionValue
{
    private $key;
    private $label;
    private $value;
    private $repeat;

    public function getKey()
    {
        return $this->key;
    }

    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    public function getLabel()
    {
        return $this->label;
    }

    public function setLabel($label)
    {
        $this->label = $label;
        return $this;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValue($value)
    {
        $this->value = $value;
        return $this;
    }

    public function getRepeat()
    {
        return $this->repeat;
    }

    public function setRepeat($repeat)
    {
        $this->repeat = $repeat;
        return $this;
    }

    protected function isStamp()
    {
        if (!is_numeric($this->value)) {
            return false;
        }
        if (strpos(strtolower($this->label), 'datum')!== false) {
            return true;
        }
        return false;
    }

    public function presentValue()
    {
        $value = $this->getValue();
        $value = nl2br($value);
        if ($this->isStamp()) {
            $value = date('d-m-Y', $value);
        }
        return $value;
    }
}

Add $sectionValue->presentValue() for date formatting


<?php

namespace Bolt\Storage\Database;

use Bolt\Events\FailedConnectionEvent;
use Doctrine\DBAL\DBALException;

/**
 * Extension of DBAL's Connection class to allow catching of database connection
 * exceptions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 * @author Carson Full <carsonfull@gmail.com>
 */
class MasterSlaveConnection extends \Doctrine\DBAL\Connections\MasterSlaveConnection
{
    protected $_queryCacheProfile;

    /**
     * {@inheritdoc}
     */
    public function connect($connectionName = null)
    {
        try {
            return parent::connect($connectionName);
        } catch (DBALException $e) {
            if ($this->_eventManager->hasListeners('failConnect')) {
                $eventArgs = new FailedConnectionEvent($this, $e);
                $this->_eventManager->dispatchEvent('failConnect', $eventArgs);
            }
        }
    }

    /**
     * Sets an optional Query Cache handler on the connection class
     *
     * @param QueryCacheProfile $profile
     */
    public function setQueryCacheProfile(QueryCacheProfile $profile)
    {
        $this->_queryCacheProfile = $profile;
    }
}

<?php

namespace Bolt\Storage\Database;

use Bolt\Events\FailedConnectionEvent;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\DBALException;

/**
 * Extension of DBAL's Connection class to allow catching of database connection
 * exceptions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 * @author Carson Full <carsonfull@gmail.com>
 */
class MasterSlaveConnection extends \Doctrine\DBAL\Connections\MasterSlaveConnection
{
    protected $_queryCacheProfile;

    /**
     * {@inheritdoc}
     */
    public function connect($connectionName = null)
    {
        try {
            return parent::connect($connectionName);
        } catch (DBALException $e) {
            if ($this->_eventManager->hasListeners('failConnect')) {
                $eventArgs = new FailedConnectionEvent($this, $e);
                $this->_eventManager->dispatchEvent('failConnect', $eventArgs);
            }
        }
    }

    /**
     * Sets an optional Query Cache handler on the connection class
     *
     * @param QueryCacheProfile $profile
     */
    public function setQueryCacheProfile(QueryCacheProfile $profile)
    {
        $this->_queryCacheProfile = $profile;
    }
}

Add missing use for \Doctrine\DBAL\Cache\QueryCacheProfile


<?php
/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/

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

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simply call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have whipped up for them.
|
*/

$response = $app->make('Illuminate\Contracts\Http\Kernel')->handle(
	Illuminate\Http\Request::capture()
);

$response->send();

<?php
/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/

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

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simply call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have whipped up for them.
|
*/

$kernel = $app->make('Illuminate\Contracts\Http\Kernel');

$response = $kernel->handle(
	$request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Terminate the request after sending.

Terminate the request after sending.


<?php

class HttpClient
{
	public $status;

	public $response;

	public function get($url)
	{
		$this->response = @file_get_contents($url);

		if (isset($http_response_header))
		{
			$this->parseResponseHeader($http_response_header);
			return TRUE;
		}
		else
		{
			$this->response = NULL;
			return FALSE;
		}
	}

	private function parseResponseHeader($header)
	{
		// HTTP/1.1 200 OK
		$pattern = '#HTTP/\d\.\d (\d{3})#';

		// Clear fields
		$this->status = NULL;

		foreach($header as $entry)
		{
			$match = preg_match($pattern, $entry, $matches);

			if ($match == 1)
			{
				$this->status = (int)$matches[1];
				break;
			}
		}
	}
}

<?php

class HttpClient
{
	public $status;

	public $response;

	public function get($url)
	{
		$this->status = NULL;
		$this->response = @file_get_contents($url);

		if (isset($http_response_header))
		{
			$this->parseResponseHeader($http_response_header);
			return TRUE;
		}
		else
		{
			$this->response = NULL;
			return FALSE;
		}
	}

	private function parseResponseHeader($header)
	{
		// HTTP/1.1 200 OK
		$pattern = '#HTTP/\d\.\d (\d{3})#';

		// Clear fields
		$this->status = NULL;

		foreach($header as $entry)
		{
			$match = preg_match($pattern, $entry, $matches);

			if ($match == 1)
			{
				$this->status = (int)$matches[1];
				break;
			}
		}
	}
}

Clear status field on every request

Clear status field on every request


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

/**
 * Queried post.
 *
 * @global WP_Post $post
 */
global $post;

// Populate the $post without calling the_post() to prevent entering The Loop. This ensures that templates which
// contain The Loop will still loop over the posts. Otherwise, if a template contains The Loop then calling the_post()
// here will advance the WP_Query::$current_post to the next_post. See WP_Query::the_post().
$post = get_queried_object(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
setup_postdata( $post );

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

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

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

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

/**
 * Queried post.
 *
 * @global WP_Post $post
 */
global $post;

// Populate the $post without calling the_post() to prevent entering The Loop. This ensures that templates which
// contain The Loop will still loop over the posts. Otherwise, if a template contains The Loop then calling the_post()
// here will advance the WP_Query::$current_post to the next_post. See WP_Query::the_post().
$post = get_queried_object(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
setup_postdata( $post );

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

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

// Support and load Core block styles.
current_theme_supports( 'wp-block-styles' );
add_action(
	'amp_post_template_head',
	static function () {
		global $wp_styles;
		wp_common_block_scripts_and_styles();
		$wp_styles->do_items();
	}
);

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

Load block styles via amp_post_template_head action


©2014 Bobby Cahill

{{-- Include libraries from CDN if live, else use local files --}}
@if ($app->env == 'live')

@else

@endif

©2014-<?php echo date("Y"); ?> Bobby Cahill

{{-- Include libraries from CDN if live, else use local files --}}
@if ($app->env == 'live')

@else

@endif

Add current year to page footer

Add current year to page footer


<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>@yield('title')</title>
  {{ HTML::style('css/cnq.css') }}

  @yield('head')

    @if (Session::has('msg'))

      {{ Session::get('msg') }}

    @endif
    @if (Session::has('error'))

      @foreach (Session::get('error')->all() as $err)
      {{ $err }}

      @endforeach

    @endif

    @yield('content')

  {{ HTML::script('js/cnq.js') }}

Add jQuery load to master template

Add jQuery load to master template


<?php
/**
 * Template Name: Solutions
 */

$data         = Timber::get_context();
$data['post'] = new TimberPost();
Timber::render('page.twig', $data);

<?php
/**
 * Template Name: Solutions
 */

$data                 = Timber::get_context();
$data['post']         = new TimberPost();
$data['header_img']   = get_field('acf_header_image');
$data['solutions']    = Timber::get_posts(array(
  'post_type' => 'solution',
  'orderby'   => 'menu_order',
  'order'     => 'ASC',
  'nopaging'  => true
));

Timber::render('tmpl_solutions.twig', $data);

Add header image & solutions query data

Add header image & solutions query data


<?php
    /**
     * @author Manuel Thalmann <m@nuth.ch>
     * @license Apache-2.0
     */
    namespace System\Web\Forms;
    use System\Object;
    use System\Web\Forms\Rendering\IRenderable;
    {
        abstract class Control extends Object implements IRenderable
        {
            /**
             * Initializes a new instance of the control-class.
             */
            public function Control()
            {
            }

            /**
             * Gets or sets the identifier of the control.
             *
             * @var string
             */
            public $Name = '';

            /**
             * Gets or sets the Text of the control.
             *
             * @var string
             */
            public $Text = '';

            /**
             * Gets or sets a value indicating whether the control can respond to user interaction.
             *
             * @var boolean
             */
            public $Enabled = true;

            /**
             * Gets or sets a value indicating whether the control and all its child controls are displayed.
             *
             * @var boolean
             */
            public $Visible = true;
        }
    }
?>

<?php
    /**
     * @author Manuel Thalmann <m@nuth.ch>
     * @license Apache-2.0
     */
    namespace System\Web\Forms;
    use System\Object;
    use System\Web\Forms\Rendering\IRenderable;
    {
        abstract class Control extends Object implements IRenderable
        {
            /**
             * Initializes a new instance of the control-class.
             */
            public function Control()
            {
            }

            /**
             * Gets or sets the identifier of the control.
             *
             * @var string
             */
            public $Name;

            /**
             * Gets or sets the Text of the control.
             *
             * @var string
             */
            public $Text;

            /**
             * Gets or sets a value indicating whether the control can respond to user interaction.
             *
             * @var boolean
             */
            public $Enabled = true;

            /**
             * Gets or sets a value indicating whether the control and all its child controls are displayed.
             *
             * @var boolean
             */
            public $Visible = true;
        }
    }
?>

Remove default name and text of the control class


<?php

namespace Guzzle\Service\Mediawiki;

use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Common\Collection;
use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

class MediawikiApiClient extends Client
{
    /**
     * Factory method to create a new MediawikiApiClient
     *
     * @param array|Collection $config Configuration data. Array keys:
     *    base_url - Base URL of web service
     *
     * @return MediawikiApiClient
     */
    public static function factory($config = array())
    {
        $default = array(
            'base_url' => "https://en.wikipedia.org/w/api.php",
        );

        $required = array('base_url');
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self($config->get('base_url'));

        $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
        $client->addSubscriber($cookiePlugin);

        $client->setConfig($config);
        $client->setUserAgent('birke-mediawiki-api-client');
        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }
}

<?php

namespace Guzzle\Service\Mediawiki;

use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Common\Collection;
use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

/**
 * @method array help
 * @method array parse
 * @method array login
 * @method array logout
 * @method array tokens
 * @method array upload
 */
class MediawikiApiClient extends Client
{
    /**
     * Factory method to create a new MediawikiApiClient
     *
     * @param array|Collection $config Configuration data. Array keys:
     *    base_url - Base URL of web service
     *
     * @return MediawikiApiClient
     */
    public static function factory($config = array())
    {
        $default = array(
            'base_url' => "https://en.wikipedia.org/w/api.php",
        );

        $required = array('base_url');
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self($config->get('base_url'));

        $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
        $client->addSubscriber($cookiePlugin);

        $client->setConfig($config);
        $client->setUserAgent('birke-mediawiki-api-client');
        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }
}

Add @method phpdoc for Client

Add @method phpdoc for Client


<?php

CroogoRouter::connect('/admin/dashboards/', array(
	'admin' => true,
	'plugin' => 'dashboards',
	'controller' => 'dashboards_dashboards',
	'action' => 'dashboard',
));

CroogoRouter::connect('/admin/dashboards/:action/*', array(
	'admin' => true,
	'plugin' => 'dashboards',
	'controller' => 'dashboards_dashboards',
), array(
	'action' => '[a-zA-Z0-9_-]+',
));

<?php

CroogoRouter::connect('/admin/dashboards', array(
	'admin' => true,
	'plugin' => 'dashboards',
	'controller' => 'dashboards_dashboards',
	'action' => 'dashboard',
));

CroogoRouter::connect('/admin/dashboards/:action/*', array(
	'admin' => true,
	'plugin' => 'dashboards',
	'controller' => 'dashboards_dashboards',
), array(
	'action' => '[a-zA-Z0-9_-]+',
));

Fix: Remove extra '/' character in dashboard route


<?php

namespace Boomgo\Tests\Units;

use mageekguy\atoum\test as AtoumTest;

abstract class Test extends AtoumTest
{
    public function __construct(score $score = null, locale $locale = null, adapter $adapter = null)
    {
        $this->setTestNamespace('\\Tests\\Units\\');
        parent::__construct($score, $locale, $adapter);
    }
}

<?php

/**
 * This file is part of the Boomgo PHP ODM for MongoDB.
 *
 * http://boomgo.org
 * https://github.com/Retentio/Boomgo
 *
 * (c) Ludovic Fleury <ludo.fleury@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Boomgo\Tests\Units;

use mageekguy\atoum\test as AtoumTest,
    mageekguy\atoum\factory;

/**
 * Rewrite default namespace for atoum
 *
 * @author David Guyon <dguyon@gmail.com>
 */
abstract class Test extends AtoumTest
{
    public function __construct(factory $factory = null)
    {
        $this->setTestNamespace('\\Tests\\Units\\');
        parent::__construct($factory);
    }
}

Update default unit test class with atoum refactoring


<?php

use Arvici\Heart\Config\Configuration;
use Arvici\Component\View\View;

/**
 * Template Configuration
 */
Configuration::define('database', function() {
    return [

        /**
         * The default fetch type to use.
         */
        'fetchType' => \Arvici\Heart\Database\Database::FETCH_ASSOC,

        /**
         * Database Connection names and configuration values.
         *
         * 'default' is used when no connection name is provided, or using SweetORM.
         */
        'connections' => [
            'default' => [
                'driver'        => 'MySQL',

                'host'          =>   'localhost',
                'username'      => 'root',
                'password'      => '',
                'port'          => 3306,
                'database'      => 'arvici_test'
            ],

            'incomplete' => [
                'driver'        => 'MySQL',
            ],

            'nodriver' => [

            ]
        ],
    ];
});

Remove some weird space in the test configuration.


<?php

class Crime extends Module {

    public $url = "https://data.bathhacked.org/resource/e46f-mhfs.json";

    function getData() {
        $lat = $this->point->lat;
        $long = $this->point->long;
        $this->url .= '?$where=month>%272014-08-01%27%20AND%20month<%272014-11-01%27%20AND%20within_circle(location,'.$long.','.$lat.',1000)';
        return json_decode($this->fetch(), true);
    }
}

?>

<?php

class Crime extends Module {

    public $url = "https://data.bathhacked.org/resource/e46f-mhfs.json";

    function getData() {
        $lat = $this->point->lat;
        $long = $this->point->long;
        $startDate = date('Y-m-d', time()-4*30*24*60*60);
        $endDate = date('Y-m-d');

        $this->url .= '?$where=month>%27'.$startDate.'%27%20AND%20month<%27'.$endDate.'%27%20AND%20within_circle(location,'.$long.','.$lat.',1000)&$order=month%20DESC';
        return json_decode($this->fetch(), true);
    }
}

?>

Make crimes date dynamic and sort by date DESC.


<?php

namespace Diarmuidie\NiceID\Tests\Utilities;

use Diarmuidie\NiceID\Utilities;

/**
 * Class NiceIDTest
 * @package Diarmuidie\NiceID\Tests
 */
class FisherYatesTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array Test unshuffled array
     */
    private $unShuffledArray = ['a','b','c','d','e','f'];

    /**
     * @var array Test shuffled array
     */
    private $shuffledtestArray = ['a','c','e','f','b','d'];

    /**
     * @var string Test shuffle secret
     */
    private $testSecret = 'My Test Secret';

    /**
     * Test shuffling
     */
    public function testShuffleArray()
    {

        $shuffled = Utilities\FisherYates::shuffle($this->unShuffledArray, $this->testSecret);

        $this->assertEquals($shuffled, $this->shuffledtestArray);

    }

    /**
     * Test unshuffling
     */
    public function testUnShuffleArray()
    {

        $unshuffled = Utilities\FisherYates::unshuffle($this->shuffledtestArray, $this->testSecret);

        $this->assertEquals($unshuffled, $this->unShuffledArray);

    }
}

<?php

namespace Diarmuidie\NiceID\Tests\Utilities;

use Diarmuidie\NiceID\Utilities;

/**
 * Class NiceIDTest
 * @package Diarmuidie\NiceID\Tests
 */
class FisherYatesTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array Test unshuffled array
     */
    private $unShuffledArray = array('a','b','c','d','e','f');

    /**
     * @var array Test shuffled array
     */
    private $shuffledtestArray = array('a','c','e','f','b','d');

    /**
     * @var string Test shuffle secret
     */
    private $testSecret = 'My Test Secret';

    /**
     * Test shuffling
     */
    public function testShuffleArray()
    {

        $shuffled = Utilities\FisherYates::shuffle($this->unShuffledArray, $this->testSecret);

        $this->assertEquals($shuffled, $this->shuffledtestArray);

    }

    /**
     * Test unshuffling
     */
    public function testUnShuffleArray()
    {

        $unshuffled = Utilities\FisherYates::unshuffle($this->shuffledtestArray, $this->testSecret);

        $this->assertEquals($unshuffled, $this->unShuffledArray);

    }
}

Use old array notation for PHP < 5.4

Use old array notation for PHP <  5.4


<?php
/**
 * Plugin Name: E2E Assets
 * Description: Enqueues assets needed for E2E tests.
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

add_action(
	'init',
	function () {
		if ( ! defined( 'GOOGLESITEKIT_PLUGIN_MAIN_FILE' ) ) {
			return;
		}

		wp_enqueue_script(
			'googlesitekit-e2e-utilities',
			plugins_url( 'dist/assets/js/e2e-utilities.js', GOOGLESITEKIT_PLUGIN_MAIN_FILE ),
			array( 'googlesitekit-apifetch-data' ),
			md5_file( plugin_dir_path( GOOGLESITEKIT_PLUGIN_MAIN_FILE ) . 'dist/assets/js/e2e-utilities.js' ),
			true
		);
	}
);

<?php
/**
 * Plugin Name: E2E Assets
 * Description: Enqueues assets needed for E2E tests.
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

use Google\Site_Kit\Core\Assets\Script;

add_filter(
	'googlesitekit_assets',
	function ( $assets ) {
		$assets[] = new Script(
			'googlesitekit-e2e-utilities',
			array(
				'src'          => plugins_url( 'dist/assets/js/e2e-utilities.js', GOOGLESITEKIT_PLUGIN_MAIN_FILE ),
				'dependencies' => array( 'googlesitekit-apifetch-data' ),
				'version'      => md5_file( plugin_dir_path( GOOGLESITEKIT_PLUGIN_MAIN_FILE ) . 'dist/assets/js/e2e-utilities.js' ),
			)
		);

		return $assets;
	}
);
// Enqueue E2E Utilities globally `wp_print_scripts` is called on admin and front.
// If asset is not registered enqueuing is a no-op.
add_action(
	'wp_print_scripts',
	function () {
		wp_enqueue_script( 'googlesitekit-e2e-utilities' );
	}
);

Update E2E assets mu-plugin to register script via new filter.

This is to grant AMP-devmode compatibility to this asset which Site Kit does automatically for all of its assets.


<?php

/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::group(['before' => 'Sentinel\auth'], function()
{
	Route::resource('projects', 'ProjectsController');
	Route::resource('tickets', 'TicketsController');
	Route::resource('invoices', 'InvoicesController');
	Route::post('tickets/{id}/reply', 'TicketsController@reply');
	Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
	# Override Sentinel's Default user routes with our own filter requirement
	Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
	Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});

Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
	Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
	Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});

<?php

/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::group(['before' => 'Sentinel\auth'], function()
{
	Route::resource('projects', 'ProjectsController');
	Route::resource('tickets', 'TicketsController');
	Route::resource('invoices', 'InvoicesController');
	Route::get('/tickets/status/{status}', ['as' => 'ticket.by.status', 'uses' => 'TicketsController@filterByStatus']);
	Route::post('tickets/{id}/reply', 'TicketsController@reply');
	Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
	# Override Sentinel's Default user routes with our own filter requirement
	Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
	Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});

Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
	Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
	Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});

Add route to handle ticket filtering by status


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', function()
{
	return View::make('hello');
});

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', function()
{
//	return View::make('hello');
	$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
	$getfield = '?screen_name=joepferguson';
	$requestMethod = 'GET';
	$settings = array(
		'oauth_access_token' => $_ENV['oauth_access_token'],
		'oauth_access_token_secret' => $_ENV['oauth_access_token_secret'],
		'consumer_key' => $_ENV['consumer_key'],
		'consumer_secret' => $_ENV['consumer_secret'],
	);
	$twitter = new TwitterAPIExchange($settings);
	$response = $twitter->setGetfield($getfield)
	                    ->buildOauth($url, $requestMethod)
	                    ->performRequest();

	var_dump(json_decode($response));
});

Add basic example of using twitter api

Add basic example of using twitter api


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::group(['middleware' => ['unauth.user']], function(){
    Route::get('/login', 'User\LoginController@showLoginPage');
    Route::post('/login', 'User\LoginController@handleLoginRequest');
});

Route::group(['middleware' => ['auth.user']], function(){
    Route::get('/', 'User\UIController@showIndexPage');

    Route::get('/logout', 'User\LoginController@showLogoutPage');
    Route::post('/logout', 'User\LoginController@handleLogout');
});

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::group(['middleware' => ['unauth.user']], function(){
    Route::get('/login', 'User\LoginController@showLoginPage');
    Route::post('/login', 'User\LoginController@handleLoginRequest');
});

Route::group(['middleware' => ['auth.user']], function(){
    Route::get('/', 'User\UIController@showIndexPage');

    Route::get('/logout', 'User\LoginController@showLogoutPage');
    Route::post('/logout', 'User\LoginController@handleLogout');

    Route::get('/author', 'User\AuthorController@showAuthorPage');
    Route::post('/author', 'User\AuthorController@handleAuthorization');
});

Create route for authorize student to leave


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');

Route::group(['middleware' => 'auth', 'admin'], function () {

	Route::get('/backend', 'BackendController@index');

});

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');

Route::group(['middleware' => ['auth', 'admin']], function () {

	Route::get('/backend', 'BackendController@index');

});

Fix route group for admin and auth verification.


<?php
use Migrations\AbstractMigration;

class PrefixMenus extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('menus')
            ->rename('qobo_menus');
    }
}

<?php
use Migrations\AbstractMigration;

class PrefixMenus extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('menus')
            ->rename('qobo_menus')
            ->update();
    }
}

Fix compatibility isssues with Phinx 0.11


<?php

/**
 * @author:  Gabriel BONDAZ <gabriel.bondaz@idci-consulting.fr>
 * @license: MIT
 */

namespace IDCI\Bundle\ExtraFormBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class JsonToArrayTransformer implements DataTransformerInterface
{

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null === $value) {
            return "";
        }

        return json_encode($value);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        return json_decode($value, true);
    }
}

<?php

/**
 * @author:  Gabriel BONDAZ <gabriel.bondaz@idci-consulting.fr>
 * @license: MIT
 */

namespace IDCI\Bundle\ExtraFormBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class JsonToArrayTransformer implements DataTransformerInterface
{

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null === $value) {
            return "";
        }

        if (is_array($value)) {
           return json_encode($value);
        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        $decoded = json_decode($value, true);

        return null === $decoded ? $value : $decoded;
    }
}

Improve json to array transformer

Improve json to array transformer


<?php

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

class AddEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('event_id');
            $table->string('time');
            $table->string('status');
            $table->text('event_url');
            $table->timestamps();
        });
    }

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

<?php

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

class AddEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('event_id');
            $table->string('time');
            $table->string('status');
            $table->text('event_url');
            $table->text('created');
            $table->timestamps();
        });
    }

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

Add created field to event migration

Add created field to event migration


<?php

require_once("boot.php");

function cronhooks_run(&$argv, &$argc){
	global $a, $db;

	if(is_null($a)) {
		$a = new App;
	}

	if(is_null($db)) {
	    @include(".htconfig.php");
    	require_once("include/dba.php");
	    $db = new dba($db_host, $db_user, $db_pass, $db_data);
    	unset($db_host, $db_user, $db_pass, $db_data);
  	};

	require_once('include/session.php');
	require_once('include/datetime.php');
	require_once('include/pidfile.php');

	load_config('config');
	load_config('system');

	$lockpath = get_config('system','lockpath');
	if ($lockpath != '') {
		$pidfile = new pidfile($lockpath, 'cron.lck');
		if($pidfile->is_already_running()) {
			logger("cronhooks: Already running");
			exit;
		}
	}

	$a->set_baseurl(get_config('system','url'));

	load_hooks();

	logger('cronhooks: start');
echo("@@@ cronhooks start\n");

	$d = datetime_convert();

	call_hooks('cron', $d);

	return;
}

if (array_search(__file__,get_included_files())===0){
  cronhooks_run($argv,$argc);
  killme();
}

<?php

require_once("boot.php");

function cronhooks_run(&$argv, &$argc){
	global $a, $db;

	if(is_null($a)) {
		$a = new App;
	}

	if(is_null($db)) {
	    @include(".htconfig.php");
    	require_once("include/dba.php");
	    $db = new dba($db_host, $db_user, $db_pass, $db_data);
    	unset($db_host, $db_user, $db_pass, $db_data);
  	};

	require_once('include/session.php');
	require_once('include/datetime.php');
	require_once('include/pidfile.php');

	load_config('config');
	load_config('system');

	$lockpath = get_config('system','lockpath');
	if ($lockpath != '') {
		$pidfile = new pidfile($lockpath, 'cron.lck');
		if($pidfile->is_already_running()) {
			logger("cronhooks: Already running");
			exit;
		}
	}

	$a->set_baseurl(get_config('system','url'));

	load_hooks();

	logger('cronhooks: start');

	$d = datetime_convert();

	call_hooks('cron', $d);

	return;
}

if (array_search(__file__,get_included_files())===0){
  cronhooks_run($argv,$argc);
  killme();
}

Remove debug line added by mistake

Remove debug line added by mistake


Update for Apr coop data

Update for Apr coop data


<?php

namespace FOQ\ElasticaBundle;

use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends Elastica_Client
{
    protected $logger;

    public function setLogger(ElasticaLogger $logger)
    {
        $this->logger = $logger;
    }

    public function request($path, $method, $data = array())
    {
        $start = microtime(true);
        //this is ghetto, but i couldnt figure out another way of making our site continue to behave normally even if ES was not running.
        //Any improvements on this welcome. Perhaps another parameter that allows you to control if you want to ignore exceptions about ES not running
        try {
            $response = parent::request($path, $method, $data);
        } catch(\Exception $e) {
            //again, ghetto, but couldnt figure out how to return a default empty Elastica_Response
            return new \Elastica_Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
        }

        if (null !== $this->logger) {
            $time = microtime(true) - $start;
            $this->logger->logQuery($path, $method, $data, $time);
        }

        return $response;
    }
}

<?php

namespace FOQ\ElasticaBundle;

use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends Elastica_Client
{
    protected $logger;

    public function setLogger(ElasticaLogger $logger)
    {
        $this->logger = $logger;
    }

    public function request($path, $method, $data = array())
    {
        $start = microtime(true);
        $response = parent::request($path, $method, $data);

        if (null !== $this->logger) {
            $time = microtime(true) - $start;
            $this->logger->logQuery($path, $method, $data, $time);
        }

        return $response;
    }
}

Revert "Hide exceptions if elasticsearch is not running. This needs some fixing and cleaning up by someone smarter than myself."

This reverts commit eb1900265fb3f077cf104c0944d8832a8d48012e and fixes #45.


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

use professionalweb\payment\contracts\PayService;

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

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param string $paymentId
     * @param float  $amount
     * @param string $description
     * @param string $currency
     * @param array  $extraParams
     *
     * @return bool
     */
    public function initPayment(string $token, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;

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

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

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

use professionalweb\payment\contracts\PayService;

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

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param string $orderId
     * @param string $paymentId
     * @param float  $amount
     * @param string $description
     * @param string $currency
     * @param array  $extraParams
     *
     * @return bool
     */
    public function initPayment(string $token, string $orderId, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;

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

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

Add orderId to initPayment method

Add orderId to initPayment method


<?php

namespace PhpAmqpLib\Message;

use PhpAmqpLib\Wire\GenericContent;

/**
 * A Message for use with the Channnel.basic_* methods.
 */
class AMQPMessage extends GenericContent
{
    protected static $PROPERTIES = array(
        "content_type" => "shortstr",
        "content_encoding" => "shortstr",
        "application_headers" => "table",
        "delivery_mode" => "octet",
        "priority" => "octet",
        "correlation_id" => "shortstr",
        "reply_to" => "shortstr",
        "expiration" => "shortstr",
        "message_id" => "shortstr",
        "timestamp" => "timestamp",
        "type" => "shortstr",
        "user_id" => "shortstr",
        "app_id" => "shortstr",
        "cluster_id" => "shortstr"
    );

    public function __construct($body = '', $properties = null)
    {
        $this->body = $body;

        parent::__construct($properties, static::$PROPERTIES);
    }
}

<?php

namespace PhpAmqpLib\Message;

use PhpAmqpLib\Wire\GenericContent;

/**
 * A Message for use with the Channnel.basic_* methods.
 */
class AMQPMessage extends GenericContent
{
    public $body;

    protected static $PROPERTIES = array(
        "content_type" => "shortstr",
        "content_encoding" => "shortstr",
        "application_headers" => "table",
        "delivery_mode" => "octet",
        "priority" => "octet",
        "correlation_id" => "shortstr",
        "reply_to" => "shortstr",
        "expiration" => "shortstr",
        "message_id" => "shortstr",
        "timestamp" => "timestamp",
        "type" => "shortstr",
        "user_id" => "shortstr",
        "app_id" => "shortstr",
        "cluster_id" => "shortstr"
    );

    public function __construct($body = '', $properties = null)
    {
        $this->body = $body;

        parent::__construct($properties, static::$PROPERTIES);
    }
}

Add body property to message, previously undeclared


<?php namespace Abhijitghogre\LaravelDbClearCommand\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class RefreshDatabase extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'db:clear';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Drop all database tables and rerun the migrations.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $tables = [];

        DB::statement('SET FOREIGN_KEY_CHECKS=0');

        foreach (DB::select('SHOW TABLES') as $k => $v) {
            $tables[] = array_values((array)$v)[0];
        }

        foreach ($tables as $table) {
            Schema::drop($table);
            echo "Table " . $table . " has been dropped." . PHP_EOL;
        }

        $this->call('migrate');

    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [

        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [

        ];
    }

}

<?php
namespace Abhijitghogre\LaravelDbClearCommand\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class RefreshDatabase extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'db:clear {--seed : Seed the database after clearing}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Drop all database tables and rerun the migrations.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $tables = [];

        DB::statement('SET FOREIGN_KEY_CHECKS=0');

        foreach (DB::select('SHOW TABLES') as $k => $v) {
            $tables[] = array_values((array) $v)[0];
        }

        foreach ($tables as $table) {
            Schema::drop($table);
            echo "Table " . $table . " has been dropped." . PHP_EOL;
        }

        $this->call('migrate');

        if ($this->option('seed')) {
            $this->call('db:seed');
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [

        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [

        ];
    }

}

Add --seed option for running seeds

Add --seed option for running seeds


<?php
declare(strict_types=1);

namespace PerFi\PerFiBundle\Form;

use PerFi\Domain\Account\AccountTypeView;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class CreateAccountType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('type', ChoiceType::class, [
                'required' => true,
                'choices' => AccountTypeView::getTypes(),
            ])
            ->add('title', TextType::class, [
                'required' => true,
            ]);
    }
}

<?php
declare(strict_types=1);

namespace PerFi\PerFiBundle\Form;

use PerFi\Domain\Account\AccountType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class CreateAccountType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('type', ChoiceType::class, [
                'required' => true,
                'choices' => [
                    'Asset' => (string) AccountType::fromString('asset'),
                    'Expense' => (string) AccountType::fromString('expense'),
                    'Income' => (string) AccountType::fromString('income'),
                ],
            ])
            ->add('title', TextType::class, [
                'required' => true,
            ]);
    }
}

Set the account types as choices

Set the account types as choices

Having a domain object that returns all the types
with labels feels weird. I think this is better.


<?php

  $phar = new Phar('FS.phar',0,'FS.phar');

  $stub = "<?php
  Phar::mapPhar('FS.phar');
  include('phar://FS.phar/FS/Bootstrap.php');
  __HALT_COMPILER();";

  $phar->setStub($stub);

  $phar->buildFromDirectory(dirname(__FILE__) . '/src');

?>

<?php

  $phar = new Phar('lib/FS.phar',0,'FS.phar');

  $stub = "<?php
  Phar::mapPhar('FS.phar');
  include('phar://FS.phar/FS/Bootstrap.php');
  __HALT_COMPILER();";

  $phar->setStub($stub);

  $phar->buildFromDirectory(dirname(__FILE__) . '/src');

?>

Move build location of phar

Move build location of phar


<?php

namespace Tapestry\Providers;

use Tapestry\Tapestry;
use Tapestry\Console\Application;
use Tapestry\Console\Commands\InitCommand;
use Tapestry\Console\Commands\BuildCommand;
use Tapestry\Console\Commands\SelfUpdateCommand;
use League\Container\ServiceProvider\AbstractServiceProvider;

class CommandServiceProvider extends AbstractServiceProvider
{
    /**
     * @var array
     */
    protected $provides = [
        Application::class,
        InitCommand::class,
    ];

    /**
     * Use the register method to register items with the container via the
     * protected $this->container property or the `getContainer` method
     * from the ContainerAwareTrait.
     *
     * @return void
     */
    public function register()
    {
        $container = $this->getContainer();

        $container->add(InitCommand::class)
            ->withArguments([
                \Symfony\Component\Filesystem\Filesystem::class,
                \Symfony\Component\Finder\Finder::class,
            ]);

        $this->getContainer()->add(BuildCommand::class)
            ->withArguments([
                Tapestry::class,
                $this->getContainer()->get('Compile.Steps'),
            ]);

        $container->add(SelfUpdateCommand::class)
            ->withArguments([
                \Symfony\Component\Filesystem\Filesystem::class,
                \Symfony\Component\Finder\Finder::class,
            ]);

        $container->add(Application::class)
            ->withArguments([
                Tapestry::class,
                [
                    $container->get(InitCommand::class),
                    $container->get(BuildCommand::class),
                    $container->get(SelfUpdateCommand::class),
                ],
            ]);
    }
}

<?php

namespace Tapestry\Providers;

use Tapestry\Tapestry;
use Tapestry\Console\Application;
use Tapestry\Console\Commands\InitCommand;
use Tapestry\Console\Commands\BuildCommand;
use Tapestry\Console\Commands\SelfUpdateCommand;
use League\Container\ServiceProvider\AbstractServiceProvider;

class CommandServiceProvider extends AbstractServiceProvider
{
    /**
     * @var array
     */
    protected $provides = [
        Application::class,
        InitCommand::class,
    ];

    /**
     * Use the register method to register items with the container via the
     * protected $this->container property or the `getContainer` method
     * from the ContainerAwareTrait.
     *
     * @return void
     */
    public function register()
    {
        $container = $this->getContainer();

        $container->add(InitCommand::class)
            ->withArguments([
                \Symfony\Component\Filesystem\Filesystem::class,
                \Symfony\Component\Finder\Finder::class,
            ]);

        $this->getContainer()->add(BuildCommand::class)
            ->withArguments([
                Tapestry::class,
                $this->getContainer()->get('Compile.Steps'),
            ]);

        $container->add(SelfUpdateCommand::class)
            ->withArguments([
                \Symfony\Component\Filesystem\Filesystem::class,
                \Symfony\Component\Finder\Finder::class,
            ]);

        $container->share(Application::class)
            ->withArguments([
                Tapestry::class,
                [
                    $container->get(InitCommand::class),
                    $container->get(BuildCommand::class),
                    $container->get(SelfUpdateCommand::class),
                ],
            ]);
    }
}

:sparkles: Set Application as a static class in IoC


<?php
if (!$_SESSION)
{
echo <<<WARN

Alert!

Sorry, but your session has expired due to two hours of inactivity.

 Please log in again to get back to work.

WARN;
die;

}

?>

<?php
if (!$_SESSION)
{
echo <<<WARN

Alert!

Sorry, but your session has expired due to inactivty.

 Please log in again to get back to work.

WARN;
die;

}

?>

Change wording on error message.  It reflected a two-hour timeout which is not implimented.

git-svn-id: e691eac7f4e7c267eb8bf668e75dc601c2a71df8@593 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php

namespace TwwSaml\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class AcsController extends AbstractActionController
{

    public function indexAction()
    {
        $serviceLocator = $this->getServiceLocator();
        $config = $serviceLocator->get('Config');
        $auth = new \OneLogin_Saml2_Auth($config['tww-saml']['settings']);
        $auth->processResponse();

        $errors = $auth->getErrors();
        if (!empty($errors)) {
            print_r('<p>'.implode(', ', $errors).'</p>');
            exit();
        }

        if (!$auth->isAuthenticated()) {
            throw new \Exception('Authentication failed.');
        }

        $_SESSION['samlUserdata'] = $auth->getAttributes();
        if (isset($_POST['RelayState']) && \OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState']) {
            return $this->redirect()->toUrl($_POST['RelayState']);
        } else {
            return $this->redirect()->toRoute('home');
        }
    }

}

<?php

namespace TwwSaml\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class AcsController extends AbstractActionController
{

    public function indexAction()
    {
        $serviceLocator = $this->getServiceLocator();
        $config = $serviceLocator->get('Config');
        $auth = new \OneLogin_Saml2_Auth($config['tww-saml']['settings']);
        $auth->processResponse();

        $errors = $auth->getErrors();
        if (!empty($errors)) {
            print_r('<p>'.implode(', ', $errors).'</p>');
            exit();
        }

        if (!$auth->isAuthenticated()) {
            throw new \Exception('Authentication failed.');
        }

        $_SESSION['samlUserdata'] = $auth->getAttributes();
        if (isset($_POST['RelayState']) && (strlen($_POST['RelayState']) > 0) && (\OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState'])) {
            return $this->redirect()->toUrl($_POST['RelayState']);
        } else {
            return $this->redirect()->toRoute('home');
        }
    }

}

Check it's actually a URL\!

Check it's actually a URL\!


<?php

namespace PragmaRX\Support\Inflectors;

class Inflector {

	protected static $localizedInflectors = [
		'en' => 'PragmaRX\Support\Inflectors\En',
		'pt' => 'PragmaRX\Support\Inflectors\PtBr',
	];

	public static function plural($word)
	{
		$inflector = static::getInflector();

		return $inflector->plural($word);
	}

    public static function singular($word)
    {
	    $inflector = static::getInflector();

	    return $inflector->singular($word);
    }

	private static function getInflector()
	{
		$inflector = static::$localizedInflectors['en'];

		if (function_exists('app'))
		{
			$locale = app()->make('translator')->getLocale();

			foreach (static::$localizedInflectors as $lang => $class)
			{
				if (starts_with($locale, $lang))
				{
					$inflector = $class;
				}
			}

		}

		return new $inflector;
	}

}

<?php

namespace PragmaRX\Support\Inflectors;

class Inflector {

	protected static $localizedInflectors = [
		'en' => 'PragmaRX\Support\Inflectors\En',
		'pt' => 'PragmaRX\Support\Inflectors\PtBr',
	];

	public function inflect($word, $count)
	{
		if ($count > 1)
		{
			return $this->plural($word);
		}

		return $this->singular($word);
	}

	public static function plural($word)
	{
		$inflector = static::getInflector();

		return $inflector->plural($word);
	}

    public static function singular($word)
    {
	    $inflector = static::getInflector();

	    return $inflector->singular($word);
    }

	private static function getInflector()
	{
		$inflector = static::$localizedInflectors['en'];

		if (function_exists('app'))
		{
			$locale = app()->make('translator')->getLocale();

			foreach (static::$localizedInflectors as $lang => $class)
			{
				if (starts_with($locale, $lang))
				{
					$inflector = $class;
				}
			}

		}

		return new $inflector;
	}

}

Add a way to inflect by count

Add a way to inflect by count


<?php
/**
 * Created by PhpStorm.
 * User: daedeloth
 * Date: 30/11/14
 * Time: 18:49
 */

namespace Neuron\Collections;
use Neuron\Interfaces\Model;

/**
 * Class TokenizedCollection
 *
 * @package Neuron\Collections
 */
class ModelCollection
	extends Collection {

	private $map = array ();

	public function __construct ()
	{
		$this->on ('add', array ($this, 'onAdd'));
		$this->on ('set', array ($this, 'onAdd'));
		$this->on ('unset', array ($this, 'onUnset'));
	}

	protected function onAdd (Model $model, $offset)
	{
		$this->map[$model->getId ()] = $model;
	}

	protected function onUnset (Model $model = null, $offset = null)
	{
		if ($model)
			unset ($this->map[$model->getId ()]);
	}

	/**
	 * Return all ids.
	 * @return array
	 */
	public function getIds () {
		return array_keys ($this->map);
	}

	public function getFromId ($id)
	{
		if (isset ($this->map[$id]))
		{
			return $this->map[$id];
		}
		return null;
	}
}

<?php
/**
 * Created by PhpStorm.
 * User: daedeloth
 * Date: 30/11/14
 * Time: 18:49
 */

namespace Neuron\Collections;
use Neuron\Interfaces\Model;

/**
 * Class TokenizedCollection
 *
 * @package Neuron\Collections
 */
class ModelCollection
	extends Collection {

	private $map = array ();

	public function __construct ()
	{
		$this->on ('add', array ($this, 'onAdd'));
		$this->on ('set', array ($this, 'onAdd'));
		$this->on ('unset', array ($this, 'onUnset'));
	}

    /**
     * @param Model|null $model
     * @param null $offset
     */
	protected function onAdd (Model $model = null, $offset = null)
	{
		$this->map[$model->getId ()] = $model;
	}

    /**
     * @param Model|null $model
     * @param null $offset
     */
	protected function onUnset (Model $model = null, $offset = null)
	{
		if ($model)
			unset ($this->map[$model->getId ()]);
	}

	/**
	 * Return all ids.
	 * @return array
	 */
	public function getIds ()
    {
		return array_keys ($this->map);
	}

    /**
     * @param $id
     * @return mixed|null
     */
	public function getFromId ($id)
	{
		if (isset ($this->map[$id]))
		{
			return $this->map[$id];
		}
		return null;
	}
}

Allow null values in model collection.

Allow null values in model collection.


<?php

require_once 'recipe/common.php';

if($_SERVER['_'] == $_SERVER['PHP_SELF']) {
    \Deployer\set('deployer_exec', $_SERVER['_']);
} else {
    \Deployer\set('deployer_exec', $_SERVER['_'] . $_SERVER['PHP_SELF']);

}

// TODO - find more reliable way to set root of project
$data = debug_backtrace();
if (isset($data[3]) && isset($data[3]['file'])) {
    \Deployer\set('current_dir', dirname($data[3]['file']));
}

\SourceBroker\DeployerExtended\Utility\FileUtility::requireFilesFromDirectoryReqursively(__DIR__ . '/../deployer/');

<?php

// run only if called from deployer.phar context
if (function_exists('\Deployer\set')) {

    require_once 'recipe/common.php';

    if ($_SERVER['_'] == $_SERVER['PHP_SELF']) {
        \Deployer\set('deployer_exec', $_SERVER['_']);
    } else {
        \Deployer\set('deployer_exec', $_SERVER['_'] . $_SERVER['PHP_SELF']);
    }

// TODO - find more reliable way to set root of project
    $data = debug_backtrace();
    if (isset($data[3]) && isset($data[3]['file'])) {
        \Deployer\set('current_dir', dirname($data[3]['file']));
    }

    \SourceBroker\DeployerExtended\Utility\FileUtility::requireFilesFromDirectoryReqursively(__DIR__ . '/../deployer/');

}

[BUGFIX] Load deployer-extended only if running deployer