<?php

namespace Nectary\Models;

use Nectary\Data_Model;

/**
 * A Viewable model is one that can present itself so that all of its
 * properties and calculated properties are useable within a template
 */
abstract class Presentable_Model extends Data_Model {
  /**
   * Present the model using the class provided
   * by presents(). Present knows how to build
   * factories.
   *
   * @return array
   */
  public function present( $options = [] ) {
    $class_reference = $this->get_presenter_class_name();

    if ( ! is_null( $class_reference ) ) {
      $instance = new $class_reference( $this, $options );

      if ( $instance instanceof Factory ) {
        return $instance->build();
      } else {
        return to_array( $instance );
      }
    } else {
      return to_array( $this );
    }
  }

  /**
   * Called to determine which class knows how to present the model.
   * Returning the string of a Factory class is prefered.
   *
   * @return String The name of the class that knows how to present the model
   */
  abstract protected function get_presenter_class_name();
}

<?php

namespace Nectary\Models;

use Nectary\Data_Model;
use Nectary\Factory;

/**
 * A Viewable model is one that can present itself so that all of its
 * properties and calculated properties are useable within a template
 */
abstract class Presentable_Model extends Data_Model {
  /**
   * Present the model using the class provided
   * by presents(). Present knows how to build
   * factories.
   *
   * @return array
   */
  public function present( $options = [] ) {
    $class_reference = $this->get_presenter_class_name();

    if ( ! is_null( $class_reference ) ) {
      $instance = new $class_reference( $this, $options );

      if ( $instance instanceof Factory ) {
        return $instance->build();
      } else {
        return to_array( $instance );
      }
    } else {
      return to_array( $this );
    }
  }

  /**
   * Called to determine which class knows how to present the model.
   * Returning the string of a Factory class is prefered.
   *
   * @return String The name of the class that knows how to present the model
   */
  abstract protected function get_presenter_class_name();
}

Fix factory reference in presentable model


<?php

namespace Swiftmade\Blogdown\Commands;

use Swiftmade\Blogdown\Parser;
use Illuminate\Console\Command;
use Swiftmade\Blogdown\Repository;
use Illuminate\Support\Facades\File;

class Build extends Command
{
    /**
     * @var Repository
     */
    private $repository;

    protected $signature = 'blog:build';
    protected $description = 'Caches blog articles';

    public function __construct(Repository $repository)
    {
        parent::__construct();
        $this->repository = $repository;
    }

    public function handle()
    {
        $this->repository->flush();

        $blogPath = base_path(config('blogdown.blog_folder'));
        collect(File::files($blogPath))
            ->filter(function ($file) {
                return pathinfo($file, PATHINFO_EXTENSION) === 'md';
            })
            ->each(function ($path) {
                $blog = Parser::parse($path);
                $this->repository->put($blog);
                $this->info('Cached /' . $blog->meta->slug);
            });
    }
}

<?php

namespace Swiftmade\Blogdown\Commands;

use Swiftmade\Blogdown\Parser;
use Illuminate\Console\Command;
use Swiftmade\Blogdown\Repository;
use Illuminate\Support\Facades\File;

class Build extends Command
{
    /**
     * @var Repository
     */
    private $repository;

    protected $signature = 'blog:build';
    protected $description = 'Caches blog articles';

    public function __construct(Repository $repository)
    {
        parent::__construct();
        $this->repository = $repository;
    }

    public function handle()
    {
        $this->repository->flush();

        $blogPath = base_path(config('blogdown.blog_folder'));
        collect(File::files($blogPath))
            ->filter(function ($file) {
                return pathinfo($file, PATHINFO_EXTENSION) === 'md';
            })
            ->each(function ($path) {
                $blog = Parser::parse(((string)$path);
                $this->repository->put($blog);
                $this->info('Cached /' . $blog->meta->slug);
            });
    }
}

Fix an issue where some versions of php need the $path property to be converted to a string.


<?php

namespace DataSift\Feature;

use DataSift\Feature\Driver\DriverManager;
use DataSift\Feature\Driver\Services\DriverInterface;

/**
 * Class FeatureManager
 *
 * @package DataSift\Feature
 */
class FeatureManager
{
    /**
     * @var DriverInterface
     */
    protected $driver;

    /**
     * FeatureManager constructor.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->driver = DriverManager::loadDriver($config);
    }

    /**
     * Is the feature flag enabled
     *
     * @param string|array $keys
     * @param mixed        $default
     *
     * @return bool
     */
    public function isEnabled($keys, $default = false)
    {
        if (! is_array($keys)) {
            $keys = array($keys);
        }

        foreach ($keys as $key) {
            $value = $this->driver->get($key, $default);
            if ((is_string($value) && ($value == '' || $value == 'false')) || $value != true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Inverse function for the isEnabled method
     *
     * @param string|array $keys
     * @param bool         $default
     *
     * @return bool
     */
    public function isNotEnabled($keys, $default = false)
    {
        return ! $this->isEnabled($keys, $default);
    }
}

<?php

namespace DataSift\Feature;

use DataSift\Feature\Driver\DriverManager;
use DataSift\Feature\Driver\Services\DriverInterface;

/**
 * Class FeatureManager
 *
 * @package DataSift\Feature
 */
class FeatureManager
{
    /**
     * @var DriverInterface
     */
    protected $driver;

    /**
     * FeatureManager constructor.
     *
     * @param array|DriverInterface $driverConfig
     */
    public function __construct($driverConfig)
    {
        if ($driverConfig instanceof DriverInterface) {
            $this->driver = $driverConfig;
        } else {
            $this->driver = DriverManager::loadDriver($driverConfig);
        }
    }

    /**
     * Is the feature flag enabled
     *
     * @param string|array $keys
     * @param mixed        $default
     *
     * @return bool
     */
    public function isEnabled($keys, $default = false)
    {
        if (! is_array($keys)) {
            $keys = array($keys);
        }

        foreach ($keys as $key) {
            $value = $this->driver->get($key, $default);
            if ((is_string($value) && ($value == '' || $value == 'false')) || $value != true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Inverse function for the isEnabled method
     *
     * @param string|array $keys
     * @param bool         $default
     *
     * @return bool
     */
    public function isNotEnabled($keys, $default = false)
    {
        return ! $this->isEnabled($keys, $default);
    }
}

Add the ability to use a custom driver, in feature manager


<?php namespace CodeIgniter\Config;

/**
 * Class BaseConfig
 *
 * Not intended to be used on its own, this class will attempt to
 * automatically populate the child class' properties with values
 * from the environment.
 *
 * These can be set within the .env file.
 *
 * @package App\Config
 */
class BaseConfig
{
	/**
	 * Will attempt to get environment variables with names
	 * that match the properties of the child class.
	 */
	public function __construct()
	{
		$properties = array_keys(get_object_vars($this));

		foreach ($properties as $property)
		{
			if ($value = getenv($property))
			{
				$this->{$property} = $value;
			}
		}
	}

	//--------------------------------------------------------------------

}

<?php namespace CodeIgniter\Config;

/**
 * Class BaseConfig
 *
 * Not intended to be used on its own, this class will attempt to
 * automatically populate the child class' properties with values
 * from the environment.
 *
 * These can be set within the .env file.
 *
 * @package App\Config
 */
class BaseConfig
{
	/**
	 * Will attempt to get environment variables with names
	 * that match the properties of the child class.
	 */
	public function __construct()
	{
		$properties = array_keys(get_object_vars($this));
		$prefix = get_class($this);

		foreach ($properties as $property)
		{
			if ($value = getenv("{$prefix}.{$property}"))
			{
				$this->{$property} = $value;
			}
			elseif ($value = getenv($property))
			{
				$this->{$property} = $value;
			}
		}
	}

	//--------------------------------------------------------------------

}

Use prefixed properties in .env files

Use prefixed properties in .env files

As mentioned in discussion regarding database config files, BaseConfig
should prefer env vars prefixed with the classname (and a dot (.)
separator) over env vars using the property name alone.


<?php while (have_posts()) : the_post(); ?>
  <article <?php post_class(); ?>>

<?php the_title(); ?>

      <?php get_template_part('templates/entry-meta'); ?>

      <?php the_content(); ?>

      <?php wp_link_pages(['before' => '
' . __('Pages:', 'sage'), 'after' => '
']); ?>

    <?php comments_template('/templates/comments.php'); ?>

<?php endwhile; ?>

<?php while (have_posts()) : the_post(); ?>
  <article <?php post_class(); ?>>

<?php the_title(); ?>

      <?php get_template_part('templates/entry-meta'); ?>

      <?php the_content(); ?>

      <?php wp_link_pages(['before' => '
' . __('Pages:', 'sage'), 'after' => '
']); ?>

<?php endwhile; ?>

Kill WP comments on blog posts.

Kill WP comments on blog posts.


<?php
namespace Transmission\Tests\Model;

use Transmission\Model\File;
use Transmission\Util\PropertyMapper;

class FileTest extends \PHPUnit_Framework_TestCase
{
    protected $file;

    /**
     * @test
     */
    public function shouldImplementModelInterface()
    {
        $this->assertInstanceOf('Transmission\Model\ModelInterface', $this->getFile());
    }

    /**
     * @test
     */
    public function shouldHaveNonEmptyMapping()
    {
        $this->assertNotEmpty($this->getFile()->getMapping());
    }

    /**
     * @test
     */
    public function shouldBeCreatedFromMapping()
    {
        $source = (object) array(
            'name' => 'foo',
            'length' => 100,
            'bytesCompleted' => 10
        );

        PropertyMapper::map($this->getFile(), $source);

        $this->assertEquals('foo', $this->getFile()->getName());
        $this->assertEquals(100, $this->getFile()->getSize());
        $this->assertEquals(10, $this->getFile()->getCompleted());
        $this->assertFalse($this->getFile()->isDone());
    }

    public function setup()
    {
        $this->file = new File();
    }

    private function getFile()
    {
        return $this->file;
    }
}

<?php
namespace Transmission\Tests\Model;

use Transmission\Model\File;
use Transmission\Util\PropertyMapper;

class FileTest extends \PHPUnit_Framework_TestCase
{
    protected $file;

    /**
     * @test
     */
    public function shouldImplementModelInterface()
    {
        $this->assertInstanceOf('Transmission\Model\ModelInterface', $this->getFile());
    }

    /**
     * @test
     */
    public function shouldHaveNonEmptyMapping()
    {
        $this->assertNotEmpty($this->getFile()->getMapping());
    }

    /**
     * @test
     */
    public function shouldBeCreatedFromMapping()
    {
        $source = (object) array(
            'name' => 'foo',
            'length' => 100,
            'bytesCompleted' => 10
        );

        PropertyMapper::map($this->getFile(), $source);

        $this->assertEquals('foo', $this->getFile()->getName());
        $this->assertEquals(100, $this->getFile()->getSize());
        $this->assertEquals(10, $this->getFile()->getCompleted());
        $this->assertFalse($this->getFile()->isDone());
    }

    /**
     * @test
     */
    public function shouldConvertToString()
    {
        $this->getFile()->setName('foo');

        $this->assertInternalType('string', (string) $this->getFile());
        $this->assertEquals('foo', (string) $this->getFile());
    }

    public function setup()
    {
        $this->file = new File();
    }

    private function getFile()
    {
        return $this->file;
    }
}

Add tests for the __toString method of the File model


@extends('layouts.master')

@section('content')

Dashboard

         $user->id, 'secret' => $user->secret()))) }}">Subscribe to your podcast.

        Synchronise with Pocket

    @if (count($items) > 0)
        @include('partials.items', array('items' => $items))
    @endif

@endsection

@extends('layouts.master')

@section('content')

Dashboard

        <button class="button" onclick="window.location.href = \"{{ str_replace('http://', 'itpc://', route('podcast', array('id' => $user->id, 'secret' => $user->secret()))) }}\">Subscribe</button>

Articles are automatically fetched, convert to podcast episodes and added to your feed every hour.

    @if (count($items) > 0)
        @include('partials.items', array('items' => $items))

<button class="button" onclick="window.location.href = \"{{ route('pocket.synchronise') }}\"">Update</button>

    @else

<button class="button" onclick="window.location.href = \"{{ route('pocket.synchronise') }}\"">Get pocket articles</button>

    @endif

@endsection

Change links to button in dashboard.

Change links to button in dashboard.


<?php sleep(2); ?>

Usage

Battery

Play Time

    <fieldset>

            Years
            <input type="text" value="2"/>

            Months
            <input type="text" value="8"/>

            Days
            <input type="text" value="27"/>

    </fieldset>

Better recharge soon!

<?php sleep(2); ?>

Usage

Battery

Play Time

    <fieldset>

            Years
            2

            Months
            8

            Days
            27

    </fieldset>

Better recharge soon!

Update to use <span> instead of <input> for non-modifiable text.


<?php

View::composer('core::partials.sidebar-nav', 'Modules\Dashboard\Composers\SidebarViewComposer');

<?php

View::composer('partials.sidebar-nav', 'Modules\Dashboard\Composers\SidebarViewComposer');

Use the new Admin theme for administration


<?php
/*
 * This file was delivered to you as part of the Yucca package.
 *
 * (c) Rémi JANOT <r.janot@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Yucca\Component\Selector;

class Ids implements SelectorInterface {
    /**
     * @var array
     */
    protected $ids;

    protected $keyName;

    /**
     * @param array $ids
     * @param string $keyName
     */
    public function __construct(array $ids, $keyName = null) {
        $this->ids = $ids;
        $this->keyName = $keyName ;
    }

    /**
     * @return mixed
     */
    public function current()
    {
        if(isset($this->keyName)) {
            return array($this->keyName => current($this->ids));
        } else {
            return current($this->ids);
        }
    }

    /**
     *
     */
    public function next()
    {
        next($this->ids);
    }

    /**
     *
     */
    public function key()
    {
        return key($this->ids);
    }

    /**
     *
     */
    public function valid()
    {
        return ( false !== current($this->ids) );
    }

    /**
     *
     */
    public function rewind()
    {
        reset($this->ids);
    }

    /**
     *
     */
    public function count()
    {
        count($this->ids);
    }

    /**
     * @return null
     */
    public function currentShardingKey()
    {
        return null;
    }
}

<?php
/*
 * This file was delivered to you as part of the Yucca package.
 *
 * (c) Rémi JANOT <r.janot@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Yucca\Component\Selector;

class Ids implements SelectorInterface {
    /**
     * @var array
     */
    protected $ids;

    protected $keyName;

    /**
     * @param array $ids
     * @param string $keyName
     */
    public function __construct(array $ids, $keyName = null) {
        $this->ids = $ids;
        $this->keyName = $keyName ;
    }

    /**
     * @return mixed
     */
    public function current()
    {
        if(isset($this->keyName)) {
            return array($this->keyName => current($this->ids));
        } else {
            return current($this->ids);
        }
    }

    /**
     *
     */
    public function next()
    {
        next($this->ids);
    }

    /**
     *
     */
    public function key()
    {
        return key($this->ids);
    }

    /**
     *
     */
    public function valid()
    {
        return ( false !== current($this->ids) );
    }

    /**
     *
     */
    public function rewind()
    {
        reset($this->ids);
    }

    /**
     *
     */
    public function count()
    {
        return count($this->ids);
    }

    /**
     * @return null
     */
    public function currentShardingKey()
    {
        return null;
    }
}

Fix IDs selector count result

[IDS] Fix IDs selector count result


<?php
/**
 * Select элемент формы
 * @file    SelectElement.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Чтв Ноя 29 22:09:01 2012
 * @copyright The BSD 3-Clause License
 */

namespace Veles\Form\Elements;

/**
 * Класс SelectElement
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class SelectElement extends AbstractElement
{
	/**
	 * Отрисовка элемента
	 */
	final public function render()
	{
		$html  = '<select' . $this->attributes() . '>';

		foreach ($this->options as $option) {
			$selected = '';

			if ($option['id'] == $this->selected) {
				$selected = ' selected="true" ';
			}

			$html .= "<option $selected value=\"$option[id]\">
						$option[name]
					  </option>";
		}

		$html .= '</select>';

		return $html;
	}
}

<?php
/**
 * Select form element
 * @file    SelectElement.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Чтв Ноя 29 22:09:01 2012
 * @copyright The BSD 3-Clause License
 */

namespace Veles\Form\Elements;

/**
 * Class SelectElement
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class SelectElement extends AbstractElement
{
	/**
	 * Element rendering
	 */
	final public function render()
	{
		$html  = '<select' . $this->attributes() . '>';

		foreach ($this->options as $option) {
			$selected = '';

			if (isset($this->selected) && $option['id'] === $this->selected) {
				$selected = ' selected="true" ';
			}

			$html .= "<option $selected value=\"$option[id]\">
						$option[name]
					  </option>";
		}

		$html .= '</select>';

		return $html;
	}

	/**
	 * Set select options
	 *
	 * @param $options
	 */
	final public function setOptions($options)
	{
		$this->options = $options;
	}
}

Add options method for form select element


<?php

namespace PicoFarad\Session;

const SESSION_LIFETIME = 2678400;

function open($base_path = '/', $save_path = '')
{
    if ($save_path !== '') session_save_path($save_path);

    session_set_cookie_params(
        SESSION_LIFETIME,
        $base_path,
        null,
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
        true
    );

    session_start();
}

function close()
{
    session_destroy();
}

function flash($message)
{
    $_SESSION['flash_message'] = $message;
}

function flash_error($message)
{
    $_SESSION['flash_error_message'] = $message;
}

<?php

namespace PicoFarad\Session;

const SESSION_LIFETIME = 2678400;

function open($base_path = '/', $save_path = '')
{
    if ($save_path !== '') session_save_path($save_path);

    // HttpOnly and secure flags for session cookie
    session_set_cookie_params(
        SESSION_LIFETIME,
        $base_path ?: '/',
        null,
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
        true
    );

    // Avoid session id in the URL
    ini_set('session.use_only_cookies', true);

    // Ensure session ID integrity
    ini_set('session.entropy_file', '/dev/urandom');
    ini_set('session.entropy_length', '32');
    ini_set('session.hash_bits_per_character', 6);

    // Custom session name
    session_name('__$');

    session_start();

    // Regenerate the session id to avoid session fixation issue
    if (empty($_SESSION['__validated'])) {
        session_regenerate_id(true);
        $_SESSION['__validated'] = 1;
    }
}

function close()
{
    session_destroy();
}

function flash($message)
{
    $_SESSION['flash_message'] = $message;
}

function flash_error($message)
{
    $_SESSION['flash_error_message'] = $message;
}

Update PicoFarad (session creation improvements)


<?php

namespace Clippings\Freezable;

/**
 * @author    Haralan Dobrev <hkdobrev@gmail.com>
 * @copyright 2014, Clippings Ltd.
 * @license   http://spdx.org/licenses/BSD-3-Clause
 */
trait FreezableTrait
{
    public $isFrozen = false;

    /**
     * Set `isFrozen` and execute `performFreeze()`
     *
     * @return self
     */
    public function freeze()
    {
        if (! $this->isFrozen) {
            $this->performFreeze();
            $this->isFrozen = true;
        }

        return $this;
    }

    /**
     * Unset `isFrozen` and execute `performUnfreeze()`
     *
     * @return self
     */
    public function unfreeze()
    {
        if ($this->isFrozen) {
            $this->performUnfreeze();
            $this->isFrozen = false;
        }

        return $this;
    }
}

<?php

namespace Clippings\Freezable;

/**
 * @author    Haralan Dobrev <hkdobrev@gmail.com>
 * @copyright 2014, Clippings Ltd.
 * @license   http://spdx.org/licenses/BSD-3-Clause
 */
trait FreezableTrait
{
    public $isFrozen = false;

    /**
     * Set `isFrozen` and execute `performFreeze()`
     *
     * @return self
     */
    public function freeze()
    {
        if (! $this->isFrozen) {
            $this->performFreeze();
            $this->isFrozen = true;
        }

        return $this;
    }

    /**
     * Unset `isFrozen` and execute `performUnfreeze()`
     *
     * @return self
     */
    public function unfreeze()
    {
        if ($this->isFrozen) {
            $this->performUnfreeze();
            $this->isFrozen = false;
        }

        return $this;
    }

    /**
     * Perform actual freezing.
     * It could be achieved by simply storing dynamic value returned
     * by a function in a property.
     *
     * @return void
     */
    abstract public function performFreeze();

    /**
     * Perform actual unfreezing.
     * It should be the opposite of the freezeing.
     * E.g. setting the property value to null.
     *
     * @return void
     */
    abstract public function performUnfreeze();
}

Add abstract performFreezen and performUnfreeze methods to trait


<?php defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController {

	public function view() {
		$this->set('tracking_code', Config::get('SITE_TRACKING_CODE'));
		$tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION');
		if (!$tracking_code_position) {
			$tracking_code_position = 'bottom';
		}
		$this->set('tracking_code_position', $tracking_code_position);

		if ($this->isPost()) {
			if ($this->token->validate('update_tracking_code')) {
					Config::save('SITE_TRACKING_CODE', $this->post('tracking_code'));
					Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position'));
					$this->redirect('/dashboard/system/seo/tracking_codes', 'saved');
			} else {
				$this->error->add($this->token->getErrorMessage());
			}
		}
	}

	public function saved() {
		$this->set('message', t('Tracking code settings updated successfully.'));
		$this->view();
	}
}

<?php defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController {

	public function view() {
		$this->set('tracking_code', Config::get('SITE_TRACKING_CODE'));
		$tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION');
		if (!$tracking_code_position) {
			$tracking_code_position = 'bottom';
		}
		$this->set('tracking_code_position', $tracking_code_position);

		if ($this->isPost()) {
			if ($this->token->validate('update_tracking_code')) {
					Config::save('SITE_TRACKING_CODE', $this->post('tracking_code'));
					Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position'));
					Cache::flush();
					$this->redirect('/dashboard/system/seo/tracking_codes', 'saved');
			} else {
				$this->error->add($this->token->getErrorMessage());
			}
		}
	}

	public function saved() {
		$this->set('message', implode(PHP_EOL, array(
			t('Tracking code settings updated successfully.'),
			t('Cached files removed.')
		)));
		$this->view();
	}
}

Fix outdated cache after saving tracking codes


<?php

/**
 * @package     PHPUnit_Helper
 *
 * @author      Adamo Crespi <hello@aerendir.me>
 * @copyright   Copyright (C) 2016.
 * @license     MIT
 */

namespace SerendipityHQ\Library\PHPUnit_Helper;

/**
 * A PHPUnit helper to better manage tested resources, mocked objects and test values
 *
 * @package SerendipityHQ\Library\PHPUnit_Helper
 */
trait PHPUnit_Helper
{
    /**
     * Sets to null all instantiated properties to freeup memory
     */
    protected function tearDown()
    {
        $refl = new \ReflectionObject($this);
        foreach ($refl->getProperties() as $prop) {
            if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
                $prop->setAccessible(true);
                $prop->setValue($this, null);
            }
        }
    }
}

<?php

/**
 * @package     PHPUnit_Helper
 *
 * @author      Adamo Crespi <hello@aerendir.me>
 * @copyright   Copyright (C) 2016.
 * @license     MIT
 */

namespace SerendipityHQ\Library\PHPUnit_Helper;

/**
 * A PHPUnit helper to better manage tested resources, mocked objects and test values
 *
 * @package SerendipityHQ\Library\PHPUnit_Helper
 */
trait PHPUnit_Helper
{
    /** @var object The tested resource */
    private $resource;

    /**
     * @param object $resource The resource to test
     */
    protected function setResource($resource)
    {
        if (false === is_object($resource))
            throw new \InvalidArgumentException('A Resource has to be an Object');

        $this->resource = $resource;
    }

    /**
     * @return object The tested resource
     */
    protected function getResource()
    {
        return $this->resource;
    }

    /**
     * Sets to null all instantiated properties to freeup memory
     */
    protected function helpTearDown()
    {
        $refl = new \ReflectionObject($this);
        foreach ($refl->getProperties() as $prop) {
            if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
                $prop->setAccessible(true);
                $prop->setValue($this, null);
            }
        }
    }
}

Add get and set methods for a resource.

Add get and set methods for a resource.


<?php

namespace App\Console\Commands;

use Github;
use App\Org;
use Illuminate\Console\Command;

class UpdateOrg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orgmanager:updateorg {org : The ID of the organization}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command to update organization data from Github (mostly used internally)';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $org = Org::findOrFail($this->argument('org'));
        Github::authenticate($org->user->token, null, 'http_token');
        $orgdata = Github::api('organization')->show($org->name);
        $org->name = $orgdata['login'];
        if (isset($orgdata['name'])) {
            $org->pretty_name = $orgdata['name'];
        }
        $org->description = $orgdata['description'];
        $org->save();
        $this->info($org->name.' updated successfully');
    }
}

<?php

namespace App\Console\Commands;

use Github;
use App\Org;
use Illuminate\Console\Command;

class UpdateOrg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orgmanager:updateorg {org : The ID of the organization}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command to update organization data from Github (mostly used internally)';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $org = Org::findOrFail($this->argument('org'));
        Github::authenticate($org->user->token, null, 'http_token');
        $orgdata = Github::api('organization')->show($org->name);
        $org->name = $orgdata['login'];
        if (isset($orgdata['name'])) {
            $org->pretty_name = $orgdata['name'];
        }
        $org->description = $orgdata['description'];
        $org->avatar = 'https://avatars.githubusercontent.com/'.$orgdata['login'];
        $org->save();
        $this->info($org->name.' updated successfully');
    }
}

Update organization image on sync

Update organization image on sync


<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.class.l10nproviderphp.inc.php");
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.class.l10nprovidergettext.inc.php");
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

Load specific L10n providers in factory

system: Load specific L10n providers in factory


<?php

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

namespace Sylius\Component\Channel\Model;

use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return string
     */
    public function getHostname();

    /**
     * @param string $url
     */
    public function setHostname($hostname);

    /**
     * @return string
     */
    public function getColor();

    /**
     * @param string $color
     */
    public function setColor($color);
}

<?php

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

namespace Sylius\Component\Channel\Model;

use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return string
     */
    public function getHostname();

    /**
     * @param string $hostname
     */
    public function setHostname($hostname);

    /**
     * @return string
     */
    public function getColor();

    /**
     * @param string $color
     */
    public function setColor($color);
}

Fix missing parameter in docs of setChannel function


<?php

function jf_template_path() {
  return Wrapper::$main_template;
}

function jf_template_base() {
  return Wrapper::$base;
}

class Wrapper {
  /**
   * Stores the full path to the main template file
   */
  static $main_template;

  /**
   * Stores the base name of the template file; e.g. 'page' for 'page.php' etc.
   */
  static $base;

  static function jf_wrap( $template ) {
    self::$main_template = $template;

    self::$base = substr( basename( self::$main_template ), 0, -4 );

    if ( 'index' == self::$base )
      self::$base = false;

    $templates = array( 'wrapper.php' );

    if ( self::$base )
      array_unshift( $templates, sprintf( 'wrapper-%s.php', self::$base ) );

    return locate_template( $templates );
  }
}
add_filter( 'template_include', array( 'Wrapper', 'jf_wrap' ), 99 );

function relinquish_theme_home_page_url( $link, $post ) {
    $post = get_post($post);

    if ( 'page' == get_option( 'show_on_front' ) && $post->ID == get_option( 'page_on_front' ) && defined('RELINQUISH_FRONTEND') )
        $link = RELINQUISH_FRONTEND;

    return $link;
}
add_filter('page_link', 'relinquish_theme_home_page_url');

Fix home page url when relinquish front end is set


<?php

use Illuminate\Console\Command;

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		SSH::run([
			"php artisan down",
			"git pull origin develop",
			"composer update",
			"php artisan up",
		]);
	}

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

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

<?php

use Illuminate\Console\Command;

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

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

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		SSH::run([
			"cd " . @$_ENV["SSH_ROOT"],
			"php artisan down",
			"git pull origin develop",
			"composer update",
			"php artisan up",
		]);
	}

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

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

Fix automated deployments by actually changing directory


<?php
/**
 * This helper package makes a database connection for package Kola\PotatoOrm\Model.
 *
 * @package Kola\PotatoOrm\Helper\DbConn
 * @author  Kolawole ERINOSO <kola.erinoso@gmail.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 */

namespace Kola\PotatoOrm\Helper;

use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;

final class DbConn extends PDO implements DbConnInterface
{
    /**
     * Override the parent class PDO constructor to prevent instantiation-argument requirement
     */
    public function __construct()
    {
    }

    /**
     * Make a database connection
     *
     * @return PDO|string
     */
    public static function connect()
    {
        self::loadDotenv();

        try {
            $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
            $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (ConnEx $e) {
            return $e->message();
        }

        return $dbConn;
    }

    /**
     * Load Dotenv to grant getenv() access to environment variables in .env file
     */
    private static function loadDotenv()
    {
        $dotenv = new \Dotenv\Dotenv(__DIR__ . '/../..');
        $dotenv->load();
    }
}

<?php
/**
 * This helper package makes a database connection for package Kola\PotatoOrm\Model.
 *
 * @package Kola\PotatoOrm\Helper\DbConn
 * @author  Kolawole ERINOSO <kola.erinoso@gmail.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 */

namespace Kola\PotatoOrm\Helper;

use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;

final class DbConn extends PDO implements DbConnInterface
{
    /**
     * Override the parent class PDO constructor to prevent instantiation-argument requirement
     */
    public function __construct()
    {
    }

    /**
     * Make a database connection
     *
     * @return PDO|string
     */
    public static function connect()
    {
        self::loadDotenv();

        try {
            $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
            $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (ConnEx $e) {
            return $e->message();
        }

        return $dbConn;
    }

    /**
     * Load Dotenv to grant getenv() access to environment variables in .env file
     */
    private static function loadDotenv()
    {
        $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']);
        $dotenv->load();
    }
}

Make Dotenv to search for .env file in the document root always


<?php
/**
 * Plugin Name:       Geo Query
 * Description:       Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
 * Plugin URI:        https://github.com/birgire/geo-query
 * GitHub Plugin URI: https://github.com/birgire/geo-query.git
 * Author:	      Birgir Erlendsson (birgire)
 * Version:           0.0.3
 * Licence:           MIT
 */

namespace Birgir\Geo;

/**
 * Autoload
 */

\add_action( 'plugins_loaded', function()
{
    require __DIR__ . '/vendor/autoload.php';
});

/**
 * Init
 */

\add_action( 'init', function()
{
    if( class_exists( __NAMESPACE__ . '\\GeoQueryContext' ) )
    {
     	$o = new GeoQueryContext();
        $o->setup( $GLOBALS['wpdb'] )->activate();
    }

});

<?php
/**
 * Plugin Name:       Geo Query
 * Description:       Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
 * Plugin URI:        https://github.com/birgire/geo-query
 * GitHub Plugin URI: https://github.com/birgire/geo-query.git
 * Author:	      Birgir Erlendsson (birgire)
 * Version:           0.0.4
 * Licence:           MIT
 */

namespace Birgir\Geo;

/**
 * Autoload
 */

\add_action( 'plugins_loaded', function()
{
    require __DIR__ . '/vendor/autoload.php';
});

/**
 * Init
 */

\add_action( 'init', function()
{
    if( class_exists( __NAMESPACE__ . '\\GeoQueryContext' ) )
    {
     	$o = new GeoQueryContext();
        $o->setup( $GLOBALS['wpdb'] )->activate();
    }

});

Fix a typo, props @billzhong

Fix a typo, props @billzhong


<?php

class CM_Form_ExampleIcon extends CM_Form_Abstract {

    public function setup() {

        $this->registerField('sizeSlider', new CM_FormField_Integer(6, 120, 0));
        $this->registerField('colorBackground', new CM_FormField_Color());
        $this->registerField('color', new CM_FormField_Color());
        $this->registerField('shadowColor', new CM_FormField_Color());
        $this->registerField('shadowX', new CM_FormField_Integer(0, 20, 0));
        $this->registerField('shadowY', new CM_FormField_Integer(0, 20, 0));
        $this->registerField('shadowBlur', new CM_FormField_Integer(0, 20, 0));
    }

    public function _renderStart(CM_Params $params) {
        $this->getField('sizeSlider')->setValue(18);
        $this->getField('shadowColor')->setValue('#333');
        $this->getField('colorBackground')->setValue('#fafafa');
    }
}

<?php

class CM_Form_ExampleIcon extends CM_Form_Abstract {

    public function setup() {

        $this->registerField('sizeSlider', new CM_FormField_Integer(6, 120, 1));
        $this->registerField('colorBackground', new CM_FormField_Color());
        $this->registerField('color', new CM_FormField_Color());
        $this->registerField('shadowColor', new CM_FormField_Color());
        $this->registerField('shadowX', new CM_FormField_Integer(0, 20, 1));
        $this->registerField('shadowY', new CM_FormField_Integer(0, 20, 1));
        $this->registerField('shadowBlur', new CM_FormField_Integer(0, 20, 2));
    }

    public function _renderStart(CM_Params $params) {
        $this->getField('sizeSlider')->setValue(18);
        $this->getField('shadowColor')->setValue('#333');
        $this->getField('colorBackground')->setValue('#fafafa');
    }
}

Set non-zero steps for example-icon form


<?php
    global $post;
    $items = get_field('items', $module->ID);

    $class = '';

    switch ($args['id']) {
        case 'content-area':
            $class = 'box-panel-secondary';
            break;

        default:
            $class = 'box-panel-primary';
            break;
    }

?>

        <div class="box box-panel <?php echo $class; ?>">

<?php echo $module->post_title; ?>

                <?php foreach ($items as $item) : ?>
                    <?php if ($item['type'] == 'external') : ?>

                        <a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?>

                    <?php elseif ($item['type'] == 'internal') : ?>

                        <a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?>
                            <?php if ($item['date'] === true) : ?>
                            <?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?>
                            <?php endif; ?>

                    <?php endif; ?>
                <?php endforeach; ?>

<?php
    global $post;
    $items = get_field('items', $module->ID);
?>

<?php echo $module->post_title; ?>

                <?php foreach ($items as $item) : ?>
                    <?php if ($item['type'] == 'external') : ?>

                        <a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?>

                    <?php elseif ($item['type'] == 'internal') : ?>

                        <a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?>
                            <?php if ($item['date'] === true) : ?>
                            <?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?>
                            <?php endif; ?>

                    <?php endif; ?>
                <?php endforeach; ?>

Remove theme specific code from inlaylist template


<?php namespace Laravel\CLI\Tasks\Bundle\Providers; use Laravel\Request;

class Github extends Provider {

	/**
	 * Install the given bundle into the application.
	 *
	 * @param  string  $bundle
	 * @param  string  $path
	 * @return void
	 */
	public function install($bundle, $path)
	{
		$url = "http://nodeload.github.com/{$bundle['location']}/zipball/master";

		parent::zipball($url, $bundle, $path);
	}

}

<?php namespace Laravel\CLI\Tasks\Bundle\Providers; use Laravel\Request;

class Github extends Provider {

	/**
	 * Install the given bundle into the application.
	 *
	 * @param  string  $bundle
	 * @param  string  $path
	 * @return void
	 */
	public function install($bundle, $path)
	{
		$url = "http://github.com/{$bundle['location']}/zipball/master";

		parent::zipball($url, $bundle, $path);
	}

}

Use the public facing URL for fetching bundles stored on GitHub.

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


<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Component\Rule\Repository;

use Doctrine\ORM\EntityRepository;

use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface;

/**
 * Class RuleRepository
 */
class RuleRepository extends EntityRepository
{
    /**
     * Return a rule by name
     *
     * @param string $name
     *
     * @return null|RuleInterface
     */
    public function findOneByName($name)
    {
        return parent::findOneBy(['name' => $name]);
    }
}

<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Component\Rule\Repository;

use Doctrine\ORM\EntityRepository;

use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface;

/**
 * Class RuleRepository
 */
class RuleRepository extends EntityRepository
{
    /**
     * Return a rule by name
     *
     * @param string $name
     *
     * @return RuleInterface|null
     */
    public function findOneByName($name)
    {
        return parent::findOneBy(['name' => $name]);
    }
}

PhpDoc: Fix type inconsistencies, put |null last for better readability


<?php

namespace common\models\comments;

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

abstract class Comment extends ActiveRecord
{
    public static function instantiate($row)
    {
        return new AdjacencyListComment();
    }

    public static function create($config = [])
    {
        return new AdjacencyListComment($config);
    }

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

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

<?php

namespace common\models\comments;

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

abstract class Comment extends ActiveRecord
{
    public static function instantiate($row)
    {
        return new AdjacencyListComment();
    }

    public static function create($config = [])
    {
        return new AdjacencyListComment($config);
    }

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

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

Add necessary behaviors and validation rules.


<?php namespace Worldpay;

class WorldpayTest extends TestCase {

  public function testRequestInstantiation()
  {
    $this->assertInstanceOf('Worldpay\Request', $this->getWorldpay()->request($this->getNormalRequest()));
  }

  public function testResponseInstantiation()
  {
    $this->assertInstanceOf('Worldpay\Response', $this->getWorldpay()->response($this->getNormalResponse()));
  }

}

<?php namespace Worldpay;

class WorldpayTest extends TestCase {

  public function testRequestInstantiation()
  {
    $this->assertInstanceOf('Worldpay\Request', $this->getWorldpay()->request($this->getNormalRequest()));
  }

  public function testResponseInstantiation()
  {
    $this->assertInstanceOf('Worldpay\Response', $this->getWorldpay()->response($this->getNormalResponse()));
  }

  public function testEnvironementCallbackURL()
  {
    $wp = new WorldPay;
    $wp->setConfig(array(
      'env' => 'local',
      'local' => 'example.local/callbacks/worldpay'
    ));
    $request = $wp->request(array(
      'instId' => '123456',
      'cartId' => 'my_shop',
      'currency' => 'GBP',
      'amount' => 9.99
    ));
    $prepare = $request->prepare();
    $this->assertEquals('example.local/callbacks/worldpay', $prepare['endpoint']);
  }

}

Add test to check custom environment URL


<?php

spl_autoload_register(
    function ($class) {
        // No op.
    }
);

<?php

/**
 * This file is part of phpcq/autoload-validation.
 *
 * (c) 2014 Christian Schiffler, Tristan Lins
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * This project is provided in good faith and hope to be usable by anyone.
 *
 * @package    phpcq/autoload-validation
 * @author     Christian Schiffler <c.schiffler@cyberspectrum.de>
 * @copyright  2014-2016 Christian Schiffler <c.schiffler@cyberspectrum.de>
 * @license    https://github.com/phpcq/autoload-validation/blob/master/LICENSE MIT
 * @link       https://github.com/phpcq/autoload-validation
 * @filesource
 */

spl_autoload_register(
    function ($class) {
        // No op.
    }
);

Add file header to fixture

Add file header to fixture


<?php declare(strict_types = 1);

namespace Mihaeu\TestGenerator;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Twig\Template;
use Twig_Environment;

/**
 * @covers Mihaeu\TestGenerator\TwigRenderer
 */
class TwigRendererTest extends TestCase
{
    /** @var TwigRenderer */
    private $twigRenderer;

    /** @var Twig_Environment | PHPUnit_Framework_MockObject_MockObject */
    private $twig;

    /** @var Template | PHPUnit_Framework_MockObject_MockObject */
    private $template;

    protected function setUp()
    {
        $this->template = $this->createMock(Template::class);
        $this->twig = $this->createMock(Twig_Environment::class);
        $this->twig->expects($this->once())->method('load')->willReturn($this->template);
        $this->twigRenderer = new TwigRenderer($this->twig, new TemplateConfiguration(new Clazz('', '', '')));
    }

    public function testRendersClassnameAndParameters()
    {
        $this->template->expects($this->once())->method('render')->willReturn('test');
        assertEquals(
            'test',
            $this->twigRenderer->render(new Clazz('', '', ''), [123]));
    }
}

<?php declare(strict_types = 1);

namespace Mihaeu\TestGenerator;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Twig\Template;
use Twig_Environment;

/**
 * @covers Mihaeu\TestGenerator\TwigRenderer
 */
class TwigRendererTest extends TestCase
{
    /** @var TwigRenderer */
    private $twigRenderer;

    /** @var Twig_Environment | PHPUnit\Framework\MockObject\MockObject */
    private $twig;

    /** @var Template | PHPUnit\Framework\MockObject\MockObject */
    private $template;

    protected function setUp()
    {
        $this->template = $this->createMock(Template::class);
        $this->twig = $this->createMock(Twig_Environment::class);
        $this->twig->expects($this->once())->method('load')->willReturn($this->template);
        $this->twigRenderer = new TwigRenderer($this->twig, new TemplateConfiguration(new Clazz('', '', '')));
    }

    public function testRendersClassnameAndParameters()
    {
        $this->template->expects($this->once())->method('render')->willReturn('test');
        assertEquals(
            'test',
            $this->twigRenderer->render(new Clazz('', '', ''), [123]));
    }
}

Modify MockObject namespace in tpye hint comment


@if(!setting('enable_voting'))

Sign up for updates!

Voting is closed, but sign up to be notified when we're ready!

        {!! Form::open(['route' => 'users.store']) !!}
        @include('auth.form')
        {!! Form::submit('Send me updates!', ['class' => 'button -primary']) !!}
        {!! Form::close() !!}

        @if(is_domestic_session() || should_collect_international_phone())

                By signing up for updates, you agree to receive future updates from DoSomething.org (duh!).

                Message & data rates may apply. Text STOP to opt-out, HELP for help.

        @endif

@endif

Clean up closed state form.

Clean up closed state form.


@section('content')

                <form>

Test
{{ \Carbon\Carbon::now() }}

                    <textarea name="post-content" class="js-st-instance"></textarea>

                    <button type="submit" class="btn btn-default btn-lg">Add Post</button>

                </form>

        @foreach($posts as $post)

{{ $post->getTitle() }}
{{ $post->getPublishDate() }}

{{ Str::words($post->getContent(), 100) }}

                Read More

        @endforeach

@endsection

Put that editor in a div, editors love divs.

2011-12 Called, they want their meme back.


<?php

namespace ArgumentsResolver\Tests;

use ArgumentsResolver\UnresolvableArgumentException;

class UnresolvableArgumentExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testGettingErrorMessage()
    {
        $functionName = __NAMESPACE__.'\Fixtures\function_various';
        $function = new \ReflectionFunction($functionName);

        $parameter = reset($function->getParameters());
        $exception = new UnresolvableArgumentException($parameter);

        $this->assertRegExp(
            sprintf('/^Unable to resolve argument \$\w+ \(#0\) of %s\(\)\.$/', preg_quote($functionName, '/')),
            $exception->getMessage()
        );
    }
}

<?php

namespace ArgumentsResolver\Tests;

use ArgumentsResolver\UnresolvableArgumentException;

class UnresolvableArgumentExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testGettingErrorMessage()
    {
        $functionName = __NAMESPACE__.'\Fixtures\function_various';
        $function = new \ReflectionFunction($functionName);

        $parameters = $function->getParameters();
        $exception = new UnresolvableArgumentException($parameters[0]);

        $this->assertRegExp(
            sprintf('/^Unable to resolve argument \$\w+ \(#0\) of %s\(\)\.$/', preg_quote($functionName, '/')),
            $exception->getMessage()
        );
    }
}

Fix a test to work with php 5.4

Fix a test to work with php 5.4


<?php

namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler;

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

class MenuUpdateProviderPass implements CompilerPassInterface
{
    const BUILDER_SERVICE_ID = 'oro_navigation.menu_update.builder';

    const MENU_UPDATE_PROVIDER_SERVICE_ID = 'oro_navigation.menu_update_provider.default';
    const OWNERSHIP_PROVIDER_TAG = 'oro_navigation.ownership_provider';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $this->processUpdateProviders($container);
    }

    /**
     * @param ContainerBuilder $container
     */
    protected function processUpdateProviders(ContainerBuilder $container)
    {
        if (!$container->hasDefinition(self::BUILDER_SERVICE_ID)) {
            return;
        }

        $providers = $container->findTaggedServiceIds(self::OWNERSHIP_PROVIDER_TAG);
        if (!$providers) {
            return;
        }

        $builderService = $container->getDefinition(self::BUILDER_SERVICE_ID);

        foreach ($providers as $id => $tags) {
            foreach ($tags as $attributes) {
                $builderService->addMethodCall(
                    'addProvider',
                    [new Reference($id), $attributes['area'], $attributes['priority']]
                );
            }
        }
    }
}

<?php

namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler;

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

class MenuUpdateProviderPass implements CompilerPassInterface
{
    const BUILDER_SERVICE_ID = 'oro_navigation.menu_update.builder';
    const OWNERSHIP_PROVIDER_TAG = 'oro_navigation.ownership_provider';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $this->processUpdateProviders($container);
    }

    /**
     * @param ContainerBuilder $container
     */
    protected function processUpdateProviders(ContainerBuilder $container)
    {
        if (!$container->hasDefinition(self::BUILDER_SERVICE_ID)) {
            return;
        }

        $providers = $container->findTaggedServiceIds(self::OWNERSHIP_PROVIDER_TAG);
        if (!$providers) {
            return;
        }

        $builderService = $container->getDefinition(self::BUILDER_SERVICE_ID);

        foreach ($providers as $id => $tags) {
            foreach ($tags as $attributes) {
                $builderService->addMethodCall(
                    'addProvider',
                    [new Reference($id), $attributes['area'], $attributes['priority']]
                );
            }
        }
    }
}

BB-4780: Convert Organization scope to Global in NavigationBundle, remove Website and AccountUser scope from FrontendNavigationBundle
- removed unused constant


<?php namespace Illuminate\Support\Facades;

class Cookie extends Facade {

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

}

<?php namespace Illuminate\Support\Facades;

class Cookie extends Facade {

	/**
	 * Retrieve a cookie from the request.
	 *
	 * @param  string  $key
	 * @param  mixed   $default
	 * @return string
	 */
	public static function get($key = null, $default = null)
	{
		return static::$app['request']->cookie($key, $default);
	}

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

}

Add get method to cookie facade.

Add get method to cookie facade.


@if($posts_preview)

{{ HTML::image('/img/arrow.png', 'arrow', array('title' => 'arrow', 'height' => '45', 'width' => '45')) }} {{ Lang::line('content.more_word')->get(Session::get('lang')) }}

		@foreach ($posts_preview as $post)
		    @if(Session::get('user.access_level') >= $post->access)

    				@include('partials.postpreview')

			@endif
		@endforeach

@endif

Fix for very new and empty CMS

Fix for very new and empty CMS


<?php

/**
 * Load admin dependencies.
 */
$tempdir = get_template_directory();
require_once($tempdir.'/admin/init.php');

/**
 * Configure Default Title.
 */
add_filter('wp_title', function($title)
{
	$name = get_bloginfo('name');
	$description = get_bloginfo('description');

	if (is_front_page()) { return "$name - $description"; }

	return trim($title).' - '.$name;
});

/**
 * Configure Excerpt String.
 */
add_filter('wp_trim_excerpt', function($excerpt)
{
	return str_replace('[...]', '…', $excerpt);
});

<?php

/**
 * Load admin dependencies.
 */
$tempdir = get_template_directory();
require_once($tempdir.'/admin/init.php');

/**
 * Theme set up settings.
 */
add_action('after_setup_theme', function()
{
	// Configure WP 2.9+ Thumbnails.
	add_theme_support('post-thumbnails');
	set_post_thumbnail_size(50, 50, true);
	add_image_size('thumbnail-large', 500, '', false);

	// Add support for post formats.
	add_theme_support('post-formats', ['aside', 'gallery', 'image', 'link', 'quote', 'video', 'audio']);
});

/**
 * Configure Default Title.
 */
add_filter('wp_title', function($title)
{
	$name = get_bloginfo('name');
	$description = get_bloginfo('description');

	if (is_front_page()) { return "$name - $description"; }

	return trim($title).' - '.$name;
});

/**
 * Configure Excerpt String.
 */
add_filter('wp_trim_excerpt', function($excerpt)
{
	return str_replace('[...]', '…', $excerpt);
});

/**
 * Change Default Excerpt Length.
 */
add_filter('excerpt_length', function($length)
{
	return 55;
});

Add theme set up settings.

Add theme set up settings.


<?php

include('../www/config.php');
include('../www/functions.php');

include('../www/libs/Db.class.php');
include('../www/libs/Socket.class.php');
include('../www/libs/Server.class.php');
include('../www/libs/Guest.class.php');
include('../www/libs/User.class.php');
include('../www/libs/Admin.class.php');

Admin::serverReload();

?>

<?php

include('/usr/share/vca/www/config.php');
include(PATH.'www/functions.php');

include(PATH.'www/libs/Db.class.php');
include(PATH.'www/libs/Socket.class.php');
include(PATH.'www/libs/Server.class.php');
include(PATH.'www/libs/Guest.class.php');
include(PATH.'www/libs/User.class.php');
include(PATH.'www/libs/Admin.class.php');

$admin = new Admin(0);
$admin->serverReload();

?>

Fix cron, for server information update

Fix cron, for server information update


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Addressing\Comparator;

use Sylius\Component\Addressing\Model\AddressInterface;

/**
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
final class AddressComparator implements AddressComparatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function equal(AddressInterface $firstAddress, AddressInterface $secondAddress)
    {
        return $this->normalizeAddress($firstAddress) === $this->normalizeAddress($secondAddress);
    }

    /**
     * @param AddressInterface $address
     *
     * @return array
     */
    private function normalizeAddress(AddressInterface $address)
    {
        return array_map(function ($value) {
            return trim(strtolower($value));
        }, [
            $address->getCity(),
            $address->getCompany(),
            $address->getCountryCode(),
            $address->getFirstName(),
            $address->getLastName(),
            $address->getPhoneNumber(),
            $address->getPostcode(),
            $address->getProvinceCode(),
            $address->getProvinceName(),
            $address->getStreet(),
        ]);
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Addressing\Comparator;

use Sylius\Component\Addressing\Model\AddressInterface;

/**
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
final class AddressComparator implements AddressComparatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function equal(AddressInterface $firstAddress, AddressInterface $secondAddress)
    {
        return $this->normalizeAddress($firstAddress) === $this->normalizeAddress($secondAddress);
    }

    /**
     * @param AddressInterface $address
     *
     * @return array
     */
    private function normalizeAddress(AddressInterface $address)
    {
        return array_map(function ($value) {
            return strtolower(trim((string) $value));
        }, [
            $address->getCity(),
            $address->getCompany(),
            $address->getCountryCode(),
            $address->getFirstName(),
            $address->getLastName(),
            $address->getPhoneNumber(),
            $address->getPostcode(),
            $address->getProvinceCode(),
            $address->getProvinceName(),
            $address->getStreet(),
        ]);
    }
}

Fix all specs failing due to strict types being enabled


<?php namespace Dyaa\Pushover;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class PushoverServiceProvider extends ServiceProvider {

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

        $this->app['pushover'] = $this->app->share(function($app)
        {
            return new Pushover($app['config']);
        });

        $this->app->booting(function()
        {
            $loader = AliasLoader::getInstance();
            $loader->alias('Pushover', 'Dyaa\Pushover\Facades\Pushover');
        });

        $this->app['pushover.send'] = $this->app->share(function ()
        {
            return new Commands\PushoverCommand($this->app['pushover']);
        });

        $this->commands(
            'pushover.send'
        );
    }

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

}

<?php namespace Dyaa\Pushover;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class PushoverServiceProvider extends ServiceProvider {

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

        $this->app->singleton('pushover', function($app)
        {
            return new Pushover($app['config']);
        });

        $this->app->booting(function()
        {
            $loader = AliasLoader::getInstance();
            $loader->alias('Pushover', 'Dyaa\Pushover\Facades\Pushover');
        });

        $this->app->singleton('pushover.send', function ()
        {
            return new Commands\PushoverCommand($this->app['pushover']);
        });

        $this->commands(
            'pushover.send'
        );
    }

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

}

Replace app share with app singleton function for laravel 5.4 support


<?php
require_once realpath(__DIR__ . '/../core/slir.class.php');

abstract class SLIRTestCase extends PHPUnit_Framework_TestCase
{
  /**
   * @var SLIR
   */
  protected $slir;

  /**
   * @return void
   */
  protected function setUp()
  {
    $this->slir = new SLIR();
    SLIRConfig::$defaultImagePath = null;
    SLIRConfig::$forceQueryString = false;
    SLIRConfig::$enableErrorImages = false;

    // Try to fix documentRoot for CLI
    SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../');
  }

  /**
   * @return void
   */
  protected function tearDown()
  {
    unset($this->slir);
  }
}

<?php
require_once realpath(__DIR__ . '/../core/slir.class.php');

abstract class SLIRTestCase extends PHPUnit_Framework_TestCase
{
  /**
   * @var SLIR
   */
  protected $slir;

  /**
   * @return void
   */
  protected function setUp()
  {
    $this->slir = new SLIR();
    SLIRConfig::$defaultImagePath   = null;
    SLIRConfig::$forceQueryString   = false;
    SLIRConfig::$enableErrorImages  = false;
    SLIRConfig::$defaultCropper     = SLIR::CROP_CLASS_CENTERED;

    // Try to fix documentRoot for CLI
    SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../');
  }

  /**
   * @return void
   */
  protected function tearDown()
  {
    unset($this->slir);
  }
}

Set the centered cropper as the default cropper for tests.

The centered cropper is fast, so this should save time when running tests.


<?php
/**
 * Created by PhpStorm.
 * User: LPALQUILER-11
 * Date: 29/08/2018
 * Time: 17:30.
 */

namespace Greenter\Zip;

use ZipArchive;

/**
 * Class ZipFileDecompress.
 */
class ZipFileDecompress implements DecompressInterface
{
    /**
     * Extract files.
     *
     * @param string        $content
     * @param callable|null $filter
     *
     * @return array
     */
    public function decompress(?string $content, callable $filter = null): ?array
    {
        $temp = tempnam(sys_get_temp_dir(), time().'.zip');
        file_put_contents($temp, $content);
        $zip = new ZipArchive();
        $output = [];
        if (true === $zip->open($temp) && $zip->numFiles > 0) {
            $output = iterator_to_array($this->getFiles($zip, $filter));
        }
        $zip->close();
        unlink($temp);

        return $output;
    }

    private function getFiles(ZipArchive $zip, $filter)
    {
        $total = $zip->numFiles;
        for ($i = 0; $i < $total; ++$i) {
            $name = $zip->getNameIndex($i);

            if (!$filter || $filter($name)) {
                yield [
                    'filename' => $name,
                    'content' => $zip->getFromIndex($i),
                ];
            }
        }
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: LPALQUILER-11
 * Date: 29/08/2018
 * Time: 17:30.
 */

namespace Greenter\Zip;

use ZipArchive;

/**
 * Class ZipFileDecompress.
 * @deprecated deprecated since version v4.0.3, use ZipFlyDecompress
 */
class ZipFileDecompress implements DecompressInterface
{
    /**
     * Extract files.
     *
     * @param string        $content
     * @param callable|null $filter
     *
     * @return array
     */
    public function decompress(?string $content, callable $filter = null): ?array
    {
        $temp = tempnam(sys_get_temp_dir(), time().'.zip');
        file_put_contents($temp, $content);
        $zip = new ZipArchive();
        $output = [];
        if (true === $zip->open($temp) && $zip->numFiles > 0) {
            $output = iterator_to_array($this->getFiles($zip, $filter));
        }
        $zip->close();
        unlink($temp);

        return $output;
    }

    private function getFiles(ZipArchive $zip, $filter)
    {
        $total = $zip->numFiles;
        for ($i = 0; $i < $total; ++$i) {
            $name = $zip->getNameIndex($i);

            if (!$filter || $filter($name)) {
                yield [
                    'filename' => $name,
                    'content' => $zip->getFromIndex($i),
                ];
            }
        }
    }
}

Set deprecated php-ext-zip used class

Set deprecated php-ext-zip used class


<?php

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

namespace Symfony\Component\Security\Http\EntryPoint;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

/**
 * Implement this interface for any classes that will be called to "start"
 * the authentication process (see method for more details).
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface AuthenticationEntryPointInterface
{
    /**
     * Returns a response that directs the user to authenticate.
     *
     * This is called when an anonymous request accesses a resource that
     * requires authentication. The job of this method is to return some
     * response that "helps" the user start into the authentication process.
     *
     * Examples:
     *  A) For a form login, you might redirect to the login page
     *      return new RedirectResponse('/login');
     *  B) For an API token authentication system, you return a 401 response
     *      return new Response('Auth header required', 401);
     *
     * @param Request                 $request       The request that resulted in an AuthenticationException
     * @param AuthenticationException $authException The exception that started the authentication process
     *
     * @return Response
     */
    public function start(Request $request, AuthenticationException $authException = null);
}

<?php

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

namespace Symfony\Component\Security\Http\EntryPoint;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

/**
 * Implement this interface for any classes that will be called to "start"
 * the authentication process (see method for more details).
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface AuthenticationEntryPointInterface
{
    /**
     * Returns a response that directs the user to authenticate.
     *
     * This is called when an anonymous request accesses a resource that
     * requires authentication. The job of this method is to return some
     * response that "helps" the user start into the authentication process.
     *
     * Examples:
     *
     * - For a form login, you might redirect to the login page
     *
     *     return new RedirectResponse('/login');
     *
     * - For an API token authentication system, you return a 401 response
     *
     *     return new Response('Auth header required', 401);
     *
     * @param Request                 $request       The request that resulted in an AuthenticationException
     * @param AuthenticationException $authException The exception that started the authentication process
     *
     * @return Response
     */
    public function start(Request $request, AuthenticationException $authException = null);
}

Fix code examples in PHPDoc

Fix code examples in PHPDoc


<?php

namespace PhalconUtils\Constants;

/**
 * Class ResponseCodes
 * @author Adeyemi Olaoye <yemi@cottacush.com>
 * @package App\Library
 */
class ResponseCodes
{
    const METHOD_NOT_IMPLEMENTED = 'method_not_implemented';
    const INTERNAL_SERVER_ERROR = 'internal_server_error';
    const UNEXPECTED_ERROR = 'unexpected_error';
    const AUTH_ERROR = 'authentication_error';
    const AUTH_ACCESS_TOKEN_REQUIRED = 'access_token_required';
    const INVALID_PARAMETERS = 'invalid_parameters';
}

<?php

namespace PhalconUtils\Constants;

/**
 * Class ResponseCodes
 * @author Adeyemi Olaoye <yemi@cottacush.com>
 * @package App\Library
 */
class ResponseCodes
{
    const METHOD_NOT_IMPLEMENTED = 'method_not_implemented';
    const INTERNAL_SERVER_ERROR = 'internal_server_error';
    const UNEXPECTED_ERROR = 'unexpected_error';
    const AUTH_ERROR = 'authentication_error';
    const AUTH_ACCESS_TOKEN_REQUIRED = 'access_token_required';
    const INVALID_PARAMETERS = 'invalid_parameters';
    const RECORD_NOT_FOUND = 'record_not_found';
}

Add undefined NOT FOUND response code

Fix: Add undefined NOT FOUND response code


<?php

/**
 * @file
 * Contains \Drupal\Console\Helper\HttpClientHelper.
 */

namespace Drupal\Console\Helper;

use Drupal\Console\Helper\Helper;
use GuzzleHttp\Client;

/**
 * Class HttpClientHelper
 * @package \Drupal\Console\Helper\HttpClientHelper
 */
class HttpClientHelper extends Helper
{
    public function downloadFile($url, $destination)
    {
        try {
            $this->getClient()->get($url, array('sink' => $destination));

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function getUrlAsString($url)
    {
        $response = $this->getClient()->get($url);

        if ($response->getStatusCode() == 200) {
            return (string) $response->getBody();
        }

        return null;
    }

    public function getHeader($url, $header)
    {
        $response = $this->getClient()->get($url);
        $headerContent = $response->getHeader($header);
        if (!empty($headerContent) && is_array($headerContent)) {
            return array_shift($headerContent);
        }

        return $headerContent;
    }

    private function getClient()
    {
        return new Client();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'httpClient';
    }
}

<?php

/**
 * @file
 * Contains \Drupal\Console\Helper\HttpClientHelper.
 */

namespace Drupal\Console\Helper;

use Drupal\Console\Helper\Helper;
use GuzzleHttp\Client;

/**
 * Class HttpClientHelper
 * @package \Drupal\Console\Helper\HttpClientHelper
 */
class HttpClientHelper extends Helper
{
    public function downloadFile($url, $destination)
    {
        $this->getClient()->get($url, array('sink' => $destination));

        return file_exists($destination);
    }

    public function getUrlAsString($url)
    {
        $response = $this->getClient()->get($url);

        if ($response->getStatusCode() == 200) {
            return (string) $response->getBody();
        }

        return null;
    }

    public function getHeader($url, $header)
    {
        $response = $this->getClient()->get($url);
        $headerContent = $response->getHeader($header);
        if (!empty($headerContent) && is_array($headerContent)) {
            return array_shift($headerContent);
        }

        return $headerContent;
    }

    private function getClient()
    {
        return new Client();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'httpClient';
    }
}

Remove try/catch to test TravisCI error

[console] Remove try/catch to test TravisCI error


<?php

namespace wcf\system\language\preload;

use wcf\data\language\Language;
use wcf\system\language\preload\command\CachePreloadPhrases;
use wcf\system\WCF;

/**
 * Provides the URL to the preload cache for
 * phrases and creates it if it is missing.
 *
 * @author Alexander Ebert
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Language\Preload
 * @since 6.0
 */
final class PhrasePreloader
{
    /**
     * Returns the URL to the preload cache. Will implicitly
     * create the cache if it does not exist.
     */
    public function getUrl(Language $language): string
    {
        if ($this->needsRebuild($language)) {
            $this->rebuild($language);
        }

        return \sprintf(
            '%s%s?v=%d',
            WCF::getPath(),
            $language->getPreloadCacheFilename(),
            \LAST_UPDATE_TIME
        );
    }

    private function needsRebuild(Language $language): bool
    {
        return \file_exists(\WCF_DIR . $language->getPreloadCacheFilename());
    }

    private function rebuild(Language $language): void
    {
        $command = new CachePreloadPhrases($language);
        $command();
    }
}

<?php

namespace wcf\system\language\preload;

use wcf\data\language\Language;
use wcf\system\language\preload\command\CachePreloadPhrases;
use wcf\system\WCF;

/**
 * Provides the URL to the preload cache for
 * phrases and creates it if it is missing.
 *
 * @author Alexander Ebert
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Language\Preload
 * @since 6.0
 */
final class PhrasePreloader
{
    /**
     * Returns the URL to the preload cache. Will implicitly
     * create the cache if it does not exist.
     */
    public function getUrl(Language $language): string
    {
        if (!$this->needsRebuild($language)) {
            $this->rebuild($language);
        }

        return \sprintf(
            '%s%s?v=%d',
            WCF::getPath(),
            $language->getPreloadCacheFilename(),
            \LAST_UPDATE_TIME
        );
    }

    private function needsRebuild(Language $language): bool
    {
        return \file_exists(\WCF_DIR . $language->getPreloadCacheFilename());
    }

    private function rebuild(Language $language): void
    {
        $command = new CachePreloadPhrases($language);
        $command();
    }
}

Fix the condition to rebuild the phrase cache


<?php

namespace Good\Rolemodel\Schema;

use Good\Rolemodel\SchemaVisitor;

class TextMember extends PrimitiveMember
{
    public function acceptSchemaVisitor(SchemaVisitor $visitor)
    {
        // visit this, there are no children to pass visitor on to
        $visitor->visitTextMember($this);
    }

    function getValidParameterTypeModifiers()
    {
        return array('minLength', 'maxLength', 'length');;
    }

    function getValidNonParameterTypeModifiers()
    {
        return array();
    }

    function processTypeModifiers(array $typeModifiers)
    {
        if (array_key_exists('length', $typeModifiers))
        {
            if (array_key_exists('minLength', $typeModifiers) ||
                array_key_exists('maxLength', $typeModifiers))
            {
                throw new \Exception("The 'length' type modifier cannot be defined alongside 'minLength' or 'maxLength'.");
            }

            $typeModifiers['minLength'] = $typeModifiers['length'];
            $typeModifiers['maxLength'] = $typeModifiers['length'];
            unset($typeModifiers['length']);
        }

        return $typeModifiers;
    }

    function getDefaultTypeModifierValues()
    {
        return array();
    }
}

?>

<?php

namespace Good\Rolemodel\Schema;

use Good\Rolemodel\SchemaVisitor;

class TextMember extends PrimitiveMember
{
    public function acceptSchemaVisitor(SchemaVisitor $visitor)
    {
        // visit this, there are no children to pass visitor on to
        $visitor->visitTextMember($this);
    }

    function getValidParameterTypeModifiers()
    {
        return array('minLength', 'maxLength', 'length');;
    }

    function getValidNonParameterTypeModifiers()
    {
        return array();
    }

    function processTypeModifiers(array $typeModifiers)
    {
        if (array_key_exists('length', $typeModifiers))
        {
            if (array_key_exists('minLength', $typeModifiers) ||
                array_key_exists('maxLength', $typeModifiers))
            {
                throw new \Exception("The 'length' type modifier cannot be defined alongside 'minLength' or 'maxLength'.");
            }

            if ($typeModifiers['length'] < 0)
            {
                throw new \Exception("The length for a text must be positive");
            }

            $typeModifiers['minLength'] = $typeModifiers['length'];
            $typeModifiers['maxLength'] = $typeModifiers['length'];
            unset($typeModifiers['length']);
        }

        if (array_key_exists('minLength', $typeModifiers) &&
            array_key_exists('maxLength', $typeModifiers) &&
            $typeModifiers['minLength'] > $typeModifiers['maxLength'])
        {
            throw new \Exception("The minLength for a text cannot be higher than its maxLength");
        }

        if ((array_key_exists('minLength', $typeModifiers) && $typeModifiers['minLength'] < 0) ||
            (array_key_exists('maxLength', $typeModifiers) && $typeModifiers['maxLength'] < 0))
        {
            throw new \Exception("The minLength and maxLength for a text must be positive");
        }

        return $typeModifiers;
    }

    function getDefaultTypeModifierValues()
    {
        return array('minLength' => 0);
    }
}

?>

Add additional processing on text type modifiers

- minLength cannot be higher than maxLength

- minLength, maxLength and length cannot be negative

- minLength defaults to 0


<?php

CroogoCache::config('contacts_view', array_merge(
	Configure::read('Cache.defaultConfig'),
	array('groups' => array('contacts'))
));

CroogoNav::add('contacts', array(
	'icon' => array('comments', 'large'),
	'title' => __d('croogo', 'Contacts'),
	'url' => array(
		'admin' => true,
		'plugin' => 'contacts',
		'controller' => 'contacts',
		'action' => 'index',
	),
	'weight' => 50,
	'children' => array(
		'attachments' => array(
			'title' => __d('croogo', 'Contacts'),
			'url' => array(
				'admin' => true,
				'plugin' => 'contacts',
				'controller' => 'contacts',
				'action' => 'index',
			),
		),
		'file_manager' => array(
			'title' => __d('croogo', 'Messages'),
			'url' => array(
				'admin' => true,
				'plugin' => 'contacts',
				'controller' => 'messages',
				'action' => 'index',
			),
		),
	),
));

<?php

CroogoCache::config('contacts_view', array_merge(
	Configure::read('Cache.defaultConfig'),
	array('groups' => array('contacts'))
));

CroogoNav::add('contacts', array(
	'icon' => array('comments', 'large'),
	'title' => __d('croogo', 'Contacts'),
	'url' => array(
		'admin' => true,
		'plugin' => 'contacts',
		'controller' => 'contacts',
		'action' => 'index',
	),
	'weight' => 50,
	'children' => array(
		'contacts' => array(
			'title' => __d('croogo', 'Contacts'),
			'url' => array(
				'admin' => true,
				'plugin' => 'contacts',
				'controller' => 'contacts',
				'action' => 'index',
			),
		),
		'messages' => array(
			'title' => __d('croogo', 'Messages'),
			'url' => array(
				'admin' => true,
				'plugin' => 'contacts',
				'controller' => 'messages',
				'action' => 'index',
			),
		),
	),
));

Use appropriate value for menu name

Contacts: Use appropriate value for menu name


<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AuthenticateBasic
{
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	function handle ($request, Closure $next)
	{
		return Auth::onceBasic() ?: $next($request);
	}
}

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Symfony\Component\HttpKernel\Exception\HttpException;

class AuthenticateBasic
{
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	function handle ($request, Closure $next)
	{
		if (Auth::onceBasic())
		{
			throw new HttpException(401, 'Invalid credentials.');
		}

		return $next($request);
	}
}

Add JSON response to basic auth middleware.


<?php

namespace Luminary\Services\ApiRequest\Content;

class Content
{
    /**
     * The request body content
     *
     * @var array
     */
    protected $content;

    /**
     * Content constructor.
     *
     * @param array $content
     */
    public function __construct(array $content)
    {
        $this->content = $content;
    }

    /**
     * Get the attributes from an request
     *
     * @return array
     */
    public function attributes() :array
    {
        $attributes = array_get($this->content, 'data.attributes', []);

        if ($id = array_get($this->content, 'data.id')) {
            $attributes = array_add($attributes, 'id', $id);
        }

        return $attributes;
    }

    /**
     * Set the relationships from a request
     *
     * @return array
     */
    public function relationships() :array
    {
        $relationships = array_get($this->content, 'data.relationships', []) ?: [];
        $relationships = collect($relationships)->map(
            function ($values) {
                $data = array_get($values, 'data');
                $id = array_get($data, 'id');

                return is_null($id) ? array_pluck($data, 'id') : $id;
            }
        )->toArray();

        return $relationships;
    }

    /**
     * Set the document type from request
     *
     * @return string
     */
    public function type() :string
    {
        return array_get($this->content, 'data.type', '');
    }
}

<?php

namespace Luminary\Services\ApiRequest\Content;

class Content
{
    /**
     * The request body content
     *
     * @var array
     */
    protected $content;

    /**
     * Content constructor.
     *
     * @param array $content
     */
    public function __construct(array $content)
    {
        $this->content = $content;
    }

    /**
     * Get the attributes from an request
     *
     * @return array
     */
    public function attributes() :array
    {
        $attributes = array_get($this->content, 'data.attributes', []);

        if ($id = array_get($this->content, 'data.id')) {
            $attributes = array_add($attributes, 'id', $id);
        }

        return $attributes;
    }

    /**
     * Set the relationships from a request
     *
     * @return array
     */
    public function relationships() :array
    {
        $relationships = array_get($this->content, 'data.relationships', []) ?: [];
        $relationships = collect($relationships)->map(
            function ($values) {
                $data = array_get($values, 'data');
                $id = array_get($data, 'id');

                return is_null($id) ? array_pluck($data, 'id') : $id;
            }
        )->toArray();

        $keys = array_map(function($key) {
            return camel_case($key);
        }, array_keys($relationships));

        return array_combine($keys, array_values($relationships));
    }

    /**
     * Set the document type from request
     *
     * @return string
     */
    public function type() :string
    {
        return array_get($this->content, 'data.type', '');
    }
}

Fix for relationships with dashes on POST|PUT


<?php

namespace App\Shared\Middleware;

/**
 * Aura router classes
 */
use Aura\Router\Matcher;

/**
 * PSR-7 interfaces
 * @see http://www.php-fig.org/psr/psr-7/
 */
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Own classes and interfaces
 */
use App\Shared\Behaviour\Middleware\AuraSuccessHandlingTrait;
use App\Shared\Behaviour\Middleware\AuraFailureHandlingTrait;

/**
 * Class Router
 * @package App\Shared\Middleware
 * @author Petr Pliska <petr.pliska@post.cz>
 */
class Router implements MiddlewareInterface
{
    /**
     * Handle unmatche route
     */
    use AuraFailureHandlingTrait;

    /**
     * Handle matched route
     */
    use AuraSuccessHandlingTrait;

    /**
     * @inject
     * @var Matcher
     */
    protected $matcher;

    /**
     * @inject
     * @var Dispatcher
     */
    protected $dispatcher;

    /**
     * @inheritdoc
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
    {
        // If no route is matcher
        if (! $route = $this->matcher->match($request)) {
            $this->handleFailure($this->matcher);
        }

        return $this->handleSuccess($route, $request->withAttribute('route', $route), $response, $next);
    }
}

<?php

namespace App\Shared\Middleware;

/**
 * Aura router classes
 */
use Aura\Router\Matcher;

/**
 * PSR-7 interfaces
 * @see http://www.php-fig.org/psr/psr-7/
 */
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Own classes and interfaces
 */
use App\Shared\Behaviour\Middleware\AuraSuccessHandlingTrait;
use App\Shared\Behaviour\Middleware\AuraFailureHandlingTrait;

/**
 * Class Router
 * @package App\Shared\Middleware
 * @author Petr Pliska <petr.pliska@post.cz>
 */
class Router implements MiddlewareInterface
{
    /**
     * Handle unmatche route
     */
    use AuraFailureHandlingTrait;

    /**
     * Handle matched route
     */
    use AuraSuccessHandlingTrait;

    /**
     * @var Matcher
     */
    protected $matcher;

    /**
     * @var Dispatcher
     */
    protected $dispatcher;

    /**
     * Router constructor.
     * @param Matcher $matcher
     */
    public function __construct(Matcher $matcher, Dispatcher $dispatcher)
    {
        $this->matcher = $matcher;
        $this->dispatcher = $dispatcher;
    }

    /**
     * @inheritdoc
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
    {
        // If no route is matcher
        if (! $route = $this->matcher->match($request)) {
            $this->handleFailure($this->matcher);
        }

        return $this->handleSuccess($route, $request->withAttribute('route', $route), $response, $next);
    }
}

Rewrite annotations to constructor injection


<?php

namespace jvwp\common;

class Ajax
{

    const WP_AJAX_HOOK_PREFIX = 'wp_ajax_';

    /**
     * Gets the action hook string to use, based on the action name that was provided
     *
     * @param string $action
     *
     * @return string
     */
    public static function getHook ($action)
    {
        return self::WP_AJAX_HOOK_PREFIX . $action;
    }

    /**
     * Normalizes the string to use in an action name, making the string lowercase and replacing every instance of a
     * non-word and non-digit character with an underscore
     *
     * @param $actionName
     *
     * @return mixed
     */
    public static function normalizeActionName ($actionName)
    {
        return preg_replace('/[^\w\d]+/', '_', strtolower($actionName));
    }
}

<?php

namespace jvwp\common;

class Ajax
{

    const WP_AJAX_HOOK_PREFIX = 'wp_ajax_';

    /**
     * Gets the action hook string to use, based on the action name that was provided
     *
     * @param string $action
     *
     * @return string
     */
    public static function getHook ($action)
    {
        return self::WP_AJAX_HOOK_PREFIX . $action;
    }

    /**
     * Normalizes the string to use in an action name, making the string lowercase and replacing every instance of a
     * non-word and non-digit character with an underscore
     *
     * @param $actionName
     *
     * @return string
     */
    public static function normalizeActionName ($actionName)
    {
        return preg_replace('/[^\w\d]+/', '_', strtolower($actionName));
    }
}

Fix return type in documentation

Fix return type in documentation


<?php namespace App;
/**
 * Application data persistence configuration
 */

$db = array();
$db['enable'] = true;
$db['driver'] = 'mysql';
$db['host'] = '127.0.0.1';
$db['name'] = 'mvcfam';
$db['user'] = 'root';
$db['pass'] = '2ws3ed';

return $db;

<?php namespace App;
/**
 * Application data persistence configuration
 */

$db = array();
$db['enable'] = !!$_ENV['DB_ENABLED'];
$db['driver'] = $_ENV['DB_DRIVER'];
$db['host'] = $_ENV['DB_HOST'];
$db['name'] = $_ENV['DB_NAME'];
$db['user'] = $_ENV['DB_USER'];
$db['pass'] = $_ENV['DB_PASS'];

return $db;

Update database config file to use ENV superglobal